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