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