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