2 * Copyright (c) 2004-2006 The Regents of The University of Michigan
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.
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.
35 #include "config/use_checker.hh"
37 #include "arch/isa_traits.hh"
38 #include "arch/utility.hh"
39 #include "cpu/checker/cpu.hh"
40 #include "cpu/exetrace.hh"
41 #include "cpu/o3/fetch.hh"
42 #include "mem/packet.hh"
43 #include "mem/request.hh"
44 #include "sim/byteswap.hh"
45 #include "sim/host.hh"
46 #include "sim/core.hh"
49 #include "arch/tlb.hh"
50 #include "arch/vtophys.hh"
51 #include "sim/system.hh"
56 DefaultFetch<Impl>::IcachePort::setPeer(Port *port)
65 DefaultFetch<Impl>::IcachePort::recvAtomic(PacketPtr pkt)
67 panic("DefaultFetch doesn't expect recvAtomic callback!");
73 DefaultFetch<Impl>::IcachePort::recvFunctional(PacketPtr pkt)
75 DPRINTF(Fetch, "DefaultFetch doesn't update its state from a "
81 DefaultFetch<Impl>::IcachePort::recvStatusChange(Status status)
83 if (status == RangeChange) {
84 if (!snoopRangeSent) {
85 snoopRangeSent = true;
86 sendStatusChange(Port::RangeChange);
91 panic("DefaultFetch doesn't expect recvStatusChange callback!");
96 DefaultFetch<Impl>::IcachePort::recvTiming(PacketPtr pkt)
98 DPRINTF(Fetch, "Received timing\n");
99 if (pkt->isResponse()) {
100 fetch->processCacheCompletion(pkt);
102 //else Snooped a coherence request, just return
108 DefaultFetch<Impl>::IcachePort::recvRetry()
114 DefaultFetch<Impl>::DefaultFetch(O3CPU *_cpu, Params *params)
118 decodeToFetchDelay(params->decodeToFetchDelay),
119 renameToFetchDelay(params->renameToFetchDelay),
120 iewToFetchDelay(params->iewToFetchDelay),
121 commitToFetchDelay(params->commitToFetchDelay),
122 fetchWidth(params->fetchWidth),
126 numThreads(params->numberOfThreads),
127 numFetchingThreads(params->smtNumFetchingThreads),
128 interruptPending(false),
132 if (numThreads > Impl::MaxThreads)
133 fatal("numThreads is not a valid value\n");
135 // Set fetch stage's status to inactive.
138 std::string policy = params->smtFetchPolicy;
140 // Convert string to lowercase
141 std::transform(policy.begin(), policy.end(), policy.begin(),
142 (int(*)(int)) tolower);
144 // Figure out fetch policy
145 if (policy == "singlethread") {
146 fetchPolicy = SingleThread;
148 panic("Invalid Fetch Policy for a SMT workload.");
149 } else if (policy == "roundrobin") {
150 fetchPolicy = RoundRobin;
151 DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
152 } else if (policy == "branch") {
153 fetchPolicy = Branch;
154 DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
155 } else if (policy == "iqcount") {
157 DPRINTF(Fetch, "Fetch policy set to IQ count\n");
158 } else if (policy == "lsqcount") {
160 DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
162 fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
163 " RoundRobin,LSQcount,IQcount}\n");
166 // Get the size of an instruction.
167 instSize = sizeof(TheISA::MachInst);
169 // Name is finally available, so create the port.
170 icachePort = new IcachePort(this);
172 icachePort->snoopRangeSent = false;
176 cpu->checker->setIcachePort(icachePort);
181 template <class Impl>
183 DefaultFetch<Impl>::name() const
185 return cpu->name() + ".fetch";
188 template <class Impl>
190 DefaultFetch<Impl>::regStats()
193 .name(name() + ".icacheStallCycles")
194 .desc("Number of cycles fetch is stalled on an Icache miss")
195 .prereq(icacheStallCycles);
198 .name(name() + ".Insts")
199 .desc("Number of instructions fetch has processed")
200 .prereq(fetchedInsts);
203 .name(name() + ".Branches")
204 .desc("Number of branches that fetch encountered")
205 .prereq(fetchedBranches);
208 .name(name() + ".predictedBranches")
209 .desc("Number of branches that fetch has predicted taken")
210 .prereq(predictedBranches);
213 .name(name() + ".Cycles")
214 .desc("Number of cycles fetch has run and was not squashing or"
216 .prereq(fetchCycles);
219 .name(name() + ".SquashCycles")
220 .desc("Number of cycles fetch has spent squashing")
221 .prereq(fetchSquashCycles);
224 .name(name() + ".IdleCycles")
225 .desc("Number of cycles fetch was idle")
226 .prereq(fetchIdleCycles);
229 .name(name() + ".BlockedCycles")
230 .desc("Number of cycles fetch has spent blocked")
231 .prereq(fetchBlockedCycles);
234 .name(name() + ".CacheLines")
235 .desc("Number of cache lines fetched")
236 .prereq(fetchedCacheLines);
239 .name(name() + ".MiscStallCycles")
240 .desc("Number of cycles fetch has spent waiting on interrupts, or "
241 "bad addresses, or out of MSHRs")
242 .prereq(fetchMiscStallCycles);
245 .name(name() + ".IcacheSquashes")
246 .desc("Number of outstanding Icache misses that were squashed")
247 .prereq(fetchIcacheSquashes);
250 .init(/* base value */ 0,
251 /* last value */ fetchWidth,
253 .name(name() + ".rateDist")
254 .desc("Number of instructions fetched each cycle (Total)")
258 .name(name() + ".idleRate")
259 .desc("Percent of cycles fetch was idle")
261 idleRate = fetchIdleCycles * 100 / cpu->numCycles;
264 .name(name() + ".branchRate")
265 .desc("Number of branch fetches per cycle")
266 .flags(Stats::total);
267 branchRate = fetchedBranches / cpu->numCycles;
270 .name(name() + ".rate")
271 .desc("Number of inst fetches per cycle")
272 .flags(Stats::total);
273 fetchRate = fetchedInsts / cpu->numCycles;
275 branchPred.regStats();
280 DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
282 timeBuffer = time_buffer;
284 // Create wires to get information from proper places in time buffer.
285 fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
286 fromRename = timeBuffer->getWire(-renameToFetchDelay);
287 fromIEW = timeBuffer->getWire(-iewToFetchDelay);
288 fromCommit = timeBuffer->getWire(-commitToFetchDelay);
293 DefaultFetch<Impl>::setActiveThreads(std::list<unsigned> *at_ptr)
295 activeThreads = at_ptr;
300 DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
304 // Create wire to write information to proper place in fetch queue.
305 toDecode = fetchQueue->getWire(0);
310 DefaultFetch<Impl>::initStage()
312 // Setup PC and nextPC with initial state.
313 for (int tid = 0; tid < numThreads; tid++) {
314 PC[tid] = cpu->readPC(tid);
315 nextPC[tid] = cpu->readNextPC(tid);
316 nextNPC[tid] = cpu->readNextNPC(tid);
319 for (int tid=0; tid < numThreads; tid++) {
321 fetchStatus[tid] = Running;
323 priorityList.push_back(tid);
327 stalls[tid].decode = false;
328 stalls[tid].rename = false;
329 stalls[tid].iew = false;
330 stalls[tid].commit = false;
333 // Schedule fetch to get the correct PC from the CPU
334 // scheduleFetchStartupEvent(1);
336 // Fetch needs to start fetching instructions at the very beginning,
337 // so it must start up in active state.
343 DefaultFetch<Impl>::setIcache()
345 // Size of cache block.
346 cacheBlkSize = icachePort->peerBlockSize();
348 // Create mask to get rid of offset bits.
349 cacheBlkMask = (cacheBlkSize - 1);
351 for (int tid=0; tid < numThreads; tid++) {
352 // Create space to store a cache line.
353 cacheData[tid] = new uint8_t[cacheBlkSize];
354 cacheDataPC[tid] = 0;
355 cacheDataValid[tid] = false;
361 DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
363 unsigned tid = pkt->req->getThreadNum();
365 DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n",tid);
367 // Only change the status if it's still waiting on the icache access
369 if (fetchStatus[tid] != IcacheWaitResponse ||
370 pkt->req != memReq[tid] ||
372 ++fetchIcacheSquashes;
378 memcpy(cacheData[tid], pkt->getPtr<uint8_t>(), cacheBlkSize);
379 cacheDataValid[tid] = true;
382 // Wake up the CPU (if it went to sleep and was waiting on
383 // this completion event).
386 DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
392 // Only switch to IcacheAccessComplete if we're not stalled as well.
393 if (checkStall(tid)) {
394 fetchStatus[tid] = Blocked;
396 fetchStatus[tid] = IcacheAccessComplete;
399 // Reset the mem req to NULL.
405 template <class Impl>
407 DefaultFetch<Impl>::drain()
409 // Fetch is ready to drain at any time.
410 cpu->signalDrained();
415 template <class Impl>
417 DefaultFetch<Impl>::resume()
419 drainPending = false;
422 template <class Impl>
424 DefaultFetch<Impl>::switchOut()
427 // Branch predictor needs to have its state cleared.
428 branchPred.switchOut();
431 template <class Impl>
433 DefaultFetch<Impl>::takeOverFrom()
436 for (int i = 0; i < Impl::MaxThreads; ++i) {
437 stalls[i].decode = 0;
438 stalls[i].rename = 0;
440 stalls[i].commit = 0;
441 PC[i] = cpu->readPC(i);
442 nextPC[i] = cpu->readNextPC(i);
443 #if ISA_HAS_DELAY_SLOT
444 nextNPC[i] = cpu->readNextNPC(i);
446 nextNPC[i] = nextPC[i] + sizeof(TheISA::MachInst);
448 fetchStatus[i] = Running;
451 wroteToTimeBuffer = false;
454 interruptPending = false;
455 branchPred.takeOverFrom();
458 template <class Impl>
460 DefaultFetch<Impl>::wakeFromQuiesce()
462 DPRINTF(Fetch, "Waking up from quiesce\n");
463 // Hopefully this is safe
464 // @todo: Allow other threads to wake from quiesce.
465 fetchStatus[0] = Running;
468 template <class Impl>
470 DefaultFetch<Impl>::switchToActive()
472 if (_status == Inactive) {
473 DPRINTF(Activity, "Activating stage.\n");
475 cpu->activateStage(O3CPU::FetchIdx);
481 template <class Impl>
483 DefaultFetch<Impl>::switchToInactive()
485 if (_status == Active) {
486 DPRINTF(Activity, "Deactivating stage.\n");
488 cpu->deactivateStage(O3CPU::FetchIdx);
494 template <class Impl>
496 DefaultFetch<Impl>::lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC,
499 // Do branch prediction check here.
500 // A bit of a misnomer...next_PC is actually the current PC until
501 // this function updates it.
504 if (!inst->isControl()) {
506 next_NPC = next_NPC + instSize;
507 inst->setPredTarg(next_PC, next_NPC);
508 inst->setPredTaken(false);
512 int tid = inst->threadNumber;
513 Addr pred_PC = next_PC;
514 predict_taken = branchPred.predict(inst, pred_PC, tid);
516 /* if (predict_taken) {
517 DPRINTF(Fetch, "[tid:%i]: Branch predicted to be taken to %#x.\n",
520 DPRINTF(Fetch, "[tid:%i]: Branch predicted to be not taken.\n", tid);
523 #if ISA_HAS_DELAY_SLOT
528 next_NPC += instSize;
534 next_NPC = next_PC + instSize;
536 /* DPRINTF(Fetch, "[tid:%i]: Branch predicted to go to %#x and then %#x.\n",
537 tid, next_PC, next_NPC);*/
538 inst->setPredTarg(next_PC, next_NPC);
539 inst->setPredTaken(predict_taken);
547 return predict_taken;
550 template <class Impl>
552 DefaultFetch<Impl>::fetchCacheLine(Addr fetch_PC, Fault &ret_fault, unsigned tid)
554 Fault fault = NoFault;
558 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
561 } else if (isSwitchedOut()) {
562 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, switched out\n",
565 } else if (interruptPending && !(fetch_PC & 0x3)) {
566 // Hold off fetch from getting new instructions when:
567 // Cache is blocked, or
568 // while an interrupt is pending and we're not in PAL mode, or
569 // fetch is switched out.
570 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n",
575 // Align the fetch PC so it's at the start of a cache block.
576 Addr block_PC = icacheBlockAlignPC(fetch_PC);
578 // If we've already got the block, no need to try to fetch it again.
579 if (cacheDataValid[tid] && block_PC == cacheDataPC[tid]) {
583 // Setup the memReq to do a read of the first instruction's address.
584 // Set the appropriate read size and flags as well.
585 // Build request here.
586 RequestPtr mem_req = new Request(tid, block_PC, cacheBlkSize, 0,
587 fetch_PC, cpu->readCpuId(), tid);
589 memReq[tid] = mem_req;
591 // Translate the instruction request.
592 fault = cpu->translateInstReq(mem_req, cpu->thread[tid]);
594 // In the case of faults, the fetch stage may need to stall and wait
595 // for the ITB miss to be handled.
597 // If translation was successful, attempt to read the first
599 if (fault == NoFault) {
601 if (cpu->system->memctrl->badaddr(memReq[tid]->paddr) ||
602 memReq[tid]->isUncacheable()) {
603 DPRINTF(Fetch, "Fetch: Bad address %#x (hopefully on a "
604 "misspeculating path)!",
606 ret_fault = TheISA::genMachineCheckFault();
611 // Build packet here.
612 PacketPtr data_pkt = new Packet(mem_req,
613 MemCmd::ReadReq, Packet::Broadcast);
614 data_pkt->dataDynamicArray(new uint8_t[cacheBlkSize]);
616 cacheDataPC[tid] = block_PC;
617 cacheDataValid[tid] = false;
619 DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
623 // Now do the timing access to see whether or not the instruction
624 // exists within the cache.
625 if (!icachePort->sendTiming(data_pkt)) {
626 if (data_pkt->result == Packet::BadAddress) {
627 fault = TheISA::genMachineCheckFault();
630 warn("Bad address!\n");
632 assert(retryPkt == NULL);
633 assert(retryTid == -1);
634 DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
635 fetchStatus[tid] = IcacheWaitRetry;
642 DPRINTF(Fetch, "[tid:%i]: Doing cache access.\n", tid);
644 lastIcacheStall[tid] = curTick;
646 DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
649 fetchStatus[tid] = IcacheWaitResponse;
659 template <class Impl>
661 DefaultFetch<Impl>::doSquash(const Addr &new_PC,
662 const Addr &new_NPC, unsigned tid)
664 DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %#x, NPC to: %#x.\n",
665 tid, new_PC, new_NPC);
668 nextPC[tid] = new_NPC;
669 nextNPC[tid] = new_NPC + instSize;
671 // Clear the icache miss if it's outstanding.
672 if (fetchStatus[tid] == IcacheWaitResponse) {
673 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
678 // Get rid of the retrying packet if it was from this thread.
679 if (retryTid == tid) {
680 assert(cacheBlocked);
682 delete retryPkt->req;
689 fetchStatus[tid] = Squashing;
696 DefaultFetch<Impl>::squashFromDecode(const Addr &new_PC, const Addr &new_NPC,
697 const InstSeqNum &seq_num,
700 DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n",tid);
702 doSquash(new_PC, new_NPC, tid);
704 // Tell the CPU to remove any instructions that are in flight between
706 cpu->removeInstsUntil(seq_num, tid);
711 DefaultFetch<Impl>::checkStall(unsigned tid) const
713 bool ret_val = false;
715 if (cpu->contextSwitch) {
716 DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
718 } else if (stalls[tid].decode) {
719 DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
721 } else if (stalls[tid].rename) {
722 DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
724 } else if (stalls[tid].iew) {
725 DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
727 } else if (stalls[tid].commit) {
728 DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
736 typename DefaultFetch<Impl>::FetchStatus
737 DefaultFetch<Impl>::updateFetchStatus()
740 std::list<unsigned>::iterator threads = activeThreads->begin();
741 std::list<unsigned>::iterator end = activeThreads->end();
743 while (threads != end) {
744 unsigned tid = *threads++;
746 if (fetchStatus[tid] == Running ||
747 fetchStatus[tid] == Squashing ||
748 fetchStatus[tid] == IcacheAccessComplete) {
750 if (_status == Inactive) {
751 DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
753 if (fetchStatus[tid] == IcacheAccessComplete) {
754 DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
758 cpu->activateStage(O3CPU::FetchIdx);
765 // Stage is switching from active to inactive, notify CPU of it.
766 if (_status == Active) {
767 DPRINTF(Activity, "Deactivating stage.\n");
769 cpu->deactivateStage(O3CPU::FetchIdx);
775 template <class Impl>
777 DefaultFetch<Impl>::squash(const Addr &new_PC, const Addr &new_NPC,
778 const InstSeqNum &seq_num,
779 bool squash_delay_slot, unsigned tid)
781 DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n",tid);
783 doSquash(new_PC, new_NPC, tid);
785 #if ISA_HAS_DELAY_SLOT
786 // Tell the CPU to remove any instructions that are not in the ROB.
787 cpu->removeInstsNotInROB(tid, squash_delay_slot, seq_num);
789 // Tell the CPU to remove any instructions that are not in the ROB.
790 cpu->removeInstsNotInROB(tid, true, 0);
794 template <class Impl>
796 DefaultFetch<Impl>::tick()
798 std::list<unsigned>::iterator threads = activeThreads->begin();
799 std::list<unsigned>::iterator end = activeThreads->end();
800 bool status_change = false;
802 wroteToTimeBuffer = false;
804 while (threads != end) {
805 unsigned tid = *threads++;
807 // Check the signals for each thread to determine the proper status
809 bool updated_status = checkSignalsAndUpdate(tid);
810 status_change = status_change || updated_status;
813 DPRINTF(Fetch, "Running stage.\n");
815 // Reset the number of the instruction we're fetching.
819 if (fromCommit->commitInfo[0].interruptPending) {
820 interruptPending = true;
823 if (fromCommit->commitInfo[0].clearInterrupt) {
824 interruptPending = false;
828 for (threadFetched = 0; threadFetched < numFetchingThreads;
830 // Fetch each of the actively fetching threads.
831 fetch(status_change);
834 // Record number of instructions fetched this cycle for distribution.
835 fetchNisnDist.sample(numInst);
838 // Change the fetch stage status if there was a status change.
839 _status = updateFetchStatus();
842 // If there was activity this cycle, inform the CPU of it.
843 if (wroteToTimeBuffer || cpu->contextSwitch) {
844 DPRINTF(Activity, "Activity this cycle.\n");
846 cpu->activityThisCycle();
850 template <class Impl>
852 DefaultFetch<Impl>::checkSignalsAndUpdate(unsigned tid)
854 // Update the per thread stall statuses.
855 if (fromDecode->decodeBlock[tid]) {
856 stalls[tid].decode = true;
859 if (fromDecode->decodeUnblock[tid]) {
860 assert(stalls[tid].decode);
861 assert(!fromDecode->decodeBlock[tid]);
862 stalls[tid].decode = false;
865 if (fromRename->renameBlock[tid]) {
866 stalls[tid].rename = true;
869 if (fromRename->renameUnblock[tid]) {
870 assert(stalls[tid].rename);
871 assert(!fromRename->renameBlock[tid]);
872 stalls[tid].rename = false;
875 if (fromIEW->iewBlock[tid]) {
876 stalls[tid].iew = true;
879 if (fromIEW->iewUnblock[tid]) {
880 assert(stalls[tid].iew);
881 assert(!fromIEW->iewBlock[tid]);
882 stalls[tid].iew = false;
885 if (fromCommit->commitBlock[tid]) {
886 stalls[tid].commit = true;
889 if (fromCommit->commitUnblock[tid]) {
890 assert(stalls[tid].commit);
891 assert(!fromCommit->commitBlock[tid]);
892 stalls[tid].commit = false;
895 // Check squash signals from commit.
896 if (fromCommit->commitInfo[tid].squash) {
898 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
899 "from commit.\n",tid);
901 #if ISA_HAS_DELAY_SLOT
902 InstSeqNum doneSeqNum = fromCommit->commitInfo[tid].bdelayDoneSeqNum;
904 InstSeqNum doneSeqNum = fromCommit->commitInfo[tid].doneSeqNum;
906 // In any case, squash.
907 squash(fromCommit->commitInfo[tid].nextPC,
908 fromCommit->commitInfo[tid].nextNPC,
910 fromCommit->commitInfo[tid].squashDelaySlot,
913 // Also check if there's a mispredict that happened.
914 if (fromCommit->commitInfo[tid].branchMispredict) {
915 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
916 fromCommit->commitInfo[tid].nextPC,
917 fromCommit->commitInfo[tid].branchTaken,
920 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
925 } else if (fromCommit->commitInfo[tid].doneSeqNum) {
926 // Update the branch predictor if it wasn't a squashed instruction
927 // that was broadcasted.
928 branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
931 // Check ROB squash signals from commit.
932 if (fromCommit->commitInfo[tid].robSquashing) {
933 DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
935 // Continue to squash.
936 fetchStatus[tid] = Squashing;
941 // Check squash signals from decode.
942 if (fromDecode->decodeInfo[tid].squash) {
943 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
944 "from decode.\n",tid);
946 // Update the branch predictor.
947 if (fromDecode->decodeInfo[tid].branchMispredict) {
948 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
949 fromDecode->decodeInfo[tid].nextPC,
950 fromDecode->decodeInfo[tid].branchTaken,
953 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
957 if (fetchStatus[tid] != Squashing) {
959 #if ISA_HAS_DELAY_SLOT
960 InstSeqNum doneSeqNum = fromDecode->decodeInfo[tid].bdelayDoneSeqNum;
962 InstSeqNum doneSeqNum = fromDecode->decodeInfo[tid].doneSeqNum;
964 DPRINTF(Fetch, "Squashing from decode with PC = %#x, NPC = %#x\n",
965 fromDecode->decodeInfo[tid].nextPC,
966 fromDecode->decodeInfo[tid].nextNPC);
967 // Squash unless we're already squashing
968 squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
969 fromDecode->decodeInfo[tid].nextNPC,
977 if (checkStall(tid) &&
978 fetchStatus[tid] != IcacheWaitResponse &&
979 fetchStatus[tid] != IcacheWaitRetry) {
980 DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
982 fetchStatus[tid] = Blocked;
987 if (fetchStatus[tid] == Blocked ||
988 fetchStatus[tid] == Squashing) {
989 // Switch status to running if fetch isn't being told to block or
990 // squash this cycle.
991 DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
994 fetchStatus[tid] = Running;
999 // If we've reached this point, we have not gotten any signals that
1000 // cause fetch to change its status. Fetch remains the same as before.
1004 template<class Impl>
1006 DefaultFetch<Impl>::fetch(bool &status_change)
1008 //////////////////////////////////////////
1009 // Start actual fetch
1010 //////////////////////////////////////////
1011 int tid = getFetchingThread(fetchPolicy);
1013 if (tid == -1 || drainPending) {
1014 DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
1016 // Breaks looping condition in tick()
1017 threadFetched = numFetchingThreads;
1021 DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
1024 Addr &fetch_PC = PC[tid];
1026 Addr &fetch_NPC = nextPC[tid];
1028 // Fault code for memory access.
1029 Fault fault = NoFault;
1031 // If returning from the delay of a cache miss, then update the status
1032 // to running, otherwise do the cache access. Possibly move this up
1033 // to tick() function.
1034 if (fetchStatus[tid] == IcacheAccessComplete) {
1035 DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n",
1038 fetchStatus[tid] = Running;
1039 status_change = true;
1040 } else if (fetchStatus[tid] == Running) {
1041 DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
1042 "instruction, starting at PC %08p.\n",
1045 bool fetch_success = fetchCacheLine(fetch_PC, fault, tid);
1046 if (!fetch_success) {
1048 ++icacheStallCycles;
1050 ++fetchMiscStallCycles;
1055 if (fetchStatus[tid] == Idle) {
1057 DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
1058 } else if (fetchStatus[tid] == Blocked) {
1059 ++fetchBlockedCycles;
1060 DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
1061 } else if (fetchStatus[tid] == Squashing) {
1062 ++fetchSquashCycles;
1063 DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
1064 } else if (fetchStatus[tid] == IcacheWaitResponse) {
1065 ++icacheStallCycles;
1066 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n", tid);
1069 // Status is Idle, Squashing, Blocked, or IcacheWaitResponse, so
1070 // fetch should do nothing.
1076 // If we had a stall due to an icache miss, then return.
1077 if (fetchStatus[tid] == IcacheWaitResponse) {
1078 ++icacheStallCycles;
1079 status_change = true;
1083 Addr next_PC = fetch_PC;
1084 Addr next_NPC = fetch_NPC;
1086 InstSeqNum inst_seq;
1088 ExtMachInst ext_inst;
1089 // @todo: Fix this hack.
1090 unsigned offset = (fetch_PC & cacheBlkMask) & ~3;
1092 if (fault == NoFault) {
1093 // If the read of the first instruction was successful, then grab the
1094 // instructions from the rest of the cache line and put them into the
1095 // queue heading to decode.
1097 DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
1100 // Need to keep track of whether or not a predicted branch
1101 // ended this fetch block.
1102 bool predicted_branch = false;
1105 offset < cacheBlkSize &&
1106 numInst < fetchWidth &&
1110 // If we're branching after this instruction, quite fetching
1111 // from the same block then.
1113 (fetch_PC + sizeof(TheISA::MachInst) != fetch_NPC);
1114 if (predicted_branch) {
1115 DPRINTF(Fetch, "Branch detected with PC = %#x, NPC = %#x\n",
1116 fetch_PC, fetch_NPC);
1120 // Get a sequence number.
1121 inst_seq = cpu->getAndIncrementInstSeq();
1123 // Make sure this is a valid index.
1124 assert(offset <= cacheBlkSize - instSize);
1126 // Get the instruction from the array of the cache line.
1127 inst = TheISA::gtoh(*reinterpret_cast<TheISA::MachInst *>
1128 (&cacheData[tid][offset]));
1130 predecoder.setTC(cpu->thread[tid]->getTC());
1131 predecoder.moreBytes(fetch_PC, fetch_PC, inst);
1133 ext_inst = predecoder.getExtMachInst();
1135 // Create a new DynInst from the instruction fetched.
1136 DynInstPtr instruction = new DynInst(ext_inst,
1137 fetch_PC, fetch_NPC,
1140 instruction->setTid(tid);
1142 instruction->setASID(tid);
1144 instruction->setThreadState(cpu->thread[tid]);
1146 DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x created "
1148 tid, instruction->readPC(), inst_seq);
1150 //DPRINTF(Fetch, "[tid:%i]: MachInst is %#x\n", tid, ext_inst);
1152 DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n",
1153 tid, instruction->staticInst->disassemble(fetch_PC));
1156 instruction->traceData =
1157 Trace::getInstRecord(curTick, cpu->tcBase(tid),
1158 instruction->staticInst,
1159 instruction->readPC());
1161 instruction->traceData = NULL;
1164 ///FIXME This needs to be more robust in dealing with delay slots
1165 #if !ISA_HAS_DELAY_SLOT
1166 // predicted_branch |=
1168 lookupAndUpdateNextPC(instruction, next_PC, next_NPC);
1169 predicted_branch |= (next_PC != fetch_NPC);
1171 // Add instruction to the CPU's list of instructions.
1172 instruction->setInstListIt(cpu->addInst(instruction));
1174 // Write the instruction to the first slot in the queue
1175 // that heads to decode.
1176 toDecode->insts[numInst] = instruction;
1180 // Increment stat of fetched instructions.
1183 // Move to the next instruction, unless we have a branch.
1185 fetch_NPC = next_NPC;
1187 if (instruction->isQuiesce()) {
1188 DPRINTF(Fetch, "Quiesce instruction encountered, halting fetch!",
1190 fetchStatus[tid] = QuiescePending;
1192 status_change = true;
1199 if (offset >= cacheBlkSize) {
1200 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of cache "
1202 } else if (numInst >= fetchWidth) {
1203 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
1204 "for this cycle.\n", tid);
1205 } else if (predicted_branch) {
1206 DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
1207 "instruction encountered.\n", tid);
1212 wroteToTimeBuffer = true;
1215 // Now that fetching is completed, update the PC to signify what the next
1217 if (fault == NoFault) {
1219 nextPC[tid] = next_NPC;
1220 nextNPC[tid] = next_NPC + instSize;
1221 #if ISA_HAS_DELAY_SLOT
1222 DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n", tid, PC[tid]);
1224 DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n", tid, next_PC);
1227 // We shouldn't be in an icache miss and also have a fault (an ITB
1229 if (fetchStatus[tid] == IcacheWaitResponse) {
1230 panic("Fetch should have exited prior to this!");
1233 // Send the fault to commit. This thread will not do anything
1234 // until commit handles the fault. The only other way it can
1235 // wake up is if a squash comes along and changes the PC.
1237 assert(numInst < fetchWidth);
1238 // Get a sequence number.
1239 inst_seq = cpu->getAndIncrementInstSeq();
1240 // We will use a nop in order to carry the fault.
1241 ext_inst = TheISA::NoopMachInst;
1243 // Create a new DynInst from the dummy nop.
1244 DynInstPtr instruction = new DynInst(ext_inst,
1245 fetch_PC, fetch_NPC,
1248 instruction->setPredTarg(next_PC, next_NPC);
1249 instruction->setTid(tid);
1251 instruction->setASID(tid);
1253 instruction->setThreadState(cpu->thread[tid]);
1255 instruction->traceData = NULL;
1257 instruction->setInstListIt(cpu->addInst(instruction));
1259 instruction->fault = fault;
1261 toDecode->insts[numInst] = instruction;
1264 DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n",tid);
1266 fetchStatus[tid] = TrapPending;
1267 status_change = true;
1268 #else // !FULL_SYSTEM
1269 fetchStatus[tid] = TrapPending;
1270 status_change = true;
1272 #endif // FULL_SYSTEM
1273 DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %08p",
1274 tid, fault->name(), PC[tid]);
1278 template<class Impl>
1280 DefaultFetch<Impl>::recvRetry()
1282 if (retryPkt != NULL) {
1283 assert(cacheBlocked);
1284 assert(retryTid != -1);
1285 assert(fetchStatus[retryTid] == IcacheWaitRetry);
1287 if (icachePort->sendTiming(retryPkt)) {
1288 fetchStatus[retryTid] = IcacheWaitResponse;
1291 cacheBlocked = false;
1294 assert(retryTid == -1);
1295 // Access has been squashed since it was sent out. Just clear
1296 // the cache being blocked.
1297 cacheBlocked = false;
1301 ///////////////////////////////////////
1303 // SMT FETCH POLICY MAINTAINED HERE //
1305 ///////////////////////////////////////
1306 template<class Impl>
1308 DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1310 if (numThreads > 1) {
1311 switch (fetch_priority) {
1317 return roundRobin();
1326 return branchCount();
1332 std::list<unsigned>::iterator thread = activeThreads->begin();
1333 assert(thread != activeThreads->end());
1336 if (fetchStatus[tid] == Running ||
1337 fetchStatus[tid] == IcacheAccessComplete ||
1338 fetchStatus[tid] == Idle) {
1348 template<class Impl>
1350 DefaultFetch<Impl>::roundRobin()
1352 std::list<unsigned>::iterator pri_iter = priorityList.begin();
1353 std::list<unsigned>::iterator end = priorityList.end();
1357 while (pri_iter != end) {
1358 high_pri = *pri_iter;
1360 assert(high_pri <= numThreads);
1362 if (fetchStatus[high_pri] == Running ||
1363 fetchStatus[high_pri] == IcacheAccessComplete ||
1364 fetchStatus[high_pri] == Idle) {
1366 priorityList.erase(pri_iter);
1367 priorityList.push_back(high_pri);
1378 template<class Impl>
1380 DefaultFetch<Impl>::iqCount()
1382 std::priority_queue<unsigned> PQ;
1384 std::list<unsigned>::iterator threads = activeThreads->begin();
1385 std::list<unsigned>::iterator end = activeThreads->end();
1387 while (threads != end) {
1388 unsigned tid = *threads++;
1390 PQ.push(fromIEW->iewInfo[tid].iqCount);
1393 while (!PQ.empty()) {
1395 unsigned high_pri = PQ.top();
1397 if (fetchStatus[high_pri] == Running ||
1398 fetchStatus[high_pri] == IcacheAccessComplete ||
1399 fetchStatus[high_pri] == Idle)
1409 template<class Impl>
1411 DefaultFetch<Impl>::lsqCount()
1413 std::priority_queue<unsigned> PQ;
1415 std::list<unsigned>::iterator threads = activeThreads->begin();
1416 std::list<unsigned>::iterator end = activeThreads->end();
1418 while (threads != end) {
1419 unsigned tid = *threads++;
1421 PQ.push(fromIEW->iewInfo[tid].ldstqCount);
1424 while (!PQ.empty()) {
1426 unsigned high_pri = PQ.top();
1428 if (fetchStatus[high_pri] == Running ||
1429 fetchStatus[high_pri] == IcacheAccessComplete ||
1430 fetchStatus[high_pri] == Idle)
1440 template<class Impl>
1442 DefaultFetch<Impl>::branchCount()
1444 std::list<unsigned>::iterator thread = activeThreads->begin();
1445 assert(thread != activeThreads->end());
1446 unsigned tid = *thread;
1448 panic("Branch Count Fetch policy unimplemented\n");