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