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