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