base_dyn_inst.hh revision 12106
1/*
2 * Copyright (c) 2011,2013 ARM Limited
3 * Copyright (c) 2013 Advanced Micro Devices, Inc.
4 * All rights reserved.
5 *
6 * The license below extends only to copyright in the software and shall
7 * not be construed as granting a license to any other intellectual
8 * property including but not limited to intellectual property relating
9 * to a hardware implementation of the functionality of the software
10 * licensed hereunder.  You may use the software subject to the license
11 * terms below provided that you ensure that this notice is replicated
12 * unmodified and in its entirety in all distributions of the software,
13 * modified or unmodified, in source code or in binary form.
14 *
15 * Copyright (c) 2004-2006 The Regents of The University of Michigan
16 * Copyright (c) 2009 The University of Edinburgh
17 * All rights reserved.
18 *
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions are
21 * met: redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimer;
23 * redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution;
26 * neither the name of the copyright holders nor the names of its
27 * contributors may be used to endorse or promote products derived from
28 * this software without specific prior written permission.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
31 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
32 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
33 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
34 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
36 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
40 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 *
42 * Authors: Kevin Lim
43 *          Timothy M. Jones
44 */
45
46#ifndef __CPU_BASE_DYN_INST_HH__
47#define __CPU_BASE_DYN_INST_HH__
48
49#include <array>
50#include <bitset>
51#include <list>
52#include <string>
53#include <queue>
54
55#include "arch/generic/tlb.hh"
56#include "arch/utility.hh"
57#include "base/trace.hh"
58#include "config/the_isa.hh"
59#include "cpu/checker/cpu.hh"
60#include "cpu/o3/comm.hh"
61#include "cpu/exec_context.hh"
62#include "cpu/exetrace.hh"
63#include "cpu/inst_seq.hh"
64#include "cpu/op_class.hh"
65#include "cpu/static_inst.hh"
66#include "cpu/translation.hh"
67#include "mem/packet.hh"
68#include "mem/request.hh"
69#include "sim/byteswap.hh"
70#include "sim/system.hh"
71
72/**
73 * @file
74 * Defines a dynamic instruction context.
75 */
76
77template <class Impl>
78class BaseDynInst : public ExecContext, public RefCounted
79{
80  public:
81    // Typedef for the CPU.
82    typedef typename Impl::CPUType ImplCPU;
83    typedef typename ImplCPU::ImplState ImplState;
84
85    // The DynInstPtr type.
86    typedef typename Impl::DynInstPtr DynInstPtr;
87    typedef RefCountingPtr<BaseDynInst<Impl> > BaseDynInstPtr;
88
89    // The list of instructions iterator type.
90    typedef typename std::list<DynInstPtr>::iterator ListIt;
91
92    enum {
93        MaxInstSrcRegs = TheISA::MaxInstSrcRegs,        /// Max source regs
94        MaxInstDestRegs = TheISA::MaxInstDestRegs       /// Max dest regs
95    };
96
97    union Result {
98        uint64_t integer;
99        double dbl;
100        void set(uint64_t i) { integer = i; }
101        void set(double d) { dbl = d; }
102        void get(uint64_t& i) { i = integer; }
103        void get(double& d) { d = dbl; }
104    };
105
106  protected:
107    enum Status {
108        IqEntry,                 /// Instruction is in the IQ
109        RobEntry,                /// Instruction is in the ROB
110        LsqEntry,                /// Instruction is in the LSQ
111        Completed,               /// Instruction has completed
112        ResultReady,             /// Instruction has its result
113        CanIssue,                /// Instruction can issue and execute
114        Issued,                  /// Instruction has issued
115        Executed,                /// Instruction has executed
116        CanCommit,               /// Instruction can commit
117        AtCommit,                /// Instruction has reached commit
118        Committed,               /// Instruction has committed
119        Squashed,                /// Instruction is squashed
120        SquashedInIQ,            /// Instruction is squashed in the IQ
121        SquashedInLSQ,           /// Instruction is squashed in the LSQ
122        SquashedInROB,           /// Instruction is squashed in the ROB
123        RecoverInst,             /// Is a recover instruction
124        BlockingInst,            /// Is a blocking instruction
125        ThreadsyncWait,          /// Is a thread synchronization instruction
126        SerializeBefore,         /// Needs to serialize on
127                                 /// instructions ahead of it
128        SerializeAfter,          /// Needs to serialize instructions behind it
129        SerializeHandled,        /// Serialization has been handled
130        NumStatus
131    };
132
133    enum Flags {
134        TranslationStarted,
135        TranslationCompleted,
136        PossibleLoadViolation,
137        HitExternalSnoop,
138        EffAddrValid,
139        RecordResult,
140        Predicate,
141        PredTaken,
142        /** Whether or not the effective address calculation is completed.
143         *  @todo: Consider if this is necessary or not.
144         */
145        EACalcDone,
146        IsStrictlyOrdered,
147        ReqMade,
148        MemOpDone,
149        MaxFlags
150    };
151
152  public:
153    /** The sequence number of the instruction. */
154    InstSeqNum seqNum;
155
156    /** The StaticInst used by this BaseDynInst. */
157    const StaticInstPtr staticInst;
158
159    /** Pointer to the Impl's CPU object. */
160    ImplCPU *cpu;
161
162    BaseCPU *getCpuPtr() { return cpu; }
163
164    /** Pointer to the thread state. */
165    ImplState *thread;
166
167    /** The kind of fault this instruction has generated. */
168    Fault fault;
169
170    /** InstRecord that tracks this instructions. */
171    Trace::InstRecord *traceData;
172
173  protected:
174    /** The result of the instruction; assumes an instruction can have many
175     *  destination registers.
176     */
177    std::queue<Result> instResult;
178
179    /** PC state for this instruction. */
180    TheISA::PCState pc;
181
182    /* An amalgamation of a lot of boolean values into one */
183    std::bitset<MaxFlags> instFlags;
184
185    /** The status of this BaseDynInst.  Several bits can be set. */
186    std::bitset<NumStatus> status;
187
188     /** Whether or not the source register is ready.
189     *  @todo: Not sure this should be here vs the derived class.
190     */
191    std::bitset<MaxInstSrcRegs> _readySrcRegIdx;
192
193  public:
194    /** The thread this instruction is from. */
195    ThreadID threadNumber;
196
197    /** Iterator pointing to this BaseDynInst in the list of all insts. */
198    ListIt instListIt;
199
200    ////////////////////// Branch Data ///////////////
201    /** Predicted PC state after this instruction. */
202    TheISA::PCState predPC;
203
204    /** The Macroop if one exists */
205    const StaticInstPtr macroop;
206
207    /** How many source registers are ready. */
208    uint8_t readyRegs;
209
210  public:
211    /////////////////////// Load Store Data //////////////////////
212    /** The effective virtual address (lds & stores only). */
213    Addr effAddr;
214
215    /** The effective physical address. */
216    Addr physEffAddrLow;
217
218    /** The effective physical address
219     *  of the second request for a split request
220     */
221    Addr physEffAddrHigh;
222
223    /** The memory request flags (from translation). */
224    unsigned memReqFlags;
225
226    /** data address space ID, for loads & stores. */
227    short asid;
228
229    /** The size of the request */
230    uint8_t effSize;
231
232    /** Pointer to the data for the memory access. */
233    uint8_t *memData;
234
235    /** Load queue index. */
236    int16_t lqIdx;
237
238    /** Store queue index. */
239    int16_t sqIdx;
240
241
242    /////////////////////// TLB Miss //////////////////////
243    /**
244     * Saved memory requests (needed when the DTB address translation is
245     * delayed due to a hw page table walk).
246     */
247    RequestPtr savedReq;
248    RequestPtr savedSreqLow;
249    RequestPtr savedSreqHigh;
250
251    /////////////////////// Checker //////////////////////
252    // Need a copy of main request pointer to verify on writes.
253    RequestPtr reqToVerify;
254
255  private:
256    /** Instruction effective address.
257     *  @todo: Consider if this is necessary or not.
258     */
259    Addr instEffAddr;
260
261  protected:
262    /** Flattened register index of the destination registers of this
263     *  instruction.
264     */
265    std::array<RegId, TheISA::MaxInstDestRegs> _flatDestRegIdx;
266
267    /** Physical register index of the destination registers of this
268     *  instruction.
269     */
270    std::array<PhysRegIdPtr, TheISA::MaxInstDestRegs> _destRegIdx;
271
272    /** Physical register index of the source registers of this
273     *  instruction.
274     */
275    std::array<PhysRegIdPtr, TheISA::MaxInstSrcRegs> _srcRegIdx;
276
277    /** Physical register index of the previous producers of the
278     *  architected destinations.
279     */
280    std::array<PhysRegIdPtr, TheISA::MaxInstDestRegs> _prevDestRegIdx;
281
282
283  public:
284    /** Records changes to result? */
285    void recordResult(bool f) { instFlags[RecordResult] = f; }
286
287    /** Is the effective virtual address valid. */
288    bool effAddrValid() const { return instFlags[EffAddrValid]; }
289
290    /** Whether or not the memory operation is done. */
291    bool memOpDone() const { return instFlags[MemOpDone]; }
292    void memOpDone(bool f) { instFlags[MemOpDone] = f; }
293
294
295    ////////////////////////////////////////////
296    //
297    // INSTRUCTION EXECUTION
298    //
299    ////////////////////////////////////////////
300
301    void demapPage(Addr vaddr, uint64_t asn)
302    {
303        cpu->demapPage(vaddr, asn);
304    }
305    void demapInstPage(Addr vaddr, uint64_t asn)
306    {
307        cpu->demapPage(vaddr, asn);
308    }
309    void demapDataPage(Addr vaddr, uint64_t asn)
310    {
311        cpu->demapPage(vaddr, asn);
312    }
313
314    Fault initiateMemRead(Addr addr, unsigned size, Request::Flags flags);
315
316    Fault writeMem(uint8_t *data, unsigned size, Addr addr,
317                   Request::Flags flags, uint64_t *res);
318
319    /** Splits a request in two if it crosses a dcache block. */
320    void splitRequest(RequestPtr req, RequestPtr &sreqLow,
321                      RequestPtr &sreqHigh);
322
323    /** Initiate a DTB address translation. */
324    void initiateTranslation(RequestPtr req, RequestPtr sreqLow,
325                             RequestPtr sreqHigh, uint64_t *res,
326                             BaseTLB::Mode mode);
327
328    /** Finish a DTB address translation. */
329    void finishTranslation(WholeTranslationState *state);
330
331    /** True if the DTB address translation has started. */
332    bool translationStarted() const { return instFlags[TranslationStarted]; }
333    void translationStarted(bool f) { instFlags[TranslationStarted] = f; }
334
335    /** True if the DTB address translation has completed. */
336    bool translationCompleted() const { return instFlags[TranslationCompleted]; }
337    void translationCompleted(bool f) { instFlags[TranslationCompleted] = f; }
338
339    /** True if this address was found to match a previous load and they issued
340     * out of order. If that happend, then it's only a problem if an incoming
341     * snoop invalidate modifies the line, in which case we need to squash.
342     * If nothing modified the line the order doesn't matter.
343     */
344    bool possibleLoadViolation() const { return instFlags[PossibleLoadViolation]; }
345    void possibleLoadViolation(bool f) { instFlags[PossibleLoadViolation] = f; }
346
347    /** True if the address hit a external snoop while sitting in the LSQ.
348     * If this is true and a older instruction sees it, this instruction must
349     * reexecute
350     */
351    bool hitExternalSnoop() const { return instFlags[HitExternalSnoop]; }
352    void hitExternalSnoop(bool f) { instFlags[HitExternalSnoop] = f; }
353
354    /**
355     * Returns true if the DTB address translation is being delayed due to a hw
356     * page table walk.
357     */
358    bool isTranslationDelayed() const
359    {
360        return (translationStarted() && !translationCompleted());
361    }
362
363  public:
364#ifdef DEBUG
365    void dumpSNList();
366#endif
367
368    /** Returns the physical register index of the i'th destination
369     *  register.
370     */
371    PhysRegIdPtr renamedDestRegIdx(int idx) const
372    {
373        return _destRegIdx[idx];
374    }
375
376    /** Returns the physical register index of the i'th source register. */
377    PhysRegIdPtr renamedSrcRegIdx(int idx) const
378    {
379        assert(TheISA::MaxInstSrcRegs > idx);
380        return _srcRegIdx[idx];
381    }
382
383    /** Returns the flattened register index of the i'th destination
384     *  register.
385     */
386    const RegId& flattenedDestRegIdx(int idx) const
387    {
388        return _flatDestRegIdx[idx];
389    }
390
391    /** Returns the physical register index of the previous physical register
392     *  that remapped to the same logical register index.
393     */
394    PhysRegIdPtr prevDestRegIdx(int idx) const
395    {
396        return _prevDestRegIdx[idx];
397    }
398
399    /** Renames a destination register to a physical register.  Also records
400     *  the previous physical register that the logical register mapped to.
401     */
402    void renameDestReg(int idx,
403                       PhysRegIdPtr renamed_dest,
404                       PhysRegIdPtr previous_rename)
405    {
406        _destRegIdx[idx] = renamed_dest;
407        _prevDestRegIdx[idx] = previous_rename;
408    }
409
410    /** Renames a source logical register to the physical register which
411     *  has/will produce that logical register's result.
412     *  @todo: add in whether or not the source register is ready.
413     */
414    void renameSrcReg(int idx, PhysRegIdPtr renamed_src)
415    {
416        _srcRegIdx[idx] = renamed_src;
417    }
418
419    /** Flattens a destination architectural register index into a logical
420     * index.
421     */
422    void flattenDestReg(int idx, const RegId& flattened_dest)
423    {
424        _flatDestRegIdx[idx] = flattened_dest;
425    }
426    /** BaseDynInst constructor given a binary instruction.
427     *  @param staticInst A StaticInstPtr to the underlying instruction.
428     *  @param pc The PC state for the instruction.
429     *  @param predPC The predicted next PC state for the instruction.
430     *  @param seq_num The sequence number of the instruction.
431     *  @param cpu Pointer to the instruction's CPU.
432     */
433    BaseDynInst(const StaticInstPtr &staticInst, const StaticInstPtr &macroop,
434                TheISA::PCState pc, TheISA::PCState predPC,
435                InstSeqNum seq_num, ImplCPU *cpu);
436
437    /** BaseDynInst constructor given a StaticInst pointer.
438     *  @param _staticInst The StaticInst for this BaseDynInst.
439     */
440    BaseDynInst(const StaticInstPtr &staticInst, const StaticInstPtr &macroop);
441
442    /** BaseDynInst destructor. */
443    ~BaseDynInst();
444
445  private:
446    /** Function to initialize variables in the constructors. */
447    void initVars();
448
449  public:
450    /** Dumps out contents of this BaseDynInst. */
451    void dump();
452
453    /** Dumps out contents of this BaseDynInst into given string. */
454    void dump(std::string &outstring);
455
456    /** Read this CPU's ID. */
457    int cpuId() const { return cpu->cpuId(); }
458
459    /** Read this CPU's Socket ID. */
460    uint32_t socketId() const { return cpu->socketId(); }
461
462    /** Read this CPU's data requestor ID */
463    MasterID masterId() const { return cpu->dataMasterId(); }
464
465    /** Read this context's system-wide ID **/
466    ContextID contextId() const { return thread->contextId(); }
467
468    /** Returns the fault type. */
469    Fault getFault() const { return fault; }
470
471    /** Checks whether or not this instruction has had its branch target
472     *  calculated yet.  For now it is not utilized and is hacked to be
473     *  always false.
474     *  @todo: Actually use this instruction.
475     */
476    bool doneTargCalc() { return false; }
477
478    /** Set the predicted target of this current instruction. */
479    void setPredTarg(const TheISA::PCState &_predPC)
480    {
481        predPC = _predPC;
482    }
483
484    const TheISA::PCState &readPredTarg() { return predPC; }
485
486    /** Returns the predicted PC immediately after the branch. */
487    Addr predInstAddr() { return predPC.instAddr(); }
488
489    /** Returns the predicted PC two instructions after the branch */
490    Addr predNextInstAddr() { return predPC.nextInstAddr(); }
491
492    /** Returns the predicted micro PC after the branch */
493    Addr predMicroPC() { return predPC.microPC(); }
494
495    /** Returns whether the instruction was predicted taken or not. */
496    bool readPredTaken()
497    {
498        return instFlags[PredTaken];
499    }
500
501    void setPredTaken(bool predicted_taken)
502    {
503        instFlags[PredTaken] = predicted_taken;
504    }
505
506    /** Returns whether the instruction mispredicted. */
507    bool mispredicted()
508    {
509        TheISA::PCState tempPC = pc;
510        TheISA::advancePC(tempPC, staticInst);
511        return !(tempPC == predPC);
512    }
513
514    //
515    //  Instruction types.  Forward checks to StaticInst object.
516    //
517    bool isNop()          const { return staticInst->isNop(); }
518    bool isMemRef()       const { return staticInst->isMemRef(); }
519    bool isLoad()         const { return staticInst->isLoad(); }
520    bool isStore()        const { return staticInst->isStore(); }
521    bool isStoreConditional() const
522    { return staticInst->isStoreConditional(); }
523    bool isInstPrefetch() const { return staticInst->isInstPrefetch(); }
524    bool isDataPrefetch() const { return staticInst->isDataPrefetch(); }
525    bool isInteger()      const { return staticInst->isInteger(); }
526    bool isFloating()     const { return staticInst->isFloating(); }
527    bool isControl()      const { return staticInst->isControl(); }
528    bool isCall()         const { return staticInst->isCall(); }
529    bool isReturn()       const { return staticInst->isReturn(); }
530    bool isDirectCtrl()   const { return staticInst->isDirectCtrl(); }
531    bool isIndirectCtrl() const { return staticInst->isIndirectCtrl(); }
532    bool isCondCtrl()     const { return staticInst->isCondCtrl(); }
533    bool isUncondCtrl()   const { return staticInst->isUncondCtrl(); }
534    bool isCondDelaySlot() const { return staticInst->isCondDelaySlot(); }
535    bool isThreadSync()   const { return staticInst->isThreadSync(); }
536    bool isSerializing()  const { return staticInst->isSerializing(); }
537    bool isSerializeBefore() const
538    { return staticInst->isSerializeBefore() || status[SerializeBefore]; }
539    bool isSerializeAfter() const
540    { return staticInst->isSerializeAfter() || status[SerializeAfter]; }
541    bool isSquashAfter() const { return staticInst->isSquashAfter(); }
542    bool isMemBarrier()   const { return staticInst->isMemBarrier(); }
543    bool isWriteBarrier() const { return staticInst->isWriteBarrier(); }
544    bool isNonSpeculative() const { return staticInst->isNonSpeculative(); }
545    bool isQuiesce() const { return staticInst->isQuiesce(); }
546    bool isIprAccess() const { return staticInst->isIprAccess(); }
547    bool isUnverifiable() const { return staticInst->isUnverifiable(); }
548    bool isSyscall() const { return staticInst->isSyscall(); }
549    bool isMacroop() const { return staticInst->isMacroop(); }
550    bool isMicroop() const { return staticInst->isMicroop(); }
551    bool isDelayedCommit() const { return staticInst->isDelayedCommit(); }
552    bool isLastMicroop() const { return staticInst->isLastMicroop(); }
553    bool isFirstMicroop() const { return staticInst->isFirstMicroop(); }
554    bool isMicroBranch() const { return staticInst->isMicroBranch(); }
555
556    /** Temporarily sets this instruction as a serialize before instruction. */
557    void setSerializeBefore() { status.set(SerializeBefore); }
558
559    /** Clears the serializeBefore part of this instruction. */
560    void clearSerializeBefore() { status.reset(SerializeBefore); }
561
562    /** Checks if this serializeBefore is only temporarily set. */
563    bool isTempSerializeBefore() { return status[SerializeBefore]; }
564
565    /** Temporarily sets this instruction as a serialize after instruction. */
566    void setSerializeAfter() { status.set(SerializeAfter); }
567
568    /** Clears the serializeAfter part of this instruction.*/
569    void clearSerializeAfter() { status.reset(SerializeAfter); }
570
571    /** Checks if this serializeAfter is only temporarily set. */
572    bool isTempSerializeAfter() { return status[SerializeAfter]; }
573
574    /** Sets the serialization part of this instruction as handled. */
575    void setSerializeHandled() { status.set(SerializeHandled); }
576
577    /** Checks if the serialization part of this instruction has been
578     *  handled.  This does not apply to the temporary serializing
579     *  state; it only applies to this instruction's own permanent
580     *  serializing state.
581     */
582    bool isSerializeHandled() { return status[SerializeHandled]; }
583
584    /** Returns the opclass of this instruction. */
585    OpClass opClass() const { return staticInst->opClass(); }
586
587    /** Returns the branch target address. */
588    TheISA::PCState branchTarget() const
589    { return staticInst->branchTarget(pc); }
590
591    /** Returns the number of source registers. */
592    int8_t numSrcRegs() const { return staticInst->numSrcRegs(); }
593
594    /** Returns the number of destination registers. */
595    int8_t numDestRegs() const { return staticInst->numDestRegs(); }
596
597    // the following are used to track physical register usage
598    // for machines with separate int & FP reg files
599    int8_t numFPDestRegs()  const { return staticInst->numFPDestRegs(); }
600    int8_t numIntDestRegs() const { return staticInst->numIntDestRegs(); }
601    int8_t numCCDestRegs() const { return staticInst->numCCDestRegs(); }
602
603    /** Returns the logical register index of the i'th destination register. */
604    const RegId& destRegIdx(int i) const { return staticInst->destRegIdx(i); }
605
606    /** Returns the logical register index of the i'th source register. */
607    const RegId& srcRegIdx(int i) const { return staticInst->srcRegIdx(i); }
608
609    /** Pops a result off the instResult queue */
610    template <class T>
611    void popResult(T& t)
612    {
613        if (!instResult.empty()) {
614            instResult.front().get(t);
615            instResult.pop();
616        }
617    }
618
619    /** Read the most recent result stored by this instruction */
620    template <class T>
621    void readResult(T& t)
622    {
623        instResult.back().get(t);
624    }
625
626    /** Pushes a result onto the instResult queue */
627    template <class T>
628    void setResult(T t)
629    {
630        if (instFlags[RecordResult]) {
631            Result instRes;
632            instRes.set(t);
633            instResult.push(instRes);
634        }
635    }
636
637    /** Records an integer register being set to a value. */
638    void setIntRegOperand(const StaticInst *si, int idx, IntReg val)
639    {
640        setResult<uint64_t>(val);
641    }
642
643    /** Records a CC register being set to a value. */
644    void setCCRegOperand(const StaticInst *si, int idx, CCReg val)
645    {
646        setResult<uint64_t>(val);
647    }
648
649    /** Records an fp register being set to a value. */
650    void setFloatRegOperand(const StaticInst *si, int idx, FloatReg val)
651    {
652        setResult<double>(val);
653    }
654
655    /** Records an fp register being set to an integer value. */
656    void setFloatRegOperandBits(const StaticInst *si, int idx, FloatRegBits val)
657    {
658        setResult<uint64_t>(val);
659    }
660
661    /** Records that one of the source registers is ready. */
662    void markSrcRegReady();
663
664    /** Marks a specific register as ready. */
665    void markSrcRegReady(RegIndex src_idx);
666
667    /** Returns if a source register is ready. */
668    bool isReadySrcRegIdx(int idx) const
669    {
670        return this->_readySrcRegIdx[idx];
671    }
672
673    /** Sets this instruction as completed. */
674    void setCompleted() { status.set(Completed); }
675
676    /** Returns whether or not this instruction is completed. */
677    bool isCompleted() const { return status[Completed]; }
678
679    /** Marks the result as ready. */
680    void setResultReady() { status.set(ResultReady); }
681
682    /** Returns whether or not the result is ready. */
683    bool isResultReady() const { return status[ResultReady]; }
684
685    /** Sets this instruction as ready to issue. */
686    void setCanIssue() { status.set(CanIssue); }
687
688    /** Returns whether or not this instruction is ready to issue. */
689    bool readyToIssue() const { return status[CanIssue]; }
690
691    /** Clears this instruction being able to issue. */
692    void clearCanIssue() { status.reset(CanIssue); }
693
694    /** Sets this instruction as issued from the IQ. */
695    void setIssued() { status.set(Issued); }
696
697    /** Returns whether or not this instruction has issued. */
698    bool isIssued() const { return status[Issued]; }
699
700    /** Clears this instruction as being issued. */
701    void clearIssued() { status.reset(Issued); }
702
703    /** Sets this instruction as executed. */
704    void setExecuted() { status.set(Executed); }
705
706    /** Returns whether or not this instruction has executed. */
707    bool isExecuted() const { return status[Executed]; }
708
709    /** Sets this instruction as ready to commit. */
710    void setCanCommit() { status.set(CanCommit); }
711
712    /** Clears this instruction as being ready to commit. */
713    void clearCanCommit() { status.reset(CanCommit); }
714
715    /** Returns whether or not this instruction is ready to commit. */
716    bool readyToCommit() const { return status[CanCommit]; }
717
718    void setAtCommit() { status.set(AtCommit); }
719
720    bool isAtCommit() { return status[AtCommit]; }
721
722    /** Sets this instruction as committed. */
723    void setCommitted() { status.set(Committed); }
724
725    /** Returns whether or not this instruction is committed. */
726    bool isCommitted() const { return status[Committed]; }
727
728    /** Sets this instruction as squashed. */
729    void setSquashed() { status.set(Squashed); }
730
731    /** Returns whether or not this instruction is squashed. */
732    bool isSquashed() const { return status[Squashed]; }
733
734    //Instruction Queue Entry
735    //-----------------------
736    /** Sets this instruction as a entry the IQ. */
737    void setInIQ() { status.set(IqEntry); }
738
739    /** Sets this instruction as a entry the IQ. */
740    void clearInIQ() { status.reset(IqEntry); }
741
742    /** Returns whether or not this instruction has issued. */
743    bool isInIQ() const { return status[IqEntry]; }
744
745    /** Sets this instruction as squashed in the IQ. */
746    void setSquashedInIQ() { status.set(SquashedInIQ); status.set(Squashed);}
747
748    /** Returns whether or not this instruction is squashed in the IQ. */
749    bool isSquashedInIQ() const { return status[SquashedInIQ]; }
750
751
752    //Load / Store Queue Functions
753    //-----------------------
754    /** Sets this instruction as a entry the LSQ. */
755    void setInLSQ() { status.set(LsqEntry); }
756
757    /** Sets this instruction as a entry the LSQ. */
758    void removeInLSQ() { status.reset(LsqEntry); }
759
760    /** Returns whether or not this instruction is in the LSQ. */
761    bool isInLSQ() const { return status[LsqEntry]; }
762
763    /** Sets this instruction as squashed in the LSQ. */
764    void setSquashedInLSQ() { status.set(SquashedInLSQ);}
765
766    /** Returns whether or not this instruction is squashed in the LSQ. */
767    bool isSquashedInLSQ() const { return status[SquashedInLSQ]; }
768
769
770    //Reorder Buffer Functions
771    //-----------------------
772    /** Sets this instruction as a entry the ROB. */
773    void setInROB() { status.set(RobEntry); }
774
775    /** Sets this instruction as a entry the ROB. */
776    void clearInROB() { status.reset(RobEntry); }
777
778    /** Returns whether or not this instruction is in the ROB. */
779    bool isInROB() const { return status[RobEntry]; }
780
781    /** Sets this instruction as squashed in the ROB. */
782    void setSquashedInROB() { status.set(SquashedInROB); }
783
784    /** Returns whether or not this instruction is squashed in the ROB. */
785    bool isSquashedInROB() const { return status[SquashedInROB]; }
786
787    /** Read the PC state of this instruction. */
788    TheISA::PCState pcState() const { return pc; }
789
790    /** Set the PC state of this instruction. */
791    void pcState(const TheISA::PCState &val) { pc = val; }
792
793    /** Read the PC of this instruction. */
794    Addr instAddr() const { return pc.instAddr(); }
795
796    /** Read the PC of the next instruction. */
797    Addr nextInstAddr() const { return pc.nextInstAddr(); }
798
799    /**Read the micro PC of this instruction. */
800    Addr microPC() const { return pc.microPC(); }
801
802    bool readPredicate()
803    {
804        return instFlags[Predicate];
805    }
806
807    void setPredicate(bool val)
808    {
809        instFlags[Predicate] = val;
810
811        if (traceData) {
812            traceData->setPredicate(val);
813        }
814    }
815
816    /** Sets the ASID. */
817    void setASID(short addr_space_id) { asid = addr_space_id; }
818
819    /** Sets the thread id. */
820    void setTid(ThreadID tid) { threadNumber = tid; }
821
822    /** Sets the pointer to the thread state. */
823    void setThreadState(ImplState *state) { thread = state; }
824
825    /** Returns the thread context. */
826    ThreadContext *tcBase() { return thread->getTC(); }
827
828  public:
829    /** Sets the effective address. */
830    void setEA(Addr ea) { instEffAddr = ea; instFlags[EACalcDone] = true; }
831
832    /** Returns the effective address. */
833    Addr getEA() const { return instEffAddr; }
834
835    /** Returns whether or not the eff. addr. calculation has been completed. */
836    bool doneEACalc() { return instFlags[EACalcDone]; }
837
838    /** Returns whether or not the eff. addr. source registers are ready. */
839    bool eaSrcsReady();
840
841    /** Is this instruction's memory access strictly ordered? */
842    bool strictlyOrdered() const { return instFlags[IsStrictlyOrdered]; }
843
844    /** Has this instruction generated a memory request. */
845    bool hasRequest() { return instFlags[ReqMade]; }
846
847    /** Returns iterator to this instruction in the list of all insts. */
848    ListIt &getInstListIt() { return instListIt; }
849
850    /** Sets iterator for this instruction in the list of all insts. */
851    void setInstListIt(ListIt _instListIt) { instListIt = _instListIt; }
852
853  public:
854    /** Returns the number of consecutive store conditional failures. */
855    unsigned int readStCondFailures() const
856    { return thread->storeCondFailures; }
857
858    /** Sets the number of consecutive store conditional failures. */
859    void setStCondFailures(unsigned int sc_failures)
860    { thread->storeCondFailures = sc_failures; }
861
862  public:
863    // monitor/mwait funtions
864    void armMonitor(Addr address) { cpu->armMonitor(threadNumber, address); }
865    bool mwait(PacketPtr pkt) { return cpu->mwait(threadNumber, pkt); }
866    void mwaitAtomic(ThreadContext *tc)
867    { return cpu->mwaitAtomic(threadNumber, tc, cpu->dtb); }
868    AddressMonitor *getAddrMonitor()
869    { return cpu->getCpuAddrMonitor(threadNumber); }
870};
871
872template<class Impl>
873Fault
874BaseDynInst<Impl>::initiateMemRead(Addr addr, unsigned size,
875                                   Request::Flags flags)
876{
877    instFlags[ReqMade] = true;
878    Request *req = NULL;
879    Request *sreqLow = NULL;
880    Request *sreqHigh = NULL;
881
882    if (instFlags[ReqMade] && translationStarted()) {
883        req = savedReq;
884        sreqLow = savedSreqLow;
885        sreqHigh = savedSreqHigh;
886    } else {
887        req = new Request(asid, addr, size, flags, masterId(), this->pc.instAddr(),
888                          thread->contextId());
889
890        req->taskId(cpu->taskId());
891
892        // Only split the request if the ISA supports unaligned accesses.
893        if (TheISA::HasUnalignedMemAcc) {
894            splitRequest(req, sreqLow, sreqHigh);
895        }
896        initiateTranslation(req, sreqLow, sreqHigh, NULL, BaseTLB::Read);
897    }
898
899    if (translationCompleted()) {
900        if (fault == NoFault) {
901            effAddr = req->getVaddr();
902            effSize = size;
903            instFlags[EffAddrValid] = true;
904
905            if (cpu->checker) {
906                if (reqToVerify != NULL) {
907                    delete reqToVerify;
908                }
909                reqToVerify = new Request(*req);
910            }
911            fault = cpu->read(req, sreqLow, sreqHigh, lqIdx);
912        } else {
913            // Commit will have to clean up whatever happened.  Set this
914            // instruction as executed.
915            this->setExecuted();
916        }
917    }
918
919    if (traceData)
920        traceData->setMem(addr, size, flags);
921
922    return fault;
923}
924
925template<class Impl>
926Fault
927BaseDynInst<Impl>::writeMem(uint8_t *data, unsigned size, Addr addr,
928                            Request::Flags flags, uint64_t *res)
929{
930    if (traceData)
931        traceData->setMem(addr, size, flags);
932
933    instFlags[ReqMade] = true;
934    Request *req = NULL;
935    Request *sreqLow = NULL;
936    Request *sreqHigh = NULL;
937
938    if (instFlags[ReqMade] && translationStarted()) {
939        req = savedReq;
940        sreqLow = savedSreqLow;
941        sreqHigh = savedSreqHigh;
942    } else {
943        req = new Request(asid, addr, size, flags, masterId(), this->pc.instAddr(),
944                          thread->contextId());
945
946        req->taskId(cpu->taskId());
947
948        // Only split the request if the ISA supports unaligned accesses.
949        if (TheISA::HasUnalignedMemAcc) {
950            splitRequest(req, sreqLow, sreqHigh);
951        }
952        initiateTranslation(req, sreqLow, sreqHigh, res, BaseTLB::Write);
953    }
954
955    if (fault == NoFault && translationCompleted()) {
956        effAddr = req->getVaddr();
957        effSize = size;
958        instFlags[EffAddrValid] = true;
959
960        if (cpu->checker) {
961            if (reqToVerify != NULL) {
962                delete reqToVerify;
963            }
964            reqToVerify = new Request(*req);
965        }
966        fault = cpu->write(req, sreqLow, sreqHigh, data, sqIdx);
967    }
968
969    return fault;
970}
971
972template<class Impl>
973inline void
974BaseDynInst<Impl>::splitRequest(RequestPtr req, RequestPtr &sreqLow,
975                                RequestPtr &sreqHigh)
976{
977    // Check to see if the request crosses the next level block boundary.
978    unsigned block_size = cpu->cacheLineSize();
979    Addr addr = req->getVaddr();
980    Addr split_addr = roundDown(addr + req->getSize() - 1, block_size);
981    assert(split_addr <= addr || split_addr - addr < block_size);
982
983    // Spans two blocks.
984    if (split_addr > addr) {
985        req->splitOnVaddr(split_addr, sreqLow, sreqHigh);
986    }
987}
988
989template<class Impl>
990inline void
991BaseDynInst<Impl>::initiateTranslation(RequestPtr req, RequestPtr sreqLow,
992                                       RequestPtr sreqHigh, uint64_t *res,
993                                       BaseTLB::Mode mode)
994{
995    translationStarted(true);
996
997    if (!TheISA::HasUnalignedMemAcc || sreqLow == NULL) {
998        WholeTranslationState *state =
999            new WholeTranslationState(req, NULL, res, mode);
1000
1001        // One translation if the request isn't split.
1002        DataTranslation<BaseDynInstPtr> *trans =
1003            new DataTranslation<BaseDynInstPtr>(this, state);
1004
1005        cpu->dtb->translateTiming(req, thread->getTC(), trans, mode);
1006
1007        if (!translationCompleted()) {
1008            // The translation isn't yet complete, so we can't possibly have a
1009            // fault. Overwrite any existing fault we might have from a previous
1010            // execution of this instruction (e.g. an uncachable load that
1011            // couldn't execute because it wasn't at the head of the ROB).
1012            fault = NoFault;
1013
1014            // Save memory requests.
1015            savedReq = state->mainReq;
1016            savedSreqLow = state->sreqLow;
1017            savedSreqHigh = state->sreqHigh;
1018        }
1019    } else {
1020        WholeTranslationState *state =
1021            new WholeTranslationState(req, sreqLow, sreqHigh, NULL, res, mode);
1022
1023        // Two translations when the request is split.
1024        DataTranslation<BaseDynInstPtr> *stransLow =
1025            new DataTranslation<BaseDynInstPtr>(this, state, 0);
1026        DataTranslation<BaseDynInstPtr> *stransHigh =
1027            new DataTranslation<BaseDynInstPtr>(this, state, 1);
1028
1029        cpu->dtb->translateTiming(sreqLow, thread->getTC(), stransLow, mode);
1030        cpu->dtb->translateTiming(sreqHigh, thread->getTC(), stransHigh, mode);
1031
1032        if (!translationCompleted()) {
1033            // The translation isn't yet complete, so we can't possibly have a
1034            // fault. Overwrite any existing fault we might have from a previous
1035            // execution of this instruction (e.g. an uncachable load that
1036            // couldn't execute because it wasn't at the head of the ROB).
1037            fault = NoFault;
1038
1039            // Save memory requests.
1040            savedReq = state->mainReq;
1041            savedSreqLow = state->sreqLow;
1042            savedSreqHigh = state->sreqHigh;
1043        }
1044    }
1045}
1046
1047template<class Impl>
1048inline void
1049BaseDynInst<Impl>::finishTranslation(WholeTranslationState *state)
1050{
1051    fault = state->getFault();
1052
1053    instFlags[IsStrictlyOrdered] = state->isStrictlyOrdered();
1054
1055    if (fault == NoFault) {
1056        // save Paddr for a single req
1057        physEffAddrLow = state->getPaddr();
1058
1059        // case for the request that has been split
1060        if (state->isSplit) {
1061          physEffAddrLow = state->sreqLow->getPaddr();
1062          physEffAddrHigh = state->sreqHigh->getPaddr();
1063        }
1064
1065        memReqFlags = state->getFlags();
1066
1067        if (state->mainReq->isCondSwap()) {
1068            assert(state->res);
1069            state->mainReq->setExtraData(*state->res);
1070        }
1071
1072    } else {
1073        state->deleteReqs();
1074    }
1075    delete state;
1076
1077    translationCompleted(true);
1078}
1079
1080#endif // __CPU_BASE_DYN_INST_HH__
1081