fetch_impl.hh revision 8346:ce8b9a250021
1/*
2 * Copyright (c) 2010 ARM Limited
3 * All rights reserved.
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder.  You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2004-2006 The Regents of The University of Michigan
15 * All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *
40 * Authors: Kevin Lim
41 *          Korey Sewell
42 */
43
44#include <algorithm>
45#include <cstring>
46
47#include "arch/isa_traits.hh"
48#include "arch/utility.hh"
49#include "base/types.hh"
50#include "config/the_isa.hh"
51#include "config/use_checker.hh"
52#include "cpu/checker/cpu.hh"
53#include "cpu/o3/fetch.hh"
54#include "cpu/exetrace.hh"
55#include "debug/Activity.hh"
56#include "debug/Fetch.hh"
57#include "mem/packet.hh"
58#include "mem/request.hh"
59#include "params/DerivO3CPU.hh"
60#include "sim/byteswap.hh"
61#include "sim/core.hh"
62
63#if FULL_SYSTEM
64#include "arch/tlb.hh"
65#include "arch/vtophys.hh"
66#include "sim/system.hh"
67#endif // FULL_SYSTEM
68
69using namespace std;
70
71template<class Impl>
72void
73DefaultFetch<Impl>::IcachePort::setPeer(Port *port)
74{
75    Port::setPeer(port);
76
77    fetch->setIcache();
78}
79
80template<class Impl>
81Tick
82DefaultFetch<Impl>::IcachePort::recvAtomic(PacketPtr pkt)
83{
84    panic("DefaultFetch doesn't expect recvAtomic callback!");
85    return curTick();
86}
87
88template<class Impl>
89void
90DefaultFetch<Impl>::IcachePort::recvFunctional(PacketPtr pkt)
91{
92    DPRINTF(Fetch, "DefaultFetch doesn't update its state from a "
93            "functional call.\n");
94}
95
96template<class Impl>
97void
98DefaultFetch<Impl>::IcachePort::recvStatusChange(Status status)
99{
100    if (status == RangeChange) {
101        if (!snoopRangeSent) {
102            snoopRangeSent = true;
103            sendStatusChange(Port::RangeChange);
104        }
105        return;
106    }
107
108    panic("DefaultFetch doesn't expect recvStatusChange callback!");
109}
110
111template<class Impl>
112bool
113DefaultFetch<Impl>::IcachePort::recvTiming(PacketPtr pkt)
114{
115    DPRINTF(Fetch, "Received timing\n");
116    if (pkt->isResponse()) {
117        // We shouldn't ever get a block in ownership state
118        assert(!(pkt->memInhibitAsserted() && !pkt->sharedAsserted()));
119
120        fetch->processCacheCompletion(pkt);
121    }
122    //else Snooped a coherence request, just return
123    return true;
124}
125
126template<class Impl>
127void
128DefaultFetch<Impl>::IcachePort::recvRetry()
129{
130    fetch->recvRetry();
131}
132
133template<class Impl>
134DefaultFetch<Impl>::DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params)
135    : cpu(_cpu),
136      branchPred(params),
137      predecoder(NULL),
138      decodeToFetchDelay(params->decodeToFetchDelay),
139      renameToFetchDelay(params->renameToFetchDelay),
140      iewToFetchDelay(params->iewToFetchDelay),
141      commitToFetchDelay(params->commitToFetchDelay),
142      fetchWidth(params->fetchWidth),
143      cacheBlocked(false),
144      retryPkt(NULL),
145      retryTid(InvalidThreadID),
146      numThreads(params->numThreads),
147      numFetchingThreads(params->smtNumFetchingThreads),
148      interruptPending(false),
149      drainPending(false),
150      switchedOut(false)
151{
152    if (numThreads > Impl::MaxThreads)
153        fatal("numThreads (%d) is larger than compiled limit (%d),\n"
154              "\tincrease MaxThreads in src/cpu/o3/impl.hh\n",
155              numThreads, static_cast<int>(Impl::MaxThreads));
156
157    // Set fetch stage's status to inactive.
158    _status = Inactive;
159
160    std::string policy = params->smtFetchPolicy;
161
162    // Convert string to lowercase
163    std::transform(policy.begin(), policy.end(), policy.begin(),
164                   (int(*)(int)) tolower);
165
166    // Figure out fetch policy
167    if (policy == "singlethread") {
168        fetchPolicy = SingleThread;
169        if (numThreads > 1)
170            panic("Invalid Fetch Policy for a SMT workload.");
171    } else if (policy == "roundrobin") {
172        fetchPolicy = RoundRobin;
173        DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
174    } else if (policy == "branch") {
175        fetchPolicy = Branch;
176        DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
177    } else if (policy == "iqcount") {
178        fetchPolicy = IQ;
179        DPRINTF(Fetch, "Fetch policy set to IQ count\n");
180    } else if (policy == "lsqcount") {
181        fetchPolicy = LSQ;
182        DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
183    } else {
184        fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
185              " RoundRobin,LSQcount,IQcount}\n");
186    }
187
188    // Get the size of an instruction.
189    instSize = sizeof(TheISA::MachInst);
190
191    // Name is finally available, so create the port.
192    icachePort = new IcachePort(this);
193
194    icachePort->snoopRangeSent = false;
195
196#if USE_CHECKER
197    if (cpu->checker) {
198        cpu->checker->setIcachePort(icachePort);
199    }
200#endif
201}
202
203template <class Impl>
204std::string
205DefaultFetch<Impl>::name() const
206{
207    return cpu->name() + ".fetch";
208}
209
210template <class Impl>
211void
212DefaultFetch<Impl>::regStats()
213{
214    icacheStallCycles
215        .name(name() + ".icacheStallCycles")
216        .desc("Number of cycles fetch is stalled on an Icache miss")
217        .prereq(icacheStallCycles);
218
219    fetchedInsts
220        .name(name() + ".Insts")
221        .desc("Number of instructions fetch has processed")
222        .prereq(fetchedInsts);
223
224    fetchedBranches
225        .name(name() + ".Branches")
226        .desc("Number of branches that fetch encountered")
227        .prereq(fetchedBranches);
228
229    predictedBranches
230        .name(name() + ".predictedBranches")
231        .desc("Number of branches that fetch has predicted taken")
232        .prereq(predictedBranches);
233
234    fetchCycles
235        .name(name() + ".Cycles")
236        .desc("Number of cycles fetch has run and was not squashing or"
237              " blocked")
238        .prereq(fetchCycles);
239
240    fetchSquashCycles
241        .name(name() + ".SquashCycles")
242        .desc("Number of cycles fetch has spent squashing")
243        .prereq(fetchSquashCycles);
244
245    fetchTlbCycles
246        .name(name() + ".TlbCycles")
247        .desc("Number of cycles fetch has spent waiting for tlb")
248        .prereq(fetchTlbCycles);
249
250    fetchIdleCycles
251        .name(name() + ".IdleCycles")
252        .desc("Number of cycles fetch was idle")
253        .prereq(fetchIdleCycles);
254
255    fetchBlockedCycles
256        .name(name() + ".BlockedCycles")
257        .desc("Number of cycles fetch has spent blocked")
258        .prereq(fetchBlockedCycles);
259
260    fetchedCacheLines
261        .name(name() + ".CacheLines")
262        .desc("Number of cache lines fetched")
263        .prereq(fetchedCacheLines);
264
265    fetchMiscStallCycles
266        .name(name() + ".MiscStallCycles")
267        .desc("Number of cycles fetch has spent waiting on interrupts, or "
268              "bad addresses, or out of MSHRs")
269        .prereq(fetchMiscStallCycles);
270
271    fetchIcacheSquashes
272        .name(name() + ".IcacheSquashes")
273        .desc("Number of outstanding Icache misses that were squashed")
274        .prereq(fetchIcacheSquashes);
275
276    fetchTlbSquashes
277        .name(name() + ".ItlbSquashes")
278        .desc("Number of outstanding ITLB misses that were squashed")
279        .prereq(fetchTlbSquashes);
280
281    fetchNisnDist
282        .init(/* base value */ 0,
283              /* last value */ fetchWidth,
284              /* bucket size */ 1)
285        .name(name() + ".rateDist")
286        .desc("Number of instructions fetched each cycle (Total)")
287        .flags(Stats::pdf);
288
289    idleRate
290        .name(name() + ".idleRate")
291        .desc("Percent of cycles fetch was idle")
292        .prereq(idleRate);
293    idleRate = fetchIdleCycles * 100 / cpu->numCycles;
294
295    branchRate
296        .name(name() + ".branchRate")
297        .desc("Number of branch fetches per cycle")
298        .flags(Stats::total);
299    branchRate = fetchedBranches / cpu->numCycles;
300
301    fetchRate
302        .name(name() + ".rate")
303        .desc("Number of inst fetches per cycle")
304        .flags(Stats::total);
305    fetchRate = fetchedInsts / cpu->numCycles;
306
307    branchPred.regStats();
308}
309
310template<class Impl>
311void
312DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
313{
314    timeBuffer = time_buffer;
315
316    // Create wires to get information from proper places in time buffer.
317    fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
318    fromRename = timeBuffer->getWire(-renameToFetchDelay);
319    fromIEW = timeBuffer->getWire(-iewToFetchDelay);
320    fromCommit = timeBuffer->getWire(-commitToFetchDelay);
321}
322
323template<class Impl>
324void
325DefaultFetch<Impl>::setActiveThreads(std::list<ThreadID> *at_ptr)
326{
327    activeThreads = at_ptr;
328}
329
330template<class Impl>
331void
332DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
333{
334    fetchQueue = fq_ptr;
335
336    // Create wire to write information to proper place in fetch queue.
337    toDecode = fetchQueue->getWire(0);
338}
339
340template<class Impl>
341void
342DefaultFetch<Impl>::initStage()
343{
344    // Setup PC and nextPC with initial state.
345    for (ThreadID tid = 0; tid < numThreads; tid++) {
346        pc[tid] = cpu->pcState(tid);
347        fetchOffset[tid] = 0;
348        macroop[tid] = NULL;
349        delayedCommit[tid] = false;
350    }
351
352    for (ThreadID tid = 0; tid < numThreads; tid++) {
353
354        fetchStatus[tid] = Running;
355
356        priorityList.push_back(tid);
357
358        memReq[tid] = NULL;
359
360        stalls[tid].decode = false;
361        stalls[tid].rename = false;
362        stalls[tid].iew = false;
363        stalls[tid].commit = false;
364    }
365
366    // Schedule fetch to get the correct PC from the CPU
367    // scheduleFetchStartupEvent(1);
368
369    // Fetch needs to start fetching instructions at the very beginning,
370    // so it must start up in active state.
371    switchToActive();
372}
373
374template<class Impl>
375void
376DefaultFetch<Impl>::setIcache()
377{
378    // Size of cache block.
379    cacheBlkSize = icachePort->peerBlockSize();
380
381    // Create mask to get rid of offset bits.
382    cacheBlkMask = (cacheBlkSize - 1);
383
384    for (ThreadID tid = 0; tid < numThreads; tid++) {
385        // Create space to store a cache line.
386        cacheData[tid] = new uint8_t[cacheBlkSize];
387        cacheDataPC[tid] = 0;
388        cacheDataValid[tid] = false;
389    }
390}
391
392template<class Impl>
393void
394DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
395{
396    ThreadID tid = pkt->req->threadId();
397
398    DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n", tid);
399
400    assert(!pkt->wasNacked());
401
402    // Only change the status if it's still waiting on the icache access
403    // to return.
404    if (fetchStatus[tid] != IcacheWaitResponse ||
405        pkt->req != memReq[tid] ||
406        isSwitchedOut()) {
407        ++fetchIcacheSquashes;
408        delete pkt->req;
409        delete pkt;
410        return;
411    }
412
413    memcpy(cacheData[tid], pkt->getPtr<uint8_t>(), cacheBlkSize);
414    cacheDataValid[tid] = true;
415
416    if (!drainPending) {
417        // Wake up the CPU (if it went to sleep and was waiting on
418        // this completion event).
419        cpu->wakeCPU();
420
421        DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
422                tid);
423
424        switchToActive();
425    }
426
427    // Only switch to IcacheAccessComplete if we're not stalled as well.
428    if (checkStall(tid)) {
429        fetchStatus[tid] = Blocked;
430    } else {
431        fetchStatus[tid] = IcacheAccessComplete;
432    }
433
434    // Reset the mem req to NULL.
435    delete pkt->req;
436    delete pkt;
437    memReq[tid] = NULL;
438}
439
440template <class Impl>
441bool
442DefaultFetch<Impl>::drain()
443{
444    // Fetch is ready to drain at any time.
445    cpu->signalDrained();
446    drainPending = true;
447    return true;
448}
449
450template <class Impl>
451void
452DefaultFetch<Impl>::resume()
453{
454    drainPending = false;
455}
456
457template <class Impl>
458void
459DefaultFetch<Impl>::switchOut()
460{
461    switchedOut = true;
462    // Branch predictor needs to have its state cleared.
463    branchPred.switchOut();
464}
465
466template <class Impl>
467void
468DefaultFetch<Impl>::takeOverFrom()
469{
470    // Reset all state
471    for (ThreadID i = 0; i < Impl::MaxThreads; ++i) {
472        stalls[i].decode = 0;
473        stalls[i].rename = 0;
474        stalls[i].iew = 0;
475        stalls[i].commit = 0;
476        pc[i] = cpu->pcState(i);
477        fetchStatus[i] = Running;
478    }
479    numInst = 0;
480    wroteToTimeBuffer = false;
481    _status = Inactive;
482    switchedOut = false;
483    interruptPending = false;
484    branchPred.takeOverFrom();
485}
486
487template <class Impl>
488void
489DefaultFetch<Impl>::wakeFromQuiesce()
490{
491    DPRINTF(Fetch, "Waking up from quiesce\n");
492    // Hopefully this is safe
493    // @todo: Allow other threads to wake from quiesce.
494    fetchStatus[0] = Running;
495}
496
497template <class Impl>
498inline void
499DefaultFetch<Impl>::switchToActive()
500{
501    if (_status == Inactive) {
502        DPRINTF(Activity, "Activating stage.\n");
503
504        cpu->activateStage(O3CPU::FetchIdx);
505
506        _status = Active;
507    }
508}
509
510template <class Impl>
511inline void
512DefaultFetch<Impl>::switchToInactive()
513{
514    if (_status == Active) {
515        DPRINTF(Activity, "Deactivating stage.\n");
516
517        cpu->deactivateStage(O3CPU::FetchIdx);
518
519        _status = Inactive;
520    }
521}
522
523template <class Impl>
524bool
525DefaultFetch<Impl>::lookupAndUpdateNextPC(
526        DynInstPtr &inst, TheISA::PCState &nextPC)
527{
528    // Do branch prediction check here.
529    // A bit of a misnomer...next_PC is actually the current PC until
530    // this function updates it.
531    bool predict_taken;
532
533    if (!inst->isControl()) {
534        TheISA::advancePC(nextPC, inst->staticInst);
535        inst->setPredTarg(nextPC);
536        inst->setPredTaken(false);
537        return false;
538    }
539
540    ThreadID tid = inst->threadNumber;
541    predict_taken = branchPred.predict(inst, nextPC, tid);
542
543    if (predict_taken) {
544        DPRINTF(Fetch, "[tid:%i]: [sn:%i]:  Branch predicted to be taken to %s.\n",
545                tid, inst->seqNum, nextPC);
546    } else {
547        DPRINTF(Fetch, "[tid:%i]: [sn:%i]:Branch predicted to be not taken.\n",
548                tid, inst->seqNum);
549    }
550
551    DPRINTF(Fetch, "[tid:%i]: [sn:%i] Branch predicted to go to %s.\n",
552            tid, inst->seqNum, nextPC);
553    inst->setPredTarg(nextPC);
554    inst->setPredTaken(predict_taken);
555
556    ++fetchedBranches;
557
558    if (predict_taken) {
559        ++predictedBranches;
560    }
561
562    return predict_taken;
563}
564
565template <class Impl>
566bool
567DefaultFetch<Impl>::fetchCacheLine(Addr vaddr, ThreadID tid, Addr pc)
568{
569    Fault fault = NoFault;
570
571    // @todo: not sure if these should block translation.
572    //AlphaDep
573    if (cacheBlocked) {
574        DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
575                tid);
576        return false;
577    } else if (isSwitchedOut()) {
578        DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, switched out\n",
579                tid);
580        return false;
581    } else if (checkInterrupt(pc)) {
582        // Hold off fetch from getting new instructions when:
583        // Cache is blocked, or
584        // while an interrupt is pending and we're not in PAL mode, or
585        // fetch is switched out.
586        DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n",
587                tid);
588        return false;
589    }
590
591    // Align the fetch address so it's at the start of a cache block.
592    Addr block_PC = icacheBlockAlignPC(vaddr);
593
594    DPRINTF(Fetch, "[tid:%i] Fetching cache line %#x for addr %#x\n",
595            tid, block_PC, vaddr);
596
597    // Setup the memReq to do a read of the first instruction's address.
598    // Set the appropriate read size and flags as well.
599    // Build request here.
600    RequestPtr mem_req =
601        new Request(tid, block_PC, cacheBlkSize, Request::INST_FETCH,
602                    pc, cpu->thread[tid]->contextId(), tid);
603
604    memReq[tid] = mem_req;
605
606    // Initiate translation of the icache block
607    fetchStatus[tid] = ItlbWait;
608    FetchTranslation *trans = new FetchTranslation(this);
609    cpu->itb->translateTiming(mem_req, cpu->thread[tid]->getTC(),
610                              trans, BaseTLB::Execute);
611    return true;
612}
613
614template <class Impl>
615void
616DefaultFetch<Impl>::finishTranslation(Fault fault, RequestPtr mem_req)
617{
618    ThreadID tid = mem_req->threadId();
619    Addr block_PC = mem_req->getVaddr();
620
621    // Wake up CPU if it was idle
622    cpu->wakeCPU();
623
624    if (fetchStatus[tid] != ItlbWait || mem_req != memReq[tid] ||
625        mem_req->getVaddr() != memReq[tid]->getVaddr() || isSwitchedOut()) {
626        DPRINTF(Fetch, "[tid:%i] Ignoring itlb completed after squash\n",
627                tid);
628        ++fetchTlbSquashes;
629        delete mem_req;
630        return;
631    }
632
633
634    // If translation was successful, attempt to read the icache block.
635    if (fault == NoFault) {
636        // Build packet here.
637        PacketPtr data_pkt = new Packet(mem_req,
638                                        MemCmd::ReadReq, Packet::Broadcast);
639        data_pkt->dataDynamicArray(new uint8_t[cacheBlkSize]);
640
641        cacheDataPC[tid] = block_PC;
642        cacheDataValid[tid] = false;
643        DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
644
645        fetchedCacheLines++;
646
647        // Access the cache.
648        if (!icachePort->sendTiming(data_pkt)) {
649            assert(retryPkt == NULL);
650            assert(retryTid == InvalidThreadID);
651            DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
652
653            fetchStatus[tid] = IcacheWaitRetry;
654            retryPkt = data_pkt;
655            retryTid = tid;
656            cacheBlocked = true;
657        } else {
658            DPRINTF(Fetch, "[tid:%i]: Doing Icache access.\n", tid);
659            DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
660                    "response.\n", tid);
661
662            lastIcacheStall[tid] = curTick();
663            fetchStatus[tid] = IcacheWaitResponse;
664        }
665    } else {
666        DPRINTF(Fetch, "[tid:%i] Got back req with addr %#x but expected %#x\n",
667                mem_req->getVaddr(), memReq[tid]->getVaddr());
668        // Translation faulted, icache request won't be sent.
669        delete mem_req;
670        memReq[tid] = NULL;
671
672        // Send the fault to commit.  This thread will not do anything
673        // until commit handles the fault.  The only other way it can
674        // wake up is if a squash comes along and changes the PC.
675        TheISA::PCState fetchPC = pc[tid];
676
677        DPRINTF(Fetch, "[tid:%i]: Translation faulted, building noop.\n", tid);
678        // We will use a nop in ordier to carry the fault.
679        DynInstPtr instruction = buildInst(tid,
680                StaticInstPtr(TheISA::NoopMachInst, fetchPC.instAddr()),
681                NULL, fetchPC, fetchPC, false);
682
683        instruction->setPredTarg(fetchPC);
684        instruction->fault = fault;
685        wroteToTimeBuffer = true;
686
687        DPRINTF(Activity, "Activity this cycle.\n");
688        cpu->activityThisCycle();
689
690        fetchStatus[tid] = TrapPending;
691
692        DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n", tid);
693        DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %s.\n",
694                tid, fault->name(), pc[tid]);
695    }
696    _status = updateFetchStatus();
697}
698
699template <class Impl>
700inline void
701DefaultFetch<Impl>::doSquash(const TheISA::PCState &newPC, ThreadID tid)
702{
703    DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %s.\n",
704            tid, newPC);
705
706    pc[tid] = newPC;
707    fetchOffset[tid] = 0;
708    macroop[tid] = NULL;
709    predecoder.reset();
710
711    // Clear the icache miss if it's outstanding.
712    if (fetchStatus[tid] == IcacheWaitResponse) {
713        DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
714                tid);
715        memReq[tid] = NULL;
716    } else if (fetchStatus[tid] == ItlbWait) {
717        DPRINTF(Fetch, "[tid:%i]: Squashing outstanding ITLB miss.\n",
718                tid);
719        memReq[tid] = NULL;
720    }
721
722    // Get rid of the retrying packet if it was from this thread.
723    if (retryTid == tid) {
724        assert(cacheBlocked);
725        if (retryPkt) {
726            delete retryPkt->req;
727            delete retryPkt;
728        }
729        retryPkt = NULL;
730        retryTid = InvalidThreadID;
731    }
732
733    fetchStatus[tid] = Squashing;
734
735    ++fetchSquashCycles;
736}
737
738template<class Impl>
739void
740DefaultFetch<Impl>::squashFromDecode(const TheISA::PCState &newPC,
741                                     const InstSeqNum &seq_num, ThreadID tid)
742{
743    DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n", tid);
744
745    doSquash(newPC, tid);
746
747    // Tell the CPU to remove any instructions that are in flight between
748    // fetch and decode.
749    cpu->removeInstsUntil(seq_num, tid);
750}
751
752template<class Impl>
753bool
754DefaultFetch<Impl>::checkStall(ThreadID tid) const
755{
756    bool ret_val = false;
757
758    if (cpu->contextSwitch) {
759        DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
760        ret_val = true;
761    } else if (stalls[tid].decode) {
762        DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
763        ret_val = true;
764    } else if (stalls[tid].rename) {
765        DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
766        ret_val = true;
767    } else if (stalls[tid].iew) {
768        DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
769        ret_val = true;
770    } else if (stalls[tid].commit) {
771        DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
772        ret_val = true;
773    }
774
775    return ret_val;
776}
777
778template<class Impl>
779typename DefaultFetch<Impl>::FetchStatus
780DefaultFetch<Impl>::updateFetchStatus()
781{
782    //Check Running
783    list<ThreadID>::iterator threads = activeThreads->begin();
784    list<ThreadID>::iterator end = activeThreads->end();
785
786    while (threads != end) {
787        ThreadID tid = *threads++;
788
789        if (fetchStatus[tid] == Running ||
790            fetchStatus[tid] == Squashing ||
791            fetchStatus[tid] == IcacheAccessComplete) {
792
793            if (_status == Inactive) {
794                DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
795
796                if (fetchStatus[tid] == IcacheAccessComplete) {
797                    DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
798                            "completion\n",tid);
799                }
800
801                cpu->activateStage(O3CPU::FetchIdx);
802            }
803
804            return Active;
805        }
806    }
807
808    // Stage is switching from active to inactive, notify CPU of it.
809    if (_status == Active) {
810        DPRINTF(Activity, "Deactivating stage.\n");
811
812        cpu->deactivateStage(O3CPU::FetchIdx);
813    }
814
815    return Inactive;
816}
817
818template <class Impl>
819void
820DefaultFetch<Impl>::squash(const TheISA::PCState &newPC,
821                           const InstSeqNum &seq_num, DynInstPtr &squashInst,
822                           ThreadID tid)
823{
824    DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n", tid);
825
826    doSquash(newPC, tid);
827
828    // Tell the CPU to remove any instructions that are not in the ROB.
829    cpu->removeInstsNotInROB(tid);
830}
831
832template <class Impl>
833void
834DefaultFetch<Impl>::tick()
835{
836    list<ThreadID>::iterator threads = activeThreads->begin();
837    list<ThreadID>::iterator end = activeThreads->end();
838    bool status_change = false;
839
840    wroteToTimeBuffer = false;
841
842    while (threads != end) {
843        ThreadID tid = *threads++;
844
845        // Check the signals for each thread to determine the proper status
846        // for each thread.
847        bool updated_status = checkSignalsAndUpdate(tid);
848        status_change =  status_change || updated_status;
849    }
850
851    DPRINTF(Fetch, "Running stage.\n");
852
853    // Reset the number of the instruction we're fetching.
854    numInst = 0;
855
856#if FULL_SYSTEM
857    if (fromCommit->commitInfo[0].interruptPending) {
858        interruptPending = true;
859    }
860
861    if (fromCommit->commitInfo[0].clearInterrupt) {
862        interruptPending = false;
863    }
864#endif
865
866    for (threadFetched = 0; threadFetched < numFetchingThreads;
867         threadFetched++) {
868        // Fetch each of the actively fetching threads.
869        fetch(status_change);
870    }
871
872    // Record number of instructions fetched this cycle for distribution.
873    fetchNisnDist.sample(numInst);
874
875    if (status_change) {
876        // Change the fetch stage status if there was a status change.
877        _status = updateFetchStatus();
878    }
879
880    // If there was activity this cycle, inform the CPU of it.
881    if (wroteToTimeBuffer || cpu->contextSwitch) {
882        DPRINTF(Activity, "Activity this cycle.\n");
883
884        cpu->activityThisCycle();
885    }
886}
887
888template <class Impl>
889bool
890DefaultFetch<Impl>::checkSignalsAndUpdate(ThreadID tid)
891{
892    // Update the per thread stall statuses.
893    if (fromDecode->decodeBlock[tid]) {
894        stalls[tid].decode = true;
895    }
896
897    if (fromDecode->decodeUnblock[tid]) {
898        assert(stalls[tid].decode);
899        assert(!fromDecode->decodeBlock[tid]);
900        stalls[tid].decode = false;
901    }
902
903    if (fromRename->renameBlock[tid]) {
904        stalls[tid].rename = true;
905    }
906
907    if (fromRename->renameUnblock[tid]) {
908        assert(stalls[tid].rename);
909        assert(!fromRename->renameBlock[tid]);
910        stalls[tid].rename = false;
911    }
912
913    if (fromIEW->iewBlock[tid]) {
914        stalls[tid].iew = true;
915    }
916
917    if (fromIEW->iewUnblock[tid]) {
918        assert(stalls[tid].iew);
919        assert(!fromIEW->iewBlock[tid]);
920        stalls[tid].iew = false;
921    }
922
923    if (fromCommit->commitBlock[tid]) {
924        stalls[tid].commit = true;
925    }
926
927    if (fromCommit->commitUnblock[tid]) {
928        assert(stalls[tid].commit);
929        assert(!fromCommit->commitBlock[tid]);
930        stalls[tid].commit = false;
931    }
932
933    // Check squash signals from commit.
934    if (fromCommit->commitInfo[tid].squash) {
935
936        DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
937                "from commit.\n",tid);
938        // In any case, squash.
939        squash(fromCommit->commitInfo[tid].pc,
940               fromCommit->commitInfo[tid].doneSeqNum,
941               fromCommit->commitInfo[tid].squashInst, tid);
942
943        // If it was a branch mispredict on a control instruction, update the
944        // branch predictor with that instruction, otherwise just kill the
945        // invalid state we generated in after sequence number
946        if (fromCommit->commitInfo[tid].mispredictInst &&
947            fromCommit->commitInfo[tid].mispredictInst->isControl()) {
948            branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
949                              fromCommit->commitInfo[tid].pc,
950                              fromCommit->commitInfo[tid].branchTaken,
951                              tid);
952        } else {
953            branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
954                              tid);
955        }
956
957        return true;
958    } else if (fromCommit->commitInfo[tid].doneSeqNum) {
959        // Update the branch predictor if it wasn't a squashed instruction
960        // that was broadcasted.
961        branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
962    }
963
964    // Check ROB squash signals from commit.
965    if (fromCommit->commitInfo[tid].robSquashing) {
966        DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
967
968        // Continue to squash.
969        fetchStatus[tid] = Squashing;
970
971        return true;
972    }
973
974    // Check squash signals from decode.
975    if (fromDecode->decodeInfo[tid].squash) {
976        DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
977                "from decode.\n",tid);
978
979        // Update the branch predictor.
980        if (fromDecode->decodeInfo[tid].branchMispredict) {
981            branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
982                              fromDecode->decodeInfo[tid].nextPC,
983                              fromDecode->decodeInfo[tid].branchTaken,
984                              tid);
985        } else {
986            branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
987                              tid);
988        }
989
990        if (fetchStatus[tid] != Squashing) {
991
992            TheISA::PCState nextPC = fromDecode->decodeInfo[tid].nextPC;
993            DPRINTF(Fetch, "Squashing from decode with PC = %s\n", nextPC);
994            // Squash unless we're already squashing
995            squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
996                             fromDecode->decodeInfo[tid].doneSeqNum,
997                             tid);
998
999            return true;
1000        }
1001    }
1002
1003    if (checkStall(tid) &&
1004        fetchStatus[tid] != IcacheWaitResponse &&
1005        fetchStatus[tid] != IcacheWaitRetry) {
1006        DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
1007
1008        fetchStatus[tid] = Blocked;
1009
1010        return true;
1011    }
1012
1013    if (fetchStatus[tid] == Blocked ||
1014        fetchStatus[tid] == Squashing) {
1015        // Switch status to running if fetch isn't being told to block or
1016        // squash this cycle.
1017        DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
1018                tid);
1019
1020        fetchStatus[tid] = Running;
1021
1022        return true;
1023    }
1024
1025    // If we've reached this point, we have not gotten any signals that
1026    // cause fetch to change its status.  Fetch remains the same as before.
1027    return false;
1028}
1029
1030template<class Impl>
1031typename Impl::DynInstPtr
1032DefaultFetch<Impl>::buildInst(ThreadID tid, StaticInstPtr staticInst,
1033                              StaticInstPtr curMacroop, TheISA::PCState thisPC,
1034                              TheISA::PCState nextPC, bool trace)
1035{
1036    // Get a sequence number.
1037    InstSeqNum seq = cpu->getAndIncrementInstSeq();
1038
1039    // Create a new DynInst from the instruction fetched.
1040    DynInstPtr instruction =
1041        new DynInst(staticInst, thisPC, nextPC, seq, cpu);
1042    instruction->setTid(tid);
1043
1044    instruction->setASID(tid);
1045
1046    instruction->setThreadState(cpu->thread[tid]);
1047
1048    DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x (%d) created "
1049            "[sn:%lli].\n", tid, thisPC.instAddr(),
1050            thisPC.microPC(), seq);
1051
1052    DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n", tid,
1053            instruction->staticInst->
1054            disassemble(thisPC.instAddr()));
1055
1056#if TRACING_ON
1057    if (trace) {
1058        instruction->traceData =
1059            cpu->getTracer()->getInstRecord(curTick(), cpu->tcBase(tid),
1060                    instruction->staticInst, thisPC, curMacroop);
1061    }
1062#else
1063    instruction->traceData = NULL;
1064#endif
1065
1066    // Add instruction to the CPU's list of instructions.
1067    instruction->setInstListIt(cpu->addInst(instruction));
1068
1069    // Write the instruction to the first slot in the queue
1070    // that heads to decode.
1071    assert(numInst < fetchWidth);
1072    toDecode->insts[toDecode->size++] = instruction;
1073
1074    // Keep track of if we can take an interrupt at this boundary
1075    delayedCommit[tid] = instruction->isDelayedCommit();
1076
1077    return instruction;
1078}
1079
1080template<class Impl>
1081void
1082DefaultFetch<Impl>::fetch(bool &status_change)
1083{
1084    //////////////////////////////////////////
1085    // Start actual fetch
1086    //////////////////////////////////////////
1087    ThreadID tid = getFetchingThread(fetchPolicy);
1088
1089    if (tid == InvalidThreadID || drainPending) {
1090        DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
1091
1092        // Breaks looping condition in tick()
1093        threadFetched = numFetchingThreads;
1094        return;
1095    }
1096
1097    DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
1098
1099    // The current PC.
1100    TheISA::PCState thisPC = pc[tid];
1101
1102    Addr pcOffset = fetchOffset[tid];
1103    Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1104
1105    bool inRom = isRomMicroPC(thisPC.microPC());
1106
1107    // If returning from the delay of a cache miss, then update the status
1108    // to running, otherwise do the cache access.  Possibly move this up
1109    // to tick() function.
1110    if (fetchStatus[tid] == IcacheAccessComplete) {
1111        DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n", tid);
1112
1113        fetchStatus[tid] = Running;
1114        status_change = true;
1115    } else if (fetchStatus[tid] == Running) {
1116        // Align the fetch PC so its at the start of a cache block.
1117        Addr block_PC = icacheBlockAlignPC(fetchAddr);
1118
1119        // If buffer is no longer valid or fetchAddr has moved to point
1120        // to the next cache block, AND we have no remaining ucode
1121        // from a macro-op, then start fetch from icache.
1122        if (!(cacheDataValid[tid] && block_PC == cacheDataPC[tid])
1123            && !inRom && !macroop[tid]) {
1124            DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
1125                    "instruction, starting at PC %s.\n", tid, thisPC);
1126
1127            fetchCacheLine(fetchAddr, tid, thisPC.instAddr());
1128
1129            if (fetchStatus[tid] == IcacheWaitResponse)
1130                ++icacheStallCycles;
1131            else if (fetchStatus[tid] == ItlbWait)
1132                ++fetchTlbCycles;
1133            else
1134                ++fetchMiscStallCycles;
1135            return;
1136        } else if ((checkInterrupt(thisPC.instAddr()) && !delayedCommit[tid])
1137                   || isSwitchedOut()) {
1138            // Stall CPU if an interrupt is posted and we're not issuing
1139            // an delayed commit micro-op currently (delayed commit instructions
1140            // are not interruptable by interrupts, only faults)
1141            ++fetchMiscStallCycles;
1142            return;
1143        }
1144    } else {
1145        if (fetchStatus[tid] == Idle) {
1146            ++fetchIdleCycles;
1147            DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
1148        } else if (fetchStatus[tid] == Blocked) {
1149            ++fetchBlockedCycles;
1150            DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
1151        } else if (fetchStatus[tid] == Squashing) {
1152            ++fetchSquashCycles;
1153            DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
1154        } else if (fetchStatus[tid] == IcacheWaitResponse) {
1155            ++icacheStallCycles;
1156            DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n",
1157                    tid);
1158        } else if (fetchStatus[tid] == ItlbWait) {
1159            DPRINTF(Fetch, "[tid:%i]: Fetch is waiting ITLB walk to "
1160                    "finish! \n", tid);
1161            ++fetchTlbCycles;
1162        } else if (fetchStatus[tid] == TrapPending) {
1163            DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending trap\n",
1164                    tid);
1165        }
1166
1167
1168        // Status is Idle, Squashing, Blocked, ItlbWait or IcacheWaitResponse
1169        // so fetch should do nothing.
1170        return;
1171    }
1172
1173    ++fetchCycles;
1174
1175    TheISA::PCState nextPC = thisPC;
1176
1177    StaticInstPtr staticInst = NULL;
1178    StaticInstPtr curMacroop = macroop[tid];
1179
1180    // If the read of the first instruction was successful, then grab the
1181    // instructions from the rest of the cache line and put them into the
1182    // queue heading to decode.
1183
1184    DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
1185            "decode.\n", tid);
1186
1187    // Need to keep track of whether or not a predicted branch
1188    // ended this fetch block.
1189    bool predictedBranch = false;
1190
1191    TheISA::MachInst *cacheInsts =
1192        reinterpret_cast<TheISA::MachInst *>(cacheData[tid]);
1193
1194    const unsigned numInsts = cacheBlkSize / instSize;
1195    unsigned blkOffset = (fetchAddr - cacheDataPC[tid]) / instSize;
1196
1197    // Loop through instruction memory from the cache.
1198    // Keep issuing while we have not reached the end of the block or a
1199    // macroop is active and fetchWidth is available and branch is not
1200    // predicted taken
1201    while ((blkOffset < numInsts || curMacroop) &&
1202                           numInst < fetchWidth && !predictedBranch) {
1203
1204        // If we need to process more memory, do it now.
1205        if (!(curMacroop || inRom) && !predecoder.extMachInstReady()) {
1206            if (ISA_HAS_DELAY_SLOT && pcOffset == 0) {
1207                // Walk past any annulled delay slot instructions.
1208                Addr pcAddr = thisPC.instAddr() & BaseCPU::PCMask;
1209                while (fetchAddr != pcAddr && blkOffset < numInsts) {
1210                    blkOffset++;
1211                    fetchAddr += instSize;
1212                }
1213                if (blkOffset >= numInsts)
1214                    break;
1215            }
1216            MachInst inst = TheISA::gtoh(cacheInsts[blkOffset]);
1217
1218            predecoder.setTC(cpu->thread[tid]->getTC());
1219            predecoder.moreBytes(thisPC, fetchAddr, inst);
1220
1221            if (predecoder.needMoreBytes()) {
1222                blkOffset++;
1223                fetchAddr += instSize;
1224                pcOffset += instSize;
1225            }
1226        }
1227
1228        // Extract as many instructions and/or microops as we can from
1229        // the memory we've processed so far.
1230        do {
1231            if (!(curMacroop || inRom)) {
1232                if (predecoder.extMachInstReady()) {
1233                    ExtMachInst extMachInst;
1234
1235                    extMachInst = predecoder.getExtMachInst(thisPC);
1236                    staticInst = StaticInstPtr(extMachInst,
1237                                               thisPC.instAddr());
1238
1239                    // Increment stat of fetched instructions.
1240                    ++fetchedInsts;
1241
1242                    if (staticInst->isMacroop()) {
1243                        curMacroop = staticInst;
1244                    } else {
1245                        pcOffset = 0;
1246                    }
1247                } else {
1248                    // We need more bytes for this instruction so blkOffset and
1249                    // pcOffset will be updated
1250                    break;
1251                }
1252            }
1253            if (curMacroop || inRom) {
1254                if (inRom) {
1255                    staticInst = cpu->microcodeRom.fetchMicroop(
1256                            thisPC.microPC(), curMacroop);
1257                } else {
1258                    staticInst = curMacroop->fetchMicroop(thisPC.microPC());
1259                }
1260                if (staticInst->isLastMicroop()) {
1261                    curMacroop = NULL;
1262                    pcOffset = 0;
1263                }
1264            }
1265
1266            DynInstPtr instruction =
1267                buildInst(tid, staticInst, curMacroop,
1268                          thisPC, nextPC, true);
1269
1270            numInst++;
1271
1272            nextPC = thisPC;
1273
1274            // If we're branching after this instruction, quite fetching
1275            // from the same block then.
1276            predictedBranch |= thisPC.branching();
1277            predictedBranch |=
1278                lookupAndUpdateNextPC(instruction, nextPC);
1279            if (predictedBranch) {
1280                DPRINTF(Fetch, "Branch detected with PC = %s\n", thisPC);
1281            }
1282
1283            // Move to the next instruction, unless we have a branch.
1284            thisPC = nextPC;
1285
1286            if (instruction->isQuiesce()) {
1287                DPRINTF(Fetch,
1288                        "Quiesce instruction encountered, halting fetch!");
1289                fetchStatus[tid] = QuiescePending;
1290                status_change = true;
1291                break;
1292            }
1293        } while ((curMacroop || predecoder.extMachInstReady()) &&
1294                 numInst < fetchWidth);
1295    }
1296
1297    if (predictedBranch) {
1298        DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
1299                "instruction encountered.\n", tid);
1300    } else if (numInst >= fetchWidth) {
1301        DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
1302                "for this cycle.\n", tid);
1303    } else if (blkOffset >= cacheBlkSize) {
1304        DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of cache "
1305                "block.\n", tid);
1306    }
1307
1308    macroop[tid] = curMacroop;
1309    fetchOffset[tid] = pcOffset;
1310
1311    if (numInst > 0) {
1312        wroteToTimeBuffer = true;
1313    }
1314
1315    pc[tid] = thisPC;
1316}
1317
1318template<class Impl>
1319void
1320DefaultFetch<Impl>::recvRetry()
1321{
1322    if (retryPkt != NULL) {
1323        assert(cacheBlocked);
1324        assert(retryTid != InvalidThreadID);
1325        assert(fetchStatus[retryTid] == IcacheWaitRetry);
1326
1327        if (icachePort->sendTiming(retryPkt)) {
1328            fetchStatus[retryTid] = IcacheWaitResponse;
1329            retryPkt = NULL;
1330            retryTid = InvalidThreadID;
1331            cacheBlocked = false;
1332        }
1333    } else {
1334        assert(retryTid == InvalidThreadID);
1335        // Access has been squashed since it was sent out.  Just clear
1336        // the cache being blocked.
1337        cacheBlocked = false;
1338    }
1339}
1340
1341///////////////////////////////////////
1342//                                   //
1343//  SMT FETCH POLICY MAINTAINED HERE //
1344//                                   //
1345///////////////////////////////////////
1346template<class Impl>
1347ThreadID
1348DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1349{
1350    if (numThreads > 1) {
1351        switch (fetch_priority) {
1352
1353          case SingleThread:
1354            return 0;
1355
1356          case RoundRobin:
1357            return roundRobin();
1358
1359          case IQ:
1360            return iqCount();
1361
1362          case LSQ:
1363            return lsqCount();
1364
1365          case Branch:
1366            return branchCount();
1367
1368          default:
1369            return InvalidThreadID;
1370        }
1371    } else {
1372        list<ThreadID>::iterator thread = activeThreads->begin();
1373        if (thread == activeThreads->end()) {
1374            return InvalidThreadID;
1375        }
1376
1377        ThreadID tid = *thread;
1378
1379        if (fetchStatus[tid] == Running ||
1380            fetchStatus[tid] == IcacheAccessComplete ||
1381            fetchStatus[tid] == Idle) {
1382            return tid;
1383        } else {
1384            return InvalidThreadID;
1385        }
1386    }
1387}
1388
1389
1390template<class Impl>
1391ThreadID
1392DefaultFetch<Impl>::roundRobin()
1393{
1394    list<ThreadID>::iterator pri_iter = priorityList.begin();
1395    list<ThreadID>::iterator end      = priorityList.end();
1396
1397    ThreadID high_pri;
1398
1399    while (pri_iter != end) {
1400        high_pri = *pri_iter;
1401
1402        assert(high_pri <= numThreads);
1403
1404        if (fetchStatus[high_pri] == Running ||
1405            fetchStatus[high_pri] == IcacheAccessComplete ||
1406            fetchStatus[high_pri] == Idle) {
1407
1408            priorityList.erase(pri_iter);
1409            priorityList.push_back(high_pri);
1410
1411            return high_pri;
1412        }
1413
1414        pri_iter++;
1415    }
1416
1417    return InvalidThreadID;
1418}
1419
1420template<class Impl>
1421ThreadID
1422DefaultFetch<Impl>::iqCount()
1423{
1424    std::priority_queue<unsigned> PQ;
1425    std::map<unsigned, ThreadID> threadMap;
1426
1427    list<ThreadID>::iterator threads = activeThreads->begin();
1428    list<ThreadID>::iterator end = activeThreads->end();
1429
1430    while (threads != end) {
1431        ThreadID tid = *threads++;
1432        unsigned iqCount = fromIEW->iewInfo[tid].iqCount;
1433
1434        PQ.push(iqCount);
1435        threadMap[iqCount] = tid;
1436    }
1437
1438    while (!PQ.empty()) {
1439        ThreadID high_pri = threadMap[PQ.top()];
1440
1441        if (fetchStatus[high_pri] == Running ||
1442            fetchStatus[high_pri] == IcacheAccessComplete ||
1443            fetchStatus[high_pri] == Idle)
1444            return high_pri;
1445        else
1446            PQ.pop();
1447
1448    }
1449
1450    return InvalidThreadID;
1451}
1452
1453template<class Impl>
1454ThreadID
1455DefaultFetch<Impl>::lsqCount()
1456{
1457    std::priority_queue<unsigned> PQ;
1458    std::map<unsigned, ThreadID> threadMap;
1459
1460    list<ThreadID>::iterator threads = activeThreads->begin();
1461    list<ThreadID>::iterator end = activeThreads->end();
1462
1463    while (threads != end) {
1464        ThreadID tid = *threads++;
1465        unsigned ldstqCount = fromIEW->iewInfo[tid].ldstqCount;
1466
1467        PQ.push(ldstqCount);
1468        threadMap[ldstqCount] = tid;
1469    }
1470
1471    while (!PQ.empty()) {
1472        ThreadID high_pri = threadMap[PQ.top()];
1473
1474        if (fetchStatus[high_pri] == Running ||
1475            fetchStatus[high_pri] == IcacheAccessComplete ||
1476            fetchStatus[high_pri] == Idle)
1477            return high_pri;
1478        else
1479            PQ.pop();
1480    }
1481
1482    return InvalidThreadID;
1483}
1484
1485template<class Impl>
1486ThreadID
1487DefaultFetch<Impl>::branchCount()
1488{
1489#if 0
1490    list<ThreadID>::iterator thread = activeThreads->begin();
1491    assert(thread != activeThreads->end());
1492    ThreadID tid = *thread;
1493#endif
1494
1495    panic("Branch Count Fetch policy unimplemented\n");
1496    return InvalidThreadID;
1497}
1498