static_inst.hh revision 1061
1/*
2 * Copyright (c) 2003-2004 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#ifndef __STATIC_INST_HH__
30#define __STATIC_INST_HH__
31
32#include <bitset>
33#include <string>
34
35#include "sim/host.hh"
36#include "base/hashmap.hh"
37#include "base/refcnt.hh"
38
39#include "cpu/full_cpu/op_class.hh"
40#include "targetarch/isa_traits.hh"
41
42// forward declarations
43struct AlphaSimpleImpl;
44class ExecContext;
45class DynInst;
46template <class Impl>
47class AlphaDynInst;
48
49class FastCPU;
50class SimpleCPU;
51class SymbolTable;
52
53namespace Trace {
54    class InstRecord;
55}
56
57/**
58 * Base, ISA-independent static instruction class.
59 *
60 * The main component of this class is the vector of flags and the
61 * associated methods for reading them.  Any object that can rely
62 * solely on these flags can process instructions without being
63 * recompiled for multiple ISAs.
64 */
65class StaticInstBase : public RefCounted
66{
67  protected:
68
69    /// Set of boolean static instruction properties.
70    ///
71    /// Notes:
72    /// - The IsInteger and IsFloating flags are based on the class of
73    /// registers accessed by the instruction.  Although most
74    /// instructions will have exactly one of these two flags set, it
75    /// is possible for an instruction to have neither (e.g., direct
76    /// unconditional branches, memory barriers) or both (e.g., an
77    /// FP/int conversion).
78    /// - If IsMemRef is set, then exactly one of IsLoad or IsStore
79    /// will be set.
80    /// - If IsControl is set, then exactly one of IsDirectControl or
81    /// IsIndirect Control will be set, and exactly one of
82    /// IsCondControl or IsUncondControl will be set.
83    /// - IsSerializing, IsMemBarrier, and IsWriteBarrier are
84    /// implemented as flags since in the current model there's no
85    /// other way for instructions to inject behavior into the
86    /// pipeline outside of fetch.  Once we go to an exec-in-exec CPU
87    /// model we should be able to get rid of these flags and
88    /// implement this behavior via the execute() methods.
89    ///
90    enum Flags {
91        IsNop,		///< Is a no-op (no effect at all).
92
93        IsInteger,	///< References integer regs.
94        IsFloating,	///< References FP regs.
95
96        IsMemRef,	///< References memory (load, store, or prefetch).
97        IsLoad,		///< Reads from memory (load or prefetch).
98        IsStore,	///< Writes to memory.
99        IsInstPrefetch,	///< Instruction-cache prefetch.
100        IsDataPrefetch,	///< Data-cache prefetch.
101        IsCopy,         ///< Fast Cache block copy
102
103        IsControl,		///< Control transfer instruction.
104        IsDirectControl,	///< PC relative control transfer.
105        IsIndirectControl,	///< Register indirect control transfer.
106        IsCondControl,		///< Conditional control transfer.
107        IsUncondControl,	///< Unconditional control transfer.
108        IsCall,			///< Subroutine call.
109        IsReturn,		///< Subroutine return.
110
111        IsThreadSync,	///< Thread synchronization operation.
112
113        IsSerializing,	///< Serializes pipeline: won't execute until all
114                        /// older instructions have committed.
115        IsMemBarrier,	///< Is a memory barrier
116        IsWriteBarrier,	///< Is a write barrier
117
118        IsNonSpeculative, ///< Should not be executed speculatively
119
120        NumFlags
121    };
122
123    /// Flag values for this instruction.
124    std::bitset<NumFlags> flags;
125
126    /// See opClass().
127    OpClass _opClass;
128
129    /// See numSrcRegs().
130    int8_t _numSrcRegs;
131
132    /// See numDestRegs().
133    int8_t _numDestRegs;
134
135    /// The following are used to track physical register usage
136    /// for machines with separate int & FP reg files.
137    //@{
138    int8_t _numFPDestRegs;
139    int8_t _numIntDestRegs;
140    //@}
141
142    /// Constructor.
143    /// It's important to initialize everything here to a sane
144    /// default, since the decoder generally only overrides
145    /// the fields that are meaningful for the particular
146    /// instruction.
147    StaticInstBase(OpClass __opClass)
148        : _opClass(__opClass), _numSrcRegs(0), _numDestRegs(0),
149          _numFPDestRegs(0), _numIntDestRegs(0)
150    {
151    }
152
153  public:
154
155    /// @name Register information.
156    /// The sum of numFPDestRegs() and numIntDestRegs() equals
157    /// numDestRegs().  The former two functions are used to track
158    /// physical register usage for machines with separate int & FP
159    /// reg files.
160    //@{
161    /// Number of source registers.
162    int8_t numSrcRegs()  const { return _numSrcRegs; }
163    /// Number of destination registers.
164    int8_t numDestRegs() const { return _numDestRegs; }
165    /// Number of floating-point destination regs.
166    int8_t numFPDestRegs()  const { return _numFPDestRegs; }
167    /// Number of integer destination regs.
168    int8_t numIntDestRegs() const { return _numIntDestRegs; }
169    //@}
170
171    /// @name Flag accessors.
172    /// These functions are used to access the values of the various
173    /// instruction property flags.  See StaticInstBase::Flags for descriptions
174    /// of the individual flags.
175    //@{
176
177    bool isNop() 	  const { return flags[IsNop]; }
178
179    bool isMemRef()    	  const { return flags[IsMemRef]; }
180    bool isLoad()	  const { return flags[IsLoad]; }
181    bool isStore()	  const { return flags[IsStore]; }
182    bool isInstPrefetch() const { return flags[IsInstPrefetch]; }
183    bool isDataPrefetch() const { return flags[IsDataPrefetch]; }
184    bool isCopy()         const { return flags[IsCopy];}
185
186    bool isInteger()	  const { return flags[IsInteger]; }
187    bool isFloating()	  const { return flags[IsFloating]; }
188
189    bool isControl()	  const { return flags[IsControl]; }
190    bool isCall()	  const { return flags[IsCall]; }
191    bool isReturn()	  const { return flags[IsReturn]; }
192    bool isDirectCtrl()	  const { return flags[IsDirectControl]; }
193    bool isIndirectCtrl() const { return flags[IsIndirectControl]; }
194    bool isCondCtrl()	  const { return flags[IsCondControl]; }
195    bool isUncondCtrl()	  const { return flags[IsUncondControl]; }
196
197    bool isThreadSync()   const { return flags[IsThreadSync]; }
198    bool isSerializing()  const { return flags[IsSerializing]; }
199    bool isMemBarrier()   const { return flags[IsMemBarrier]; }
200    bool isWriteBarrier() const { return flags[IsWriteBarrier]; }
201    bool isNonSpeculative() const { return flags[IsNonSpeculative]; }
202    //@}
203
204    /// Operation class.  Used to select appropriate function unit in issue.
205    OpClass opClass()     const { return _opClass; }
206};
207
208
209// forward declaration
210template <class ISA>
211class StaticInstPtr;
212
213/**
214 * Generic yet ISA-dependent static instruction class.
215 *
216 * This class builds on StaticInstBase, defining fields and interfaces
217 * that are generic across all ISAs but that differ in details
218 * according to the specific ISA being used.
219 */
220template <class ISA>
221class StaticInst : public StaticInstBase
222{
223  public:
224
225    /// Binary machine instruction type.
226    typedef typename ISA::MachInst MachInst;
227    /// Memory address type.
228    typedef typename ISA::Addr	   Addr;
229    /// Logical register index type.
230    typedef typename ISA::RegIndex RegIndex;
231
232    enum {
233        MaxInstSrcRegs = ISA::MaxInstSrcRegs,	//< Max source regs
234        MaxInstDestRegs = ISA::MaxInstDestRegs,	//< Max dest regs
235    };
236
237
238    /// Return logical index (architectural reg num) of i'th destination reg.
239    /// Only the entries from 0 through numDestRegs()-1 are valid.
240    RegIndex destRegIdx(int i) const { return _destRegIdx[i]; }
241
242    /// Return logical index (architectural reg num) of i'th source reg.
243    /// Only the entries from 0 through numSrcRegs()-1 are valid.
244    RegIndex srcRegIdx(int i)  const { return _srcRegIdx[i]; }
245
246    /// Pointer to a statically allocated "null" instruction object.
247    /// Used to give eaCompInst() and memAccInst() something to return
248    /// when called on non-memory instructions.
249    static StaticInstPtr<ISA> nullStaticInstPtr;
250
251    /**
252     * Memory references only: returns "fake" instruction representing
253     * the effective address part of the memory operation.  Used to
254     * obtain the dependence info (numSrcRegs and srcRegIdx[]) for
255     * just the EA computation.
256     */
257    virtual const
258    StaticInstPtr<ISA> &eaCompInst() const { return nullStaticInstPtr; }
259
260    /**
261     * Memory references only: returns "fake" instruction representing
262     * the memory access part of the memory operation.  Used to
263     * obtain the dependence info (numSrcRegs and srcRegIdx[]) for
264     * just the memory access (not the EA computation).
265     */
266    virtual const
267    StaticInstPtr<ISA> &memAccInst() const { return nullStaticInstPtr; }
268
269    /// The binary machine instruction.
270    const MachInst machInst;
271
272  protected:
273
274    /// See destRegIdx().
275    RegIndex _destRegIdx[MaxInstDestRegs];
276    /// See srcRegIdx().
277    RegIndex _srcRegIdx[MaxInstSrcRegs];
278
279    /**
280     * Base mnemonic (e.g., "add").  Used by generateDisassembly()
281     * methods.  Also useful to readily identify instructions from
282     * within the debugger when #cachedDisassembly has not been
283     * initialized.
284     */
285    const char *mnemonic;
286
287    /**
288     * String representation of disassembly (lazily evaluated via
289     * disassemble()).
290     */
291    std::string *cachedDisassembly;
292
293    /**
294     * Internal function to generate disassembly string.
295     */
296    virtual std::string generateDisassembly(Addr pc,
297                                            const SymbolTable *symtab) = 0;
298
299    /// Constructor.
300    StaticInst(const char *_mnemonic, MachInst _machInst, OpClass __opClass)
301        : StaticInstBase(__opClass),
302          machInst(_machInst), mnemonic(_mnemonic), cachedDisassembly(0)
303    {
304    }
305
306  public:
307
308    virtual ~StaticInst()
309    {
310        if (cachedDisassembly)
311            delete cachedDisassembly;
312    }
313
314#include "static_inst_impl.hh"
315
316    /**
317     * Return the target address for a PC-relative branch.
318     * Invalid if not a PC-relative branch (i.e. isDirectCtrl()
319     * should be true).
320     */
321    virtual Addr branchTarget(Addr branchPC) const
322    {
323        panic("StaticInst::branchTarget() called on instruction "
324              "that is not a PC-relative branch.");
325    }
326
327    /**
328     * Return the target address for an indirect branch (jump).  The
329     * register value is read from the supplied execution context, so
330     * the result is valid only if the execution context is about to
331     * execute the branch in question.  Invalid if not an indirect
332     * branch (i.e. isIndirectCtrl() should be true).
333     */
334    virtual Addr branchTarget(ExecContext *xc) const
335    {
336        panic("StaticInst::branchTarget() called on instruction "
337              "that is not an indirect branch.");
338    }
339
340    /**
341     * Return true if the instruction is a control transfer, and if so,
342     * return the target address as well.
343     */
344    bool hasBranchTarget(Addr pc, ExecContext *xc, Addr &tgt);
345
346    /**
347     * Return string representation of disassembled instruction.
348     * The default version of this function will call the internal
349     * virtual generateDisassembly() function to get the string,
350     * then cache it in #cachedDisassembly.  If the disassembly
351     * should not be cached, this function should be overridden directly.
352     */
353    virtual const std::string &disassemble(Addr pc,
354                                           const SymbolTable *symtab = 0)
355    {
356        if (!cachedDisassembly)
357            cachedDisassembly =
358                new std::string(generateDisassembly(pc, symtab));
359
360        return *cachedDisassembly;
361    }
362
363    /// Decoded instruction cache type.
364    /// For now we're using a generic hash_map; this seems to work
365    /// pretty well.
366    typedef m5::hash_map<MachInst, StaticInstPtr<ISA> > DecodeCache;
367
368    /// A cache of decoded instruction objects.
369    static DecodeCache decodeCache;
370
371    /**
372     * Dump some basic stats on the decode cache hash map.
373     * Only gets called if DECODE_CACHE_HASH_STATS is defined.
374     */
375    static void dumpDecodeCacheStats();
376
377    /// Decode a machine instruction.
378    /// @param mach_inst The binary instruction to decode.
379    /// @retval A pointer to the corresponding StaticInst object.
380    static
381    StaticInstPtr<ISA> decode(MachInst mach_inst)
382    {
383#ifdef DECODE_CACHE_HASH_STATS
384        // Simple stats on decode hash_map.  Turns out the default
385        // hash function is as good as anything I could come up with.
386        const int dump_every_n = 10000000;
387        static int decodes_til_dump = dump_every_n;
388
389        if (--decodes_til_dump == 0) {
390            dumpDecodeCacheStats();
391            decodes_til_dump = dump_every_n;
392        }
393#endif
394
395        typename DecodeCache::iterator iter = decodeCache.find(mach_inst);
396        if (iter != decodeCache.end()) {
397            return iter->second;
398        }
399
400        StaticInstPtr<ISA> si = ISA::decodeInst(mach_inst);
401        decodeCache[mach_inst] = si;
402        return si;
403    }
404};
405
406typedef RefCountingPtr<StaticInstBase> StaticInstBasePtr;
407
408/// Reference-counted pointer to a StaticInst object.
409/// This type should be used instead of "StaticInst<ISA> *" so that
410/// StaticInst objects can be properly reference-counted.
411template <class ISA>
412class StaticInstPtr : public RefCountingPtr<StaticInst<ISA> >
413{
414  public:
415    /// Constructor.
416    StaticInstPtr()
417        : RefCountingPtr<StaticInst<ISA> >()
418    {
419    }
420
421    /// Conversion from "StaticInst<ISA> *".
422    StaticInstPtr(StaticInst<ISA> *p)
423        : RefCountingPtr<StaticInst<ISA> >(p)
424    {
425    }
426
427    /// Copy constructor.
428    StaticInstPtr(const StaticInstPtr &r)
429        : RefCountingPtr<StaticInst<ISA> >(r)
430    {
431    }
432
433    /// Construct directly from machine instruction.
434    /// Calls StaticInst<ISA>::decode().
435    StaticInstPtr(typename ISA::MachInst mach_inst)
436        : RefCountingPtr<StaticInst<ISA> >(StaticInst<ISA>::decode(mach_inst))
437    {
438    }
439
440    /// Convert to pointer to StaticInstBase class.
441    operator const StaticInstBasePtr()
442    {
443        return get();
444    }
445};
446
447#endif // __STATIC_INST_HH__
448