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