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 "arch/isa_traits.hh"
36 #include "arch/utility.hh"
37 #include "base/types.hh"
38 #include "config/the_isa.hh"
39 #include "config/use_checker.hh"
40 #include "cpu/checker/cpu.hh"
41 #include "cpu/exetrace.hh"
42 #include "cpu/o3/fetch.hh"
43 #include "mem/packet.hh"
44 #include "mem/request.hh"
45 #include "params/DerivO3CPU.hh"
46 #include "sim/byteswap.hh"
47 #include "sim/core.hh"
50 #include "arch/tlb.hh"
51 #include "arch/vtophys.hh"
52 #include "sim/system.hh"
59 DefaultFetch<Impl>::IcachePort::setPeer(Port *port)
68 DefaultFetch<Impl>::IcachePort::recvAtomic(PacketPtr pkt)
70 panic("DefaultFetch doesn't expect recvAtomic callback!");
76 DefaultFetch<Impl>::IcachePort::recvFunctional(PacketPtr pkt)
78 DPRINTF(Fetch, "DefaultFetch doesn't update its state from a "
84 DefaultFetch<Impl>::IcachePort::recvStatusChange(Status status)
86 if (status == RangeChange) {
87 if (!snoopRangeSent) {
88 snoopRangeSent = true;
89 sendStatusChange(Port::RangeChange);
94 panic("DefaultFetch doesn't expect recvStatusChange callback!");
99 DefaultFetch<Impl>::IcachePort::recvTiming(PacketPtr pkt)
101 DPRINTF(Fetch, "Received timing\n");
102 if (pkt->isResponse()) {
103 fetch->processCacheCompletion(pkt);
105 //else Snooped a coherence request, just return
111 DefaultFetch<Impl>::IcachePort::recvRetry()
117 DefaultFetch<Impl>::DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params)
121 decodeToFetchDelay(params->decodeToFetchDelay),
122 renameToFetchDelay(params->renameToFetchDelay),
123 iewToFetchDelay(params->iewToFetchDelay),
124 commitToFetchDelay(params->commitToFetchDelay),
125 fetchWidth(params->fetchWidth),
128 retryTid(InvalidThreadID),
129 numThreads(params->numThreads),
130 numFetchingThreads(params->smtNumFetchingThreads),
131 interruptPending(false),
135 if (numThreads > Impl::MaxThreads)
136 fatal("numThreads (%d) is larger than compiled limit (%d),\n"
137 "\tincrease MaxThreads in src/cpu/o3/impl.hh\n",
138 numThreads, static_cast<int>(Impl::MaxThreads));
140 // Set fetch stage's status to inactive.
143 std::string policy = params->smtFetchPolicy;
145 // Convert string to lowercase
146 std::transform(policy.begin(), policy.end(), policy.begin(),
147 (int(*)(int)) tolower);
149 // Figure out fetch policy
150 if (policy == "singlethread") {
151 fetchPolicy = SingleThread;
153 panic("Invalid Fetch Policy for a SMT workload.");
154 } else if (policy == "roundrobin") {
155 fetchPolicy = RoundRobin;
156 DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
157 } else if (policy == "branch") {
158 fetchPolicy = Branch;
159 DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
160 } else if (policy == "iqcount") {
162 DPRINTF(Fetch, "Fetch policy set to IQ count\n");
163 } else if (policy == "lsqcount") {
165 DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
167 fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
168 " RoundRobin,LSQcount,IQcount}\n");
171 // Get the size of an instruction.
172 instSize = sizeof(TheISA::MachInst);
174 // Name is finally available, so create the port.
175 icachePort = new IcachePort(this);
177 icachePort->snoopRangeSent = false;
181 cpu->checker->setIcachePort(icachePort);
186 template <class Impl>
188 DefaultFetch<Impl>::name() const
190 return cpu->name() + ".fetch";
193 template <class Impl>
195 DefaultFetch<Impl>::regStats()
198 .name(name() + ".icacheStallCycles")
199 .desc("Number of cycles fetch is stalled on an Icache miss")
200 .prereq(icacheStallCycles);
203 .name(name() + ".Insts")
204 .desc("Number of instructions fetch has processed")
205 .prereq(fetchedInsts);
208 .name(name() + ".Branches")
209 .desc("Number of branches that fetch encountered")
210 .prereq(fetchedBranches);
213 .name(name() + ".predictedBranches")
214 .desc("Number of branches that fetch has predicted taken")
215 .prereq(predictedBranches);
218 .name(name() + ".Cycles")
219 .desc("Number of cycles fetch has run and was not squashing or"
221 .prereq(fetchCycles);
224 .name(name() + ".SquashCycles")
225 .desc("Number of cycles fetch has spent squashing")
226 .prereq(fetchSquashCycles);
229 .name(name() + ".IdleCycles")
230 .desc("Number of cycles fetch was idle")
231 .prereq(fetchIdleCycles);
234 .name(name() + ".BlockedCycles")
235 .desc("Number of cycles fetch has spent blocked")
236 .prereq(fetchBlockedCycles);
239 .name(name() + ".CacheLines")
240 .desc("Number of cache lines fetched")
241 .prereq(fetchedCacheLines);
244 .name(name() + ".MiscStallCycles")
245 .desc("Number of cycles fetch has spent waiting on interrupts, or "
246 "bad addresses, or out of MSHRs")
247 .prereq(fetchMiscStallCycles);
250 .name(name() + ".IcacheSquashes")
251 .desc("Number of outstanding Icache misses that were squashed")
252 .prereq(fetchIcacheSquashes);
255 .init(/* base value */ 0,
256 /* last value */ fetchWidth,
258 .name(name() + ".rateDist")
259 .desc("Number of instructions fetched each cycle (Total)")
263 .name(name() + ".idleRate")
264 .desc("Percent of cycles fetch was idle")
266 idleRate = fetchIdleCycles * 100 / cpu->numCycles;
269 .name(name() + ".branchRate")
270 .desc("Number of branch fetches per cycle")
271 .flags(Stats::total);
272 branchRate = fetchedBranches / cpu->numCycles;
275 .name(name() + ".rate")
276 .desc("Number of inst fetches per cycle")
277 .flags(Stats::total);
278 fetchRate = fetchedInsts / cpu->numCycles;
280 branchPred.regStats();
285 DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
287 timeBuffer = time_buffer;
289 // Create wires to get information from proper places in time buffer.
290 fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
291 fromRename = timeBuffer->getWire(-renameToFetchDelay);
292 fromIEW = timeBuffer->getWire(-iewToFetchDelay);
293 fromCommit = timeBuffer->getWire(-commitToFetchDelay);
298 DefaultFetch<Impl>::setActiveThreads(std::list<ThreadID> *at_ptr)
300 activeThreads = at_ptr;
305 DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
309 // Create wire to write information to proper place in fetch queue.
310 toDecode = fetchQueue->getWire(0);
315 DefaultFetch<Impl>::initStage()
317 // Setup PC and nextPC with initial state.
318 for (ThreadID tid = 0; tid < numThreads; tid++) {
319 PC[tid] = cpu->readPC(tid);
320 nextPC[tid] = cpu->readNextPC(tid);
321 microPC[tid] = cpu->readMicroPC(tid);
324 for (ThreadID tid = 0; tid < numThreads; tid++) {
326 fetchStatus[tid] = Running;
328 priorityList.push_back(tid);
332 stalls[tid].decode = false;
333 stalls[tid].rename = false;
334 stalls[tid].iew = false;
335 stalls[tid].commit = false;
338 // Schedule fetch to get the correct PC from the CPU
339 // scheduleFetchStartupEvent(1);
341 // Fetch needs to start fetching instructions at the very beginning,
342 // so it must start up in active state.
348 DefaultFetch<Impl>::setIcache()
350 // Size of cache block.
351 cacheBlkSize = icachePort->peerBlockSize();
353 // Create mask to get rid of offset bits.
354 cacheBlkMask = (cacheBlkSize - 1);
356 for (ThreadID tid = 0; tid < numThreads; tid++) {
357 // Create space to store a cache line.
358 cacheData[tid] = new uint8_t[cacheBlkSize];
359 cacheDataPC[tid] = 0;
360 cacheDataValid[tid] = false;
366 DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
368 ThreadID tid = pkt->req->threadId();
370 DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n",tid);
372 assert(!pkt->wasNacked());
374 // Only change the status if it's still waiting on the icache access
376 if (fetchStatus[tid] != IcacheWaitResponse ||
377 pkt->req != memReq[tid] ||
379 ++fetchIcacheSquashes;
385 memcpy(cacheData[tid], pkt->getPtr<uint8_t>(), cacheBlkSize);
386 cacheDataValid[tid] = true;
389 // Wake up the CPU (if it went to sleep and was waiting on
390 // this completion event).
393 DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
399 // Only switch to IcacheAccessComplete if we're not stalled as well.
400 if (checkStall(tid)) {
401 fetchStatus[tid] = Blocked;
403 fetchStatus[tid] = IcacheAccessComplete;
406 // Reset the mem req to NULL.
412 template <class Impl>
414 DefaultFetch<Impl>::drain()
416 // Fetch is ready to drain at any time.
417 cpu->signalDrained();
422 template <class Impl>
424 DefaultFetch<Impl>::resume()
426 drainPending = false;
429 template <class Impl>
431 DefaultFetch<Impl>::switchOut()
434 // Branch predictor needs to have its state cleared.
435 branchPred.switchOut();
438 template <class Impl>
440 DefaultFetch<Impl>::takeOverFrom()
443 for (ThreadID i = 0; i < Impl::MaxThreads; ++i) {
444 stalls[i].decode = 0;
445 stalls[i].rename = 0;
447 stalls[i].commit = 0;
448 PC[i] = cpu->readPC(i);
449 nextPC[i] = cpu->readNextPC(i);
450 microPC[i] = cpu->readMicroPC(i);
451 fetchStatus[i] = Running;
454 wroteToTimeBuffer = false;
457 interruptPending = false;
458 branchPred.takeOverFrom();
461 template <class Impl>
463 DefaultFetch<Impl>::wakeFromQuiesce()
465 DPRINTF(Fetch, "Waking up from quiesce\n");
466 // Hopefully this is safe
467 // @todo: Allow other threads to wake from quiesce.
468 fetchStatus[0] = Running;
471 template <class Impl>
473 DefaultFetch<Impl>::switchToActive()
475 if (_status == Inactive) {
476 DPRINTF(Activity, "Activating stage.\n");
478 cpu->activateStage(O3CPU::FetchIdx);
484 template <class Impl>
486 DefaultFetch<Impl>::switchToInactive()
488 if (_status == Active) {
489 DPRINTF(Activity, "Deactivating stage.\n");
491 cpu->deactivateStage(O3CPU::FetchIdx);
497 template <class Impl>
499 DefaultFetch<Impl>::lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC,
500 Addr &next_NPC, Addr &next_MicroPC)
502 // Do branch prediction check here.
503 // A bit of a misnomer...next_PC is actually the current PC until
504 // this function updates it.
507 if (!inst->isControl()) {
508 if (inst->isMicroop() && !inst->isLastMicroop()) {
512 next_NPC = next_NPC + instSize;
515 inst->setPredTarg(next_PC, next_NPC, next_MicroPC);
516 inst->setPredTaken(false);
520 //Assume for now that all control flow is to a different macroop which
521 //would reset the micro pc to 0.
524 ThreadID tid = inst->threadNumber;
525 Addr pred_PC = next_PC;
526 predict_taken = branchPred.predict(inst, pred_PC, tid);
529 DPRINTF(Fetch, "[tid:%i]: [sn:%i]: Branch predicted to be taken to %#x.\n",
530 tid, inst->seqNum, pred_PC);
532 DPRINTF(Fetch, "[tid:%i]: [sn:%i]:Branch predicted to be not taken.\n",
536 #if ISA_HAS_DELAY_SLOT
541 next_NPC += instSize;
547 next_NPC = next_PC + instSize;
550 DPRINTF(Fetch, "[tid:%i]: [sn:%i] Branch predicted to go to %#x and then %#x.\n",
551 tid, inst->seqNum, next_PC, next_NPC);
552 inst->setPredTarg(next_PC, next_NPC, next_MicroPC);
553 inst->setPredTaken(predict_taken);
561 return predict_taken;
564 template <class Impl>
566 DefaultFetch<Impl>::fetchCacheLine(Addr fetch_PC, Fault &ret_fault, ThreadID tid)
568 Fault fault = NoFault;
572 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
575 } else if (isSwitchedOut()) {
576 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, switched out\n",
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",
589 // Align the fetch PC so it's at the start of a cache block.
590 Addr block_PC = icacheBlockAlignPC(fetch_PC);
592 // If we've already got the block, no need to try to fetch it again.
593 if (cacheDataValid[tid] && block_PC == cacheDataPC[tid]) {
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.
601 new Request(tid, block_PC, cacheBlkSize, Request::INST_FETCH,
602 fetch_PC, cpu->thread[tid]->contextId(), tid);
604 memReq[tid] = mem_req;
606 // Translate the instruction request.
607 fault = cpu->itb->translateAtomic(mem_req, cpu->thread[tid]->getTC(),
610 // In the case of faults, the fetch stage may need to stall and wait
611 // for the ITB miss to be handled.
613 // If translation was successful, attempt to read the first
615 if (fault == NoFault) {
617 if (cpu->system->memctrl->badaddr(memReq[tid]->paddr) ||
618 memReq[tid]->isUncacheable()) {
619 DPRINTF(Fetch, "Fetch: Bad address %#x (hopefully on a "
620 "misspeculating path)!",
622 ret_fault = TheISA::genMachineCheckFault();
627 // Build packet here.
628 PacketPtr data_pkt = new Packet(mem_req,
629 MemCmd::ReadReq, Packet::Broadcast);
630 data_pkt->dataDynamicArray(new uint8_t[cacheBlkSize]);
632 cacheDataPC[tid] = block_PC;
633 cacheDataValid[tid] = false;
635 DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
639 // Now do the timing access to see whether or not the instruction
640 // exists within the cache.
641 if (!icachePort->sendTiming(data_pkt)) {
642 assert(retryPkt == NULL);
643 assert(retryTid == InvalidThreadID);
644 DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
645 fetchStatus[tid] = IcacheWaitRetry;
652 DPRINTF(Fetch, "[tid:%i]: Doing cache access.\n", tid);
654 lastIcacheStall[tid] = curTick;
656 DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
659 fetchStatus[tid] = IcacheWaitResponse;
669 template <class Impl>
671 DefaultFetch<Impl>::doSquash(const Addr &new_PC,
672 const Addr &new_NPC, const Addr &new_microPC, ThreadID tid)
674 DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %#x, NPC to: %#x.\n",
675 tid, new_PC, new_NPC);
678 nextPC[tid] = new_NPC;
679 microPC[tid] = new_microPC;
681 // Clear the icache miss if it's outstanding.
682 if (fetchStatus[tid] == IcacheWaitResponse) {
683 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
688 // Get rid of the retrying packet if it was from this thread.
689 if (retryTid == tid) {
690 assert(cacheBlocked);
692 delete retryPkt->req;
696 retryTid = InvalidThreadID;
699 fetchStatus[tid] = Squashing;
706 DefaultFetch<Impl>::squashFromDecode(const Addr &new_PC, const Addr &new_NPC,
707 const Addr &new_MicroPC,
708 const InstSeqNum &seq_num, ThreadID tid)
710 DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n",tid);
712 doSquash(new_PC, new_NPC, new_MicroPC, tid);
714 // Tell the CPU to remove any instructions that are in flight between
716 cpu->removeInstsUntil(seq_num, tid);
721 DefaultFetch<Impl>::checkStall(ThreadID tid) const
723 bool ret_val = false;
725 if (cpu->contextSwitch) {
726 DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
728 } else if (stalls[tid].decode) {
729 DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
731 } else if (stalls[tid].rename) {
732 DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
734 } else if (stalls[tid].iew) {
735 DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
737 } else if (stalls[tid].commit) {
738 DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
746 typename DefaultFetch<Impl>::FetchStatus
747 DefaultFetch<Impl>::updateFetchStatus()
750 list<ThreadID>::iterator threads = activeThreads->begin();
751 list<ThreadID>::iterator end = activeThreads->end();
753 while (threads != end) {
754 ThreadID tid = *threads++;
756 if (fetchStatus[tid] == Running ||
757 fetchStatus[tid] == Squashing ||
758 fetchStatus[tid] == IcacheAccessComplete) {
760 if (_status == Inactive) {
761 DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
763 if (fetchStatus[tid] == IcacheAccessComplete) {
764 DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
768 cpu->activateStage(O3CPU::FetchIdx);
775 // Stage is switching from active to inactive, notify CPU of it.
776 if (_status == Active) {
777 DPRINTF(Activity, "Deactivating stage.\n");
779 cpu->deactivateStage(O3CPU::FetchIdx);
785 template <class Impl>
787 DefaultFetch<Impl>::squash(const Addr &new_PC, const Addr &new_NPC,
788 const Addr &new_MicroPC,
789 const InstSeqNum &seq_num, ThreadID tid)
791 DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n",tid);
793 doSquash(new_PC, new_NPC, new_MicroPC, tid);
795 // Tell the CPU to remove any instructions that are not in the ROB.
796 cpu->removeInstsNotInROB(tid);
799 template <class Impl>
801 DefaultFetch<Impl>::tick()
803 list<ThreadID>::iterator threads = activeThreads->begin();
804 list<ThreadID>::iterator end = activeThreads->end();
805 bool status_change = false;
807 wroteToTimeBuffer = false;
809 while (threads != end) {
810 ThreadID tid = *threads++;
812 // Check the signals for each thread to determine the proper status
814 bool updated_status = checkSignalsAndUpdate(tid);
815 status_change = status_change || updated_status;
818 DPRINTF(Fetch, "Running stage.\n");
820 // Reset the number of the instruction we're fetching.
824 if (fromCommit->commitInfo[0].interruptPending) {
825 interruptPending = true;
828 if (fromCommit->commitInfo[0].clearInterrupt) {
829 interruptPending = false;
833 for (threadFetched = 0; threadFetched < numFetchingThreads;
835 // Fetch each of the actively fetching threads.
836 fetch(status_change);
839 // Record number of instructions fetched this cycle for distribution.
840 fetchNisnDist.sample(numInst);
843 // Change the fetch stage status if there was a status change.
844 _status = updateFetchStatus();
847 // If there was activity this cycle, inform the CPU of it.
848 if (wroteToTimeBuffer || cpu->contextSwitch) {
849 DPRINTF(Activity, "Activity this cycle.\n");
851 cpu->activityThisCycle();
855 template <class Impl>
857 DefaultFetch<Impl>::checkSignalsAndUpdate(ThreadID tid)
859 // Update the per thread stall statuses.
860 if (fromDecode->decodeBlock[tid]) {
861 stalls[tid].decode = true;
864 if (fromDecode->decodeUnblock[tid]) {
865 assert(stalls[tid].decode);
866 assert(!fromDecode->decodeBlock[tid]);
867 stalls[tid].decode = false;
870 if (fromRename->renameBlock[tid]) {
871 stalls[tid].rename = true;
874 if (fromRename->renameUnblock[tid]) {
875 assert(stalls[tid].rename);
876 assert(!fromRename->renameBlock[tid]);
877 stalls[tid].rename = false;
880 if (fromIEW->iewBlock[tid]) {
881 stalls[tid].iew = true;
884 if (fromIEW->iewUnblock[tid]) {
885 assert(stalls[tid].iew);
886 assert(!fromIEW->iewBlock[tid]);
887 stalls[tid].iew = false;
890 if (fromCommit->commitBlock[tid]) {
891 stalls[tid].commit = true;
894 if (fromCommit->commitUnblock[tid]) {
895 assert(stalls[tid].commit);
896 assert(!fromCommit->commitBlock[tid]);
897 stalls[tid].commit = false;
900 // Check squash signals from commit.
901 if (fromCommit->commitInfo[tid].squash) {
903 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
904 "from commit.\n",tid);
905 // In any case, squash.
906 squash(fromCommit->commitInfo[tid].nextPC,
907 fromCommit->commitInfo[tid].nextNPC,
908 fromCommit->commitInfo[tid].nextMicroPC,
909 fromCommit->commitInfo[tid].doneSeqNum,
912 // Also check if there's a mispredict that happened.
913 if (fromCommit->commitInfo[tid].branchMispredict) {
914 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
915 fromCommit->commitInfo[tid].nextPC,
916 fromCommit->commitInfo[tid].branchTaken,
919 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
924 } else if (fromCommit->commitInfo[tid].doneSeqNum) {
925 // Update the branch predictor if it wasn't a squashed instruction
926 // that was broadcasted.
927 branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
930 // Check ROB squash signals from commit.
931 if (fromCommit->commitInfo[tid].robSquashing) {
932 DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
934 // Continue to squash.
935 fetchStatus[tid] = Squashing;
940 // Check squash signals from decode.
941 if (fromDecode->decodeInfo[tid].squash) {
942 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
943 "from decode.\n",tid);
945 // Update the branch predictor.
946 if (fromDecode->decodeInfo[tid].branchMispredict) {
947 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
948 fromDecode->decodeInfo[tid].nextPC,
949 fromDecode->decodeInfo[tid].branchTaken,
952 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
956 if (fetchStatus[tid] != Squashing) {
958 DPRINTF(Fetch, "Squashing from decode with PC = %#x, NPC = %#x\n",
959 fromDecode->decodeInfo[tid].nextPC,
960 fromDecode->decodeInfo[tid].nextNPC);
961 // Squash unless we're already squashing
962 squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
963 fromDecode->decodeInfo[tid].nextNPC,
964 fromDecode->decodeInfo[tid].nextMicroPC,
965 fromDecode->decodeInfo[tid].doneSeqNum,
972 if (checkStall(tid) &&
973 fetchStatus[tid] != IcacheWaitResponse &&
974 fetchStatus[tid] != IcacheWaitRetry) {
975 DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
977 fetchStatus[tid] = Blocked;
982 if (fetchStatus[tid] == Blocked ||
983 fetchStatus[tid] == Squashing) {
984 // Switch status to running if fetch isn't being told to block or
985 // squash this cycle.
986 DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
989 fetchStatus[tid] = Running;
994 // If we've reached this point, we have not gotten any signals that
995 // cause fetch to change its status. Fetch remains the same as before.
1001 DefaultFetch<Impl>::fetch(bool &status_change)
1003 //////////////////////////////////////////
1004 // Start actual fetch
1005 //////////////////////////////////////////
1006 ThreadID tid = getFetchingThread(fetchPolicy);
1008 if (tid == InvalidThreadID || drainPending) {
1009 DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
1011 // Breaks looping condition in tick()
1012 threadFetched = numFetchingThreads;
1016 DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
1019 Addr fetch_PC = PC[tid];
1020 Addr fetch_NPC = nextPC[tid];
1021 Addr fetch_MicroPC = microPC[tid];
1023 // Fault code for memory access.
1024 Fault fault = NoFault;
1026 // If returning from the delay of a cache miss, then update the status
1027 // to running, otherwise do the cache access. Possibly move this up
1028 // to tick() function.
1029 if (fetchStatus[tid] == IcacheAccessComplete) {
1030 DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n",
1033 fetchStatus[tid] = Running;
1034 status_change = true;
1035 } else if (fetchStatus[tid] == Running) {
1036 DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
1037 "instruction, starting at PC %08p.\n",
1040 bool fetch_success = fetchCacheLine(fetch_PC, fault, tid);
1041 if (!fetch_success) {
1043 ++icacheStallCycles;
1045 ++fetchMiscStallCycles;
1050 if (fetchStatus[tid] == Idle) {
1052 DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
1053 } else if (fetchStatus[tid] == Blocked) {
1054 ++fetchBlockedCycles;
1055 DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
1056 } else if (fetchStatus[tid] == Squashing) {
1057 ++fetchSquashCycles;
1058 DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
1059 } else if (fetchStatus[tid] == IcacheWaitResponse) {
1060 ++icacheStallCycles;
1061 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n", tid);
1064 // Status is Idle, Squashing, Blocked, or IcacheWaitResponse, so
1065 // fetch should do nothing.
1071 // If we had a stall due to an icache miss, then return.
1072 if (fetchStatus[tid] == IcacheWaitResponse) {
1073 ++icacheStallCycles;
1074 status_change = true;
1078 Addr next_PC = fetch_PC;
1079 Addr next_NPC = fetch_NPC;
1080 Addr next_MicroPC = fetch_MicroPC;
1082 InstSeqNum inst_seq;
1084 ExtMachInst ext_inst;
1085 // @todo: Fix this hack.
1086 unsigned offset = (fetch_PC & cacheBlkMask) & ~3;
1088 StaticInstPtr staticInst = NULL;
1089 StaticInstPtr macroop = NULL;
1091 if (fault == NoFault) {
1092 // If the read of the first instruction was successful, then grab the
1093 // instructions from the rest of the cache line and put them into the
1094 // queue heading to decode.
1096 DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
1099 // Need to keep track of whether or not a predicted branch
1100 // ended this fetch block.
1101 bool predicted_branch = false;
1103 while (offset < cacheBlkSize &&
1104 numInst < fetchWidth &&
1105 !predicted_branch) {
1107 // If we're branching after this instruction, quite fetching
1108 // from the same block then.
1110 (fetch_PC + sizeof(TheISA::MachInst) != fetch_NPC);
1111 if (predicted_branch) {
1112 DPRINTF(Fetch, "Branch detected with PC = %#x, NPC = %#x\n",
1113 fetch_PC, fetch_NPC);
1116 // Make sure this is a valid index.
1117 assert(offset <= cacheBlkSize - instSize);
1120 // Get the instruction from the array of the cache line.
1121 inst = TheISA::gtoh(*reinterpret_cast<TheISA::MachInst *>
1122 (&cacheData[tid][offset]));
1124 predecoder.setTC(cpu->thread[tid]->getTC());
1125 predecoder.moreBytes(fetch_PC, fetch_PC, inst);
1127 ext_inst = predecoder.getExtMachInst();
1128 staticInst = StaticInstPtr(ext_inst, fetch_PC);
1129 if (staticInst->isMacroop())
1130 macroop = staticInst;
1134 staticInst = macroop->fetchMicroop(fetch_MicroPC);
1135 if (staticInst->isLastMicroop())
1139 // Get a sequence number.
1140 inst_seq = cpu->getAndIncrementInstSeq();
1142 // Create a new DynInst from the instruction fetched.
1143 DynInstPtr instruction = new DynInst(staticInst,
1144 fetch_PC, fetch_NPC, fetch_MicroPC,
1145 next_PC, next_NPC, next_MicroPC,
1147 instruction->setTid(tid);
1149 instruction->setASID(tid);
1151 instruction->setThreadState(cpu->thread[tid]);
1153 DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x created "
1155 tid, instruction->readPC(), inst_seq);
1157 //DPRINTF(Fetch, "[tid:%i]: MachInst is %#x\n", tid, ext_inst);
1159 DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n",
1160 tid, instruction->staticInst->disassemble(fetch_PC));
1163 instruction->traceData =
1164 cpu->getTracer()->getInstRecord(curTick, cpu->tcBase(tid),
1165 instruction->staticInst, instruction->readPC(),
1166 macroop, instruction->readMicroPC());
1168 instruction->traceData = NULL;
1171 ///FIXME This needs to be more robust in dealing with delay slots
1173 lookupAndUpdateNextPC(instruction, next_PC, next_NPC, next_MicroPC);
1175 // Add instruction to the CPU's list of instructions.
1176 instruction->setInstListIt(cpu->addInst(instruction));
1178 // Write the instruction to the first slot in the queue
1179 // that heads to decode.
1180 toDecode->insts[numInst] = instruction;
1184 // Increment stat of fetched instructions.
1187 // Move to the next instruction, unless we have a branch.
1189 fetch_NPC = next_NPC;
1190 fetch_MicroPC = next_MicroPC;
1192 if (instruction->isQuiesce()) {
1193 DPRINTF(Fetch, "Quiesce instruction encountered, halting fetch!",
1195 fetchStatus[tid] = QuiescePending;
1197 status_change = true;
1202 } while (staticInst->isMicroop() &&
1203 !staticInst->isLastMicroop() &&
1204 numInst < fetchWidth);
1208 if (predicted_branch) {
1209 DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
1210 "instruction encountered.\n", tid);
1211 } else if (numInst >= fetchWidth) {
1212 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
1213 "for this cycle.\n", tid);
1214 } else if (offset >= cacheBlkSize) {
1215 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of cache "
1221 wroteToTimeBuffer = true;
1224 // Now that fetching is completed, update the PC to signify what the next
1226 if (fault == NoFault) {
1228 nextPC[tid] = next_NPC;
1229 microPC[tid] = next_MicroPC;
1230 DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n", tid, next_PC);
1232 // We shouldn't be in an icache miss and also have a fault (an ITB
1234 if (fetchStatus[tid] == IcacheWaitResponse) {
1235 panic("Fetch should have exited prior to this!");
1238 // Send the fault to commit. This thread will not do anything
1239 // until commit handles the fault. The only other way it can
1240 // wake up is if a squash comes along and changes the PC.
1241 assert(numInst < fetchWidth);
1242 // Get a sequence number.
1243 inst_seq = cpu->getAndIncrementInstSeq();
1244 // We will use a nop in order to carry the fault.
1245 ext_inst = TheISA::NoopMachInst;
1247 // Create a new DynInst from the dummy nop.
1248 DynInstPtr instruction = new DynInst(ext_inst,
1249 fetch_PC, fetch_NPC, fetch_MicroPC,
1250 next_PC, next_NPC, next_MicroPC,
1252 instruction->setPredTarg(next_NPC, next_NPC + instSize, 0);
1253 instruction->setTid(tid);
1255 instruction->setASID(tid);
1257 instruction->setThreadState(cpu->thread[tid]);
1259 instruction->traceData = NULL;
1261 instruction->setInstListIt(cpu->addInst(instruction));
1263 instruction->fault = fault;
1265 toDecode->insts[numInst] = instruction;
1268 wroteToTimeBuffer = true;
1270 DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n",tid);
1272 fetchStatus[tid] = TrapPending;
1273 status_change = true;
1275 DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %08p",
1276 tid, fault->name(), PC[tid]);
1280 template<class Impl>
1282 DefaultFetch<Impl>::recvRetry()
1284 if (retryPkt != NULL) {
1285 assert(cacheBlocked);
1286 assert(retryTid != InvalidThreadID);
1287 assert(fetchStatus[retryTid] == IcacheWaitRetry);
1289 if (icachePort->sendTiming(retryPkt)) {
1290 fetchStatus[retryTid] = IcacheWaitResponse;
1292 retryTid = InvalidThreadID;
1293 cacheBlocked = false;
1296 assert(retryTid == InvalidThreadID);
1297 // Access has been squashed since it was sent out. Just clear
1298 // the cache being blocked.
1299 cacheBlocked = false;
1303 ///////////////////////////////////////
1305 // SMT FETCH POLICY MAINTAINED HERE //
1307 ///////////////////////////////////////
1308 template<class Impl>
1310 DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1312 if (numThreads > 1) {
1313 switch (fetch_priority) {
1319 return roundRobin();
1328 return branchCount();
1331 return InvalidThreadID;
1334 list<ThreadID>::iterator thread = activeThreads->begin();
1335 if (thread == activeThreads->end()) {
1336 return InvalidThreadID;
1339 ThreadID tid = *thread;
1341 if (fetchStatus[tid] == Running ||
1342 fetchStatus[tid] == IcacheAccessComplete ||
1343 fetchStatus[tid] == Idle) {
1346 return InvalidThreadID;
1352 template<class Impl>
1354 DefaultFetch<Impl>::roundRobin()
1356 list<ThreadID>::iterator pri_iter = priorityList.begin();
1357 list<ThreadID>::iterator end = priorityList.end();
1361 while (pri_iter != end) {
1362 high_pri = *pri_iter;
1364 assert(high_pri <= numThreads);
1366 if (fetchStatus[high_pri] == Running ||
1367 fetchStatus[high_pri] == IcacheAccessComplete ||
1368 fetchStatus[high_pri] == Idle) {
1370 priorityList.erase(pri_iter);
1371 priorityList.push_back(high_pri);
1379 return InvalidThreadID;
1382 template<class Impl>
1384 DefaultFetch<Impl>::iqCount()
1386 std::priority_queue<ThreadID> PQ;
1388 list<ThreadID>::iterator threads = activeThreads->begin();
1389 list<ThreadID>::iterator end = activeThreads->end();
1391 while (threads != end) {
1392 ThreadID tid = *threads++;
1394 PQ.push(fromIEW->iewInfo[tid].iqCount);
1397 while (!PQ.empty()) {
1398 ThreadID high_pri = PQ.top();
1400 if (fetchStatus[high_pri] == Running ||
1401 fetchStatus[high_pri] == IcacheAccessComplete ||
1402 fetchStatus[high_pri] == Idle)
1409 return InvalidThreadID;
1412 template<class Impl>
1414 DefaultFetch<Impl>::lsqCount()
1416 std::priority_queue<ThreadID> PQ;
1418 list<ThreadID>::iterator threads = activeThreads->begin();
1419 list<ThreadID>::iterator end = activeThreads->end();
1421 while (threads != end) {
1422 ThreadID tid = *threads++;
1424 PQ.push(fromIEW->iewInfo[tid].ldstqCount);
1427 while (!PQ.empty()) {
1428 ThreadID high_pri = PQ.top();
1430 if (fetchStatus[high_pri] == Running ||
1431 fetchStatus[high_pri] == IcacheAccessComplete ||
1432 fetchStatus[high_pri] == Idle)
1438 return InvalidThreadID;
1441 template<class Impl>
1443 DefaultFetch<Impl>::branchCount()
1446 list<ThreadID>::iterator thread = activeThreads->begin();
1447 assert(thread != activeThreads->end());
1448 ThreadID tid = *thread;
1451 panic("Branch Count Fetch policy unimplemented\n");
1452 return InvalidThreadID;