2 * Copyright (c) 2010-2011 ARM Limited
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder. You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
14 * Copyright (c) 2004-2006 The Regents of The University of Michigan
15 * All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
50 #include "arch/isa_traits.hh"
51 #include "arch/tlb.hh"
52 #include "arch/utility.hh"
53 #include "arch/vtophys.hh"
54 #include "base/types.hh"
55 #include "config/the_isa.hh"
56 #include "cpu/base.hh"
57 //#include "cpu/checker/cpu.hh"
58 #include "cpu/o3/fetch.hh"
59 #include "cpu/exetrace.hh"
60 #include "debug/Activity.hh"
61 #include "debug/Fetch.hh"
62 #include "mem/packet.hh"
63 #include "params/DerivO3CPU.hh"
64 #include "sim/byteswap.hh"
65 #include "sim/core.hh"
66 #include "sim/eventq.hh"
67 #include "sim/full_system.hh"
68 #include "sim/system.hh"
73 DefaultFetch<Impl>::DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params)
77 decodeToFetchDelay(params->decodeToFetchDelay),
78 renameToFetchDelay(params->renameToFetchDelay),
79 iewToFetchDelay(params->iewToFetchDelay),
80 commitToFetchDelay(params->commitToFetchDelay),
81 fetchWidth(params->fetchWidth),
84 retryTid(InvalidThreadID),
85 numThreads(params->numThreads),
86 numFetchingThreads(params->smtNumFetchingThreads),
87 interruptPending(false),
90 finishTranslationEvent(this)
92 if (numThreads > Impl::MaxThreads)
93 fatal("numThreads (%d) is larger than compiled limit (%d),\n"
94 "\tincrease MaxThreads in src/cpu/o3/impl.hh\n",
95 numThreads, static_cast<int>(Impl::MaxThreads));
96 if (fetchWidth > Impl::MaxWidth)
97 fatal("fetchWidth (%d) is larger than compiled limit (%d),\n"
98 "\tincrease MaxWidth in src/cpu/o3/impl.hh\n",
99 fetchWidth, static_cast<int>(Impl::MaxWidth));
101 // Set fetch stage's status to inactive.
104 std::string policy = params->smtFetchPolicy;
106 // Convert string to lowercase
107 std::transform(policy.begin(), policy.end(), policy.begin(),
108 (int(*)(int)) tolower);
110 // Figure out fetch policy
111 if (policy == "singlethread") {
112 fetchPolicy = SingleThread;
114 panic("Invalid Fetch Policy for a SMT workload.");
115 } else if (policy == "roundrobin") {
116 fetchPolicy = RoundRobin;
117 DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
118 } else if (policy == "branch") {
119 fetchPolicy = Branch;
120 DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
121 } else if (policy == "iqcount") {
123 DPRINTF(Fetch, "Fetch policy set to IQ count\n");
124 } else if (policy == "lsqcount") {
126 DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
128 fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
129 " RoundRobin,LSQcount,IQcount}\n");
132 // Get the size of an instruction.
133 instSize = sizeof(TheISA::MachInst);
135 for (int i = 0; i < Impl::MaxThreads; i++) {
137 decoder[i] = new TheISA::Decoder(NULL);
141 template <class Impl>
143 DefaultFetch<Impl>::name() const
145 return cpu->name() + ".fetch";
148 template <class Impl>
150 DefaultFetch<Impl>::regStats()
153 .name(name() + ".icacheStallCycles")
154 .desc("Number of cycles fetch is stalled on an Icache miss")
155 .prereq(icacheStallCycles);
158 .name(name() + ".Insts")
159 .desc("Number of instructions fetch has processed")
160 .prereq(fetchedInsts);
163 .name(name() + ".Branches")
164 .desc("Number of branches that fetch encountered")
165 .prereq(fetchedBranches);
168 .name(name() + ".predictedBranches")
169 .desc("Number of branches that fetch has predicted taken")
170 .prereq(predictedBranches);
173 .name(name() + ".Cycles")
174 .desc("Number of cycles fetch has run and was not squashing or"
176 .prereq(fetchCycles);
179 .name(name() + ".SquashCycles")
180 .desc("Number of cycles fetch has spent squashing")
181 .prereq(fetchSquashCycles);
184 .name(name() + ".TlbCycles")
185 .desc("Number of cycles fetch has spent waiting for tlb")
186 .prereq(fetchTlbCycles);
189 .name(name() + ".IdleCycles")
190 .desc("Number of cycles fetch was idle")
191 .prereq(fetchIdleCycles);
194 .name(name() + ".BlockedCycles")
195 .desc("Number of cycles fetch has spent blocked")
196 .prereq(fetchBlockedCycles);
199 .name(name() + ".CacheLines")
200 .desc("Number of cache lines fetched")
201 .prereq(fetchedCacheLines);
204 .name(name() + ".MiscStallCycles")
205 .desc("Number of cycles fetch has spent waiting on interrupts, or "
206 "bad addresses, or out of MSHRs")
207 .prereq(fetchMiscStallCycles);
209 fetchPendingDrainCycles
210 .name(name() + ".PendingDrainCycles")
211 .desc("Number of cycles fetch has spent waiting on pipes to drain")
212 .prereq(fetchPendingDrainCycles);
214 fetchNoActiveThreadStallCycles
215 .name(name() + ".NoActiveThreadStallCycles")
216 .desc("Number of stall cycles due to no active thread to fetch from")
217 .prereq(fetchNoActiveThreadStallCycles);
219 fetchPendingTrapStallCycles
220 .name(name() + ".PendingTrapStallCycles")
221 .desc("Number of stall cycles due to pending traps")
222 .prereq(fetchPendingTrapStallCycles);
224 fetchPendingQuiesceStallCycles
225 .name(name() + ".PendingQuiesceStallCycles")
226 .desc("Number of stall cycles due to pending quiesce instructions")
227 .prereq(fetchPendingQuiesceStallCycles);
229 fetchIcacheWaitRetryStallCycles
230 .name(name() + ".IcacheWaitRetryStallCycles")
231 .desc("Number of stall cycles due to full MSHR")
232 .prereq(fetchIcacheWaitRetryStallCycles);
235 .name(name() + ".IcacheSquashes")
236 .desc("Number of outstanding Icache misses that were squashed")
237 .prereq(fetchIcacheSquashes);
240 .name(name() + ".ItlbSquashes")
241 .desc("Number of outstanding ITLB misses that were squashed")
242 .prereq(fetchTlbSquashes);
245 .init(/* base value */ 0,
246 /* last value */ fetchWidth,
248 .name(name() + ".rateDist")
249 .desc("Number of instructions fetched each cycle (Total)")
253 .name(name() + ".idleRate")
254 .desc("Percent of cycles fetch was idle")
256 idleRate = fetchIdleCycles * 100 / cpu->numCycles;
259 .name(name() + ".branchRate")
260 .desc("Number of branch fetches per cycle")
261 .flags(Stats::total);
262 branchRate = fetchedBranches / cpu->numCycles;
265 .name(name() + ".rate")
266 .desc("Number of inst fetches per cycle")
267 .flags(Stats::total);
268 fetchRate = fetchedInsts / cpu->numCycles;
270 branchPred.regStats();
275 DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
277 timeBuffer = time_buffer;
279 // Create wires to get information from proper places in time buffer.
280 fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
281 fromRename = timeBuffer->getWire(-renameToFetchDelay);
282 fromIEW = timeBuffer->getWire(-iewToFetchDelay);
283 fromCommit = timeBuffer->getWire(-commitToFetchDelay);
288 DefaultFetch<Impl>::setActiveThreads(std::list<ThreadID> *at_ptr)
290 activeThreads = at_ptr;
295 DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
299 // Create wire to write information to proper place in fetch queue.
300 toDecode = fetchQueue->getWire(0);
305 DefaultFetch<Impl>::initStage()
307 // Setup PC and nextPC with initial state.
308 for (ThreadID tid = 0; tid < numThreads; tid++) {
309 pc[tid] = cpu->pcState(tid);
310 fetchOffset[tid] = 0;
312 delayedCommit[tid] = false;
315 for (ThreadID tid = 0; tid < numThreads; tid++) {
317 fetchStatus[tid] = Running;
319 priorityList.push_back(tid);
323 stalls[tid].decode = false;
324 stalls[tid].rename = false;
325 stalls[tid].iew = false;
326 stalls[tid].commit = false;
329 // Schedule fetch to get the correct PC from the CPU
330 // scheduleFetchStartupEvent(1);
332 // Fetch needs to start fetching instructions at the very beginning,
333 // so it must start up in active state.
339 DefaultFetch<Impl>::setIcache()
341 assert(cpu->getInstPort().isConnected());
343 // Size of cache block.
344 cacheBlkSize = cpu->getInstPort().peerBlockSize();
346 // Create mask to get rid of offset bits.
347 cacheBlkMask = (cacheBlkSize - 1);
349 for (ThreadID tid = 0; tid < numThreads; tid++) {
350 // Create space to store a cache line.
352 cacheData[tid] = new uint8_t[cacheBlkSize];
353 cacheDataPC[tid] = 0;
354 cacheDataValid[tid] = false;
360 DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
362 ThreadID tid = pkt->req->threadId();
364 DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n", tid);
366 // Only change the status if it's still waiting on the icache access
368 if (fetchStatus[tid] != IcacheWaitResponse ||
369 pkt->req != memReq[tid] ||
371 ++fetchIcacheSquashes;
377 memcpy(cacheData[tid], pkt->getPtr<uint8_t>(), cacheBlkSize);
378 cacheDataValid[tid] = true;
381 // Wake up the CPU (if it went to sleep and was waiting on
382 // this completion event).
385 DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
391 // Only switch to IcacheAccessComplete if we're not stalled as well.
392 if (checkStall(tid)) {
393 fetchStatus[tid] = Blocked;
395 fetchStatus[tid] = IcacheAccessComplete;
398 // Reset the mem req to NULL.
404 template <class Impl>
406 DefaultFetch<Impl>::drain()
408 // Fetch is ready to drain at any time.
409 cpu->signalDrained();
414 template <class Impl>
416 DefaultFetch<Impl>::resume()
418 drainPending = false;
421 template <class Impl>
423 DefaultFetch<Impl>::switchOut()
426 // Branch predictor needs to have its state cleared.
427 branchPred.switchOut();
430 template <class Impl>
432 DefaultFetch<Impl>::takeOverFrom()
434 // the instruction port is now connected so we can get the block
439 for (ThreadID i = 0; i < Impl::MaxThreads; ++i) {
440 stalls[i].decode = 0;
441 stalls[i].rename = 0;
443 stalls[i].commit = 0;
444 pc[i] = cpu->pcState(i);
445 fetchStatus[i] = Running;
448 wroteToTimeBuffer = false;
451 interruptPending = false;
452 branchPred.takeOverFrom();
455 template <class Impl>
457 DefaultFetch<Impl>::wakeFromQuiesce()
459 DPRINTF(Fetch, "Waking up from quiesce\n");
460 // Hopefully this is safe
461 // @todo: Allow other threads to wake from quiesce.
462 fetchStatus[0] = Running;
465 template <class Impl>
467 DefaultFetch<Impl>::switchToActive()
469 if (_status == Inactive) {
470 DPRINTF(Activity, "Activating stage.\n");
472 cpu->activateStage(O3CPU::FetchIdx);
478 template <class Impl>
480 DefaultFetch<Impl>::switchToInactive()
482 if (_status == Active) {
483 DPRINTF(Activity, "Deactivating stage.\n");
485 cpu->deactivateStage(O3CPU::FetchIdx);
491 template <class Impl>
493 DefaultFetch<Impl>::lookupAndUpdateNextPC(
494 DynInstPtr &inst, TheISA::PCState &nextPC)
496 // Do branch prediction check here.
497 // A bit of a misnomer...next_PC is actually the current PC until
498 // this function updates it.
501 if (!inst->isControl()) {
502 TheISA::advancePC(nextPC, inst->staticInst);
503 inst->setPredTarg(nextPC);
504 inst->setPredTaken(false);
508 ThreadID tid = inst->threadNumber;
509 predict_taken = branchPred.predict(inst, nextPC, tid);
512 DPRINTF(Fetch, "[tid:%i]: [sn:%i]: Branch predicted to be taken to %s.\n",
513 tid, inst->seqNum, nextPC);
515 DPRINTF(Fetch, "[tid:%i]: [sn:%i]:Branch predicted to be not taken.\n",
519 DPRINTF(Fetch, "[tid:%i]: [sn:%i] Branch predicted to go to %s.\n",
520 tid, inst->seqNum, nextPC);
521 inst->setPredTarg(nextPC);
522 inst->setPredTaken(predict_taken);
530 return predict_taken;
533 template <class Impl>
535 DefaultFetch<Impl>::fetchCacheLine(Addr vaddr, ThreadID tid, Addr pc)
537 Fault fault = NoFault;
539 // @todo: not sure if these should block translation.
542 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
545 } else if (isSwitchedOut()) {
546 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, switched out\n",
549 } else if (checkInterrupt(pc) && !delayedCommit[tid]) {
550 // Hold off fetch from getting new instructions when:
551 // Cache is blocked, or
552 // while an interrupt is pending and we're not in PAL mode, or
553 // fetch is switched out.
554 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n",
559 // Align the fetch address so it's at the start of a cache block.
560 Addr block_PC = icacheBlockAlignPC(vaddr);
562 DPRINTF(Fetch, "[tid:%i] Fetching cache line %#x for addr %#x\n",
563 tid, block_PC, vaddr);
565 // Setup the memReq to do a read of the first instruction's address.
566 // Set the appropriate read size and flags as well.
567 // Build request here.
569 new Request(tid, block_PC, cacheBlkSize, Request::INST_FETCH,
570 cpu->instMasterId(), pc, cpu->thread[tid]->contextId(), tid);
572 memReq[tid] = mem_req;
574 // Initiate translation of the icache block
575 fetchStatus[tid] = ItlbWait;
576 FetchTranslation *trans = new FetchTranslation(this);
577 cpu->itb->translateTiming(mem_req, cpu->thread[tid]->getTC(),
578 trans, BaseTLB::Execute);
582 template <class Impl>
584 DefaultFetch<Impl>::finishTranslation(Fault fault, RequestPtr mem_req)
586 ThreadID tid = mem_req->threadId();
587 Addr block_PC = mem_req->getVaddr();
589 // Wake up CPU if it was idle
592 if (fetchStatus[tid] != ItlbWait || mem_req != memReq[tid] ||
593 mem_req->getVaddr() != memReq[tid]->getVaddr() || isSwitchedOut()) {
594 DPRINTF(Fetch, "[tid:%i] Ignoring itlb completed after squash\n",
602 // If translation was successful, attempt to read the icache block.
603 if (fault == NoFault) {
604 // Check that we're not going off into random memory
605 // If we have, just wait around for commit to squash something and put
606 // us on the right track
607 if (!cpu->system->isMemAddr(mem_req->getPaddr())) {
608 warn("Address %#x is outside of physical memory, stopping fetch\n",
609 mem_req->getPaddr());
610 fetchStatus[tid] = NoGoodAddr;
616 // Build packet here.
617 PacketPtr data_pkt = new Packet(mem_req, MemCmd::ReadReq);
618 data_pkt->dataDynamicArray(new uint8_t[cacheBlkSize]);
620 cacheDataPC[tid] = block_PC;
621 cacheDataValid[tid] = false;
622 DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
627 if (!cpu->getInstPort().sendTimingReq(data_pkt)) {
628 assert(retryPkt == NULL);
629 assert(retryTid == InvalidThreadID);
630 DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
632 fetchStatus[tid] = IcacheWaitRetry;
637 DPRINTF(Fetch, "[tid:%i]: Doing Icache access.\n", tid);
638 DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
641 lastIcacheStall[tid] = curTick();
642 fetchStatus[tid] = IcacheWaitResponse;
645 if (!(numInst < fetchWidth)) {
646 assert(!finishTranslationEvent.scheduled());
647 finishTranslationEvent.setFault(fault);
648 finishTranslationEvent.setReq(mem_req);
649 cpu->schedule(finishTranslationEvent, cpu->nextCycle(curTick() + cpu->ticks(1)));
652 DPRINTF(Fetch, "[tid:%i] Got back req with addr %#x but expected %#x\n",
653 tid, mem_req->getVaddr(), memReq[tid]->getVaddr());
654 // Translation faulted, icache request won't be sent.
658 // Send the fault to commit. This thread will not do anything
659 // until commit handles the fault. The only other way it can
660 // wake up is if a squash comes along and changes the PC.
661 TheISA::PCState fetchPC = pc[tid];
663 DPRINTF(Fetch, "[tid:%i]: Translation faulted, building noop.\n", tid);
664 // We will use a nop in ordier to carry the fault.
665 DynInstPtr instruction = buildInst(tid,
666 decoder[tid]->decode(TheISA::NoopMachInst, fetchPC.instAddr()),
667 NULL, fetchPC, fetchPC, false);
669 instruction->setPredTarg(fetchPC);
670 instruction->fault = fault;
671 wroteToTimeBuffer = true;
673 DPRINTF(Activity, "Activity this cycle.\n");
674 cpu->activityThisCycle();
676 fetchStatus[tid] = TrapPending;
678 DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n", tid);
679 DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %s.\n",
680 tid, fault->name(), pc[tid]);
682 _status = updateFetchStatus();
685 template <class Impl>
687 DefaultFetch<Impl>::doSquash(const TheISA::PCState &newPC,
688 const DynInstPtr squashInst, ThreadID tid)
690 DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %s.\n",
694 fetchOffset[tid] = 0;
695 if (squashInst && squashInst->pcState().instAddr() == newPC.instAddr())
696 macroop[tid] = squashInst->macroop;
699 decoder[tid]->reset();
701 // Clear the icache miss if it's outstanding.
702 if (fetchStatus[tid] == IcacheWaitResponse) {
703 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
706 } else if (fetchStatus[tid] == ItlbWait) {
707 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding ITLB miss.\n",
712 // Get rid of the retrying packet if it was from this thread.
713 if (retryTid == tid) {
714 assert(cacheBlocked);
716 delete retryPkt->req;
720 retryTid = InvalidThreadID;
723 fetchStatus[tid] = Squashing;
725 // microops are being squashed, it is not known wheather the
726 // youngest non-squashed microop was marked delayed commit
727 // or not. Setting the flag to true ensures that the
728 // interrupts are not handled when they cannot be, though
729 // some opportunities to handle interrupts may be missed.
730 delayedCommit[tid] = true;
737 DefaultFetch<Impl>::squashFromDecode(const TheISA::PCState &newPC,
738 const DynInstPtr squashInst,
739 const InstSeqNum seq_num, ThreadID tid)
741 DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n", tid);
743 doSquash(newPC, squashInst, tid);
745 // Tell the CPU to remove any instructions that are in flight between
747 cpu->removeInstsUntil(seq_num, tid);
752 DefaultFetch<Impl>::checkStall(ThreadID tid) const
754 bool ret_val = false;
756 if (cpu->contextSwitch) {
757 DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
759 } else if (stalls[tid].decode) {
760 DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
762 } else if (stalls[tid].rename) {
763 DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
765 } else if (stalls[tid].iew) {
766 DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
768 } else if (stalls[tid].commit) {
769 DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
777 typename DefaultFetch<Impl>::FetchStatus
778 DefaultFetch<Impl>::updateFetchStatus()
781 list<ThreadID>::iterator threads = activeThreads->begin();
782 list<ThreadID>::iterator end = activeThreads->end();
784 while (threads != end) {
785 ThreadID tid = *threads++;
787 if (fetchStatus[tid] == Running ||
788 fetchStatus[tid] == Squashing ||
789 fetchStatus[tid] == IcacheAccessComplete) {
791 if (_status == Inactive) {
792 DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
794 if (fetchStatus[tid] == IcacheAccessComplete) {
795 DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
799 cpu->activateStage(O3CPU::FetchIdx);
806 // Stage is switching from active to inactive, notify CPU of it.
807 if (_status == Active) {
808 DPRINTF(Activity, "Deactivating stage.\n");
810 cpu->deactivateStage(O3CPU::FetchIdx);
816 template <class Impl>
818 DefaultFetch<Impl>::squash(const TheISA::PCState &newPC,
819 const InstSeqNum seq_num, DynInstPtr squashInst,
822 DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n", tid);
824 doSquash(newPC, squashInst, tid);
826 // Tell the CPU to remove any instructions that are not in the ROB.
827 cpu->removeInstsNotInROB(tid);
830 template <class Impl>
832 DefaultFetch<Impl>::tick()
834 list<ThreadID>::iterator threads = activeThreads->begin();
835 list<ThreadID>::iterator end = activeThreads->end();
836 bool status_change = false;
838 wroteToTimeBuffer = false;
840 for (ThreadID i = 0; i < Impl::MaxThreads; ++i) {
841 issuePipelinedIfetch[i] = false;
844 while (threads != end) {
845 ThreadID tid = *threads++;
847 // Check the signals for each thread to determine the proper status
849 bool updated_status = checkSignalsAndUpdate(tid);
850 status_change = status_change || updated_status;
853 DPRINTF(Fetch, "Running stage.\n");
856 if (fromCommit->commitInfo[0].interruptPending) {
857 interruptPending = true;
860 if (fromCommit->commitInfo[0].clearInterrupt) {
861 interruptPending = false;
865 for (threadFetched = 0; threadFetched < numFetchingThreads;
867 // Fetch each of the actively fetching threads.
868 fetch(status_change);
871 // Record number of instructions fetched this cycle for distribution.
872 fetchNisnDist.sample(numInst);
875 // Change the fetch stage status if there was a status change.
876 _status = updateFetchStatus();
879 // If there was activity this cycle, inform the CPU of it.
880 if (wroteToTimeBuffer || cpu->contextSwitch) {
881 DPRINTF(Activity, "Activity this cycle.\n");
883 cpu->activityThisCycle();
886 // Issue the next I-cache request if possible.
887 for (ThreadID i = 0; i < Impl::MaxThreads; ++i) {
888 if (issuePipelinedIfetch[i]) {
889 pipelineIcacheAccesses(i);
893 // Reset the number of the instruction we've fetched.
897 template <class Impl>
899 DefaultFetch<Impl>::checkSignalsAndUpdate(ThreadID tid)
901 // Update the per thread stall statuses.
902 if (fromDecode->decodeBlock[tid]) {
903 stalls[tid].decode = true;
906 if (fromDecode->decodeUnblock[tid]) {
907 assert(stalls[tid].decode);
908 assert(!fromDecode->decodeBlock[tid]);
909 stalls[tid].decode = false;
912 if (fromRename->renameBlock[tid]) {
913 stalls[tid].rename = true;
916 if (fromRename->renameUnblock[tid]) {
917 assert(stalls[tid].rename);
918 assert(!fromRename->renameBlock[tid]);
919 stalls[tid].rename = false;
922 if (fromIEW->iewBlock[tid]) {
923 stalls[tid].iew = true;
926 if (fromIEW->iewUnblock[tid]) {
927 assert(stalls[tid].iew);
928 assert(!fromIEW->iewBlock[tid]);
929 stalls[tid].iew = false;
932 if (fromCommit->commitBlock[tid]) {
933 stalls[tid].commit = true;
936 if (fromCommit->commitUnblock[tid]) {
937 assert(stalls[tid].commit);
938 assert(!fromCommit->commitBlock[tid]);
939 stalls[tid].commit = false;
942 // Check squash signals from commit.
943 if (fromCommit->commitInfo[tid].squash) {
945 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
946 "from commit.\n",tid);
947 // In any case, squash.
948 squash(fromCommit->commitInfo[tid].pc,
949 fromCommit->commitInfo[tid].doneSeqNum,
950 fromCommit->commitInfo[tid].squashInst, tid);
952 // If it was a branch mispredict on a control instruction, update the
953 // branch predictor with that instruction, otherwise just kill the
954 // invalid state we generated in after sequence number
955 if (fromCommit->commitInfo[tid].mispredictInst &&
956 fromCommit->commitInfo[tid].mispredictInst->isControl()) {
957 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
958 fromCommit->commitInfo[tid].pc,
959 fromCommit->commitInfo[tid].branchTaken,
962 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
967 } else if (fromCommit->commitInfo[tid].doneSeqNum) {
968 // Update the branch predictor if it wasn't a squashed instruction
969 // that was broadcasted.
970 branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
973 // Check ROB squash signals from commit.
974 if (fromCommit->commitInfo[tid].robSquashing) {
975 DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
977 // Continue to squash.
978 fetchStatus[tid] = Squashing;
983 // Check squash signals from decode.
984 if (fromDecode->decodeInfo[tid].squash) {
985 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
986 "from decode.\n",tid);
988 // Update the branch predictor.
989 if (fromDecode->decodeInfo[tid].branchMispredict) {
990 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
991 fromDecode->decodeInfo[tid].nextPC,
992 fromDecode->decodeInfo[tid].branchTaken,
995 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
999 if (fetchStatus[tid] != Squashing) {
1001 DPRINTF(Fetch, "Squashing from decode with PC = %s\n",
1002 fromDecode->decodeInfo[tid].nextPC);
1003 // Squash unless we're already squashing
1004 squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
1005 fromDecode->decodeInfo[tid].squashInst,
1006 fromDecode->decodeInfo[tid].doneSeqNum,
1013 if (checkStall(tid) &&
1014 fetchStatus[tid] != IcacheWaitResponse &&
1015 fetchStatus[tid] != IcacheWaitRetry) {
1016 DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
1018 fetchStatus[tid] = Blocked;
1023 if (fetchStatus[tid] == Blocked ||
1024 fetchStatus[tid] == Squashing) {
1025 // Switch status to running if fetch isn't being told to block or
1026 // squash this cycle.
1027 DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
1030 fetchStatus[tid] = Running;
1035 // If we've reached this point, we have not gotten any signals that
1036 // cause fetch to change its status. Fetch remains the same as before.
1040 template<class Impl>
1041 typename Impl::DynInstPtr
1042 DefaultFetch<Impl>::buildInst(ThreadID tid, StaticInstPtr staticInst,
1043 StaticInstPtr curMacroop, TheISA::PCState thisPC,
1044 TheISA::PCState nextPC, bool trace)
1046 // Get a sequence number.
1047 InstSeqNum seq = cpu->getAndIncrementInstSeq();
1049 // Create a new DynInst from the instruction fetched.
1050 DynInstPtr instruction =
1051 new DynInst(staticInst, curMacroop, thisPC, nextPC, seq, cpu);
1052 instruction->setTid(tid);
1054 instruction->setASID(tid);
1056 instruction->setThreadState(cpu->thread[tid]);
1058 DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x (%d) created "
1059 "[sn:%lli].\n", tid, thisPC.instAddr(),
1060 thisPC.microPC(), seq);
1062 DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n", tid,
1063 instruction->staticInst->
1064 disassemble(thisPC.instAddr()));
1068 instruction->traceData =
1069 cpu->getTracer()->getInstRecord(curTick(), cpu->tcBase(tid),
1070 instruction->staticInst, thisPC, curMacroop);
1073 instruction->traceData = NULL;
1076 // Add instruction to the CPU's list of instructions.
1077 instruction->setInstListIt(cpu->addInst(instruction));
1079 // Write the instruction to the first slot in the queue
1080 // that heads to decode.
1081 assert(numInst < fetchWidth);
1082 toDecode->insts[toDecode->size++] = instruction;
1084 // Keep track of if we can take an interrupt at this boundary
1085 delayedCommit[tid] = instruction->isDelayedCommit();
1090 template<class Impl>
1092 DefaultFetch<Impl>::fetch(bool &status_change)
1094 //////////////////////////////////////////
1095 // Start actual fetch
1096 //////////////////////////////////////////
1097 ThreadID tid = getFetchingThread(fetchPolicy);
1099 if (tid == InvalidThreadID || drainPending) {
1100 // Breaks looping condition in tick()
1101 threadFetched = numFetchingThreads;
1103 if (numThreads == 1) { // @todo Per-thread stats
1110 DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
1113 TheISA::PCState thisPC = pc[tid];
1115 Addr pcOffset = fetchOffset[tid];
1116 Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1118 bool inRom = isRomMicroPC(thisPC.microPC());
1120 // If returning from the delay of a cache miss, then update the status
1121 // to running, otherwise do the cache access. Possibly move this up
1122 // to tick() function.
1123 if (fetchStatus[tid] == IcacheAccessComplete) {
1124 DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n", tid);
1126 fetchStatus[tid] = Running;
1127 status_change = true;
1128 } else if (fetchStatus[tid] == Running) {
1129 // Align the fetch PC so its at the start of a cache block.
1130 Addr block_PC = icacheBlockAlignPC(fetchAddr);
1132 // If buffer is no longer valid or fetchAddr has moved to point
1133 // to the next cache block, AND we have no remaining ucode
1134 // from a macro-op, then start fetch from icache.
1135 if (!(cacheDataValid[tid] && block_PC == cacheDataPC[tid])
1136 && !inRom && !macroop[tid]) {
1137 DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
1138 "instruction, starting at PC %s.\n", tid, thisPC);
1140 fetchCacheLine(fetchAddr, tid, thisPC.instAddr());
1142 if (fetchStatus[tid] == IcacheWaitResponse)
1143 ++icacheStallCycles;
1144 else if (fetchStatus[tid] == ItlbWait)
1147 ++fetchMiscStallCycles;
1149 } else if ((checkInterrupt(thisPC.instAddr()) && !delayedCommit[tid])
1150 || isSwitchedOut()) {
1151 // Stall CPU if an interrupt is posted and we're not issuing
1152 // an delayed commit micro-op currently (delayed commit instructions
1153 // are not interruptable by interrupts, only faults)
1154 ++fetchMiscStallCycles;
1155 DPRINTF(Fetch, "[tid:%i]: Fetch is stalled!\n", tid);
1159 if (fetchStatus[tid] == Idle) {
1161 DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
1164 // Status is Idle, so fetch should do nothing.
1170 TheISA::PCState nextPC = thisPC;
1172 StaticInstPtr staticInst = NULL;
1173 StaticInstPtr curMacroop = macroop[tid];
1175 // If the read of the first instruction was successful, then grab the
1176 // instructions from the rest of the cache line and put them into the
1177 // queue heading to decode.
1179 DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
1182 // Need to keep track of whether or not a predicted branch
1183 // ended this fetch block.
1184 bool predictedBranch = false;
1186 TheISA::MachInst *cacheInsts =
1187 reinterpret_cast<TheISA::MachInst *>(cacheData[tid]);
1189 const unsigned numInsts = cacheBlkSize / instSize;
1190 unsigned blkOffset = (fetchAddr - cacheDataPC[tid]) / instSize;
1192 // Loop through instruction memory from the cache.
1193 // Keep issuing while fetchWidth is available and branch is not
1195 while (numInst < fetchWidth && !predictedBranch) {
1197 // We need to process more memory if we aren't going to get a
1198 // StaticInst from the rom, the current macroop, or what's already
1200 bool needMem = !inRom && !curMacroop &&
1201 !decoder[tid]->instReady();
1202 fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1203 Addr block_PC = icacheBlockAlignPC(fetchAddr);
1206 // If buffer is no longer valid or fetchAddr has moved to point
1207 // to the next cache block then start fetch from icache.
1208 if (!cacheDataValid[tid] || block_PC != cacheDataPC[tid])
1211 if (blkOffset >= numInsts) {
1212 // We need to process more memory, but we've run out of the
1217 if (ISA_HAS_DELAY_SLOT && pcOffset == 0) {
1218 // Walk past any annulled delay slot instructions.
1219 Addr pcAddr = thisPC.instAddr() & BaseCPU::PCMask;
1220 while (fetchAddr != pcAddr && blkOffset < numInsts) {
1222 fetchAddr += instSize;
1224 if (blkOffset >= numInsts)
1227 MachInst inst = TheISA::gtoh(cacheInsts[blkOffset]);
1229 decoder[tid]->setTC(cpu->thread[tid]->getTC());
1230 decoder[tid]->moreBytes(thisPC, fetchAddr, inst);
1232 if (decoder[tid]->needMoreBytes()) {
1234 fetchAddr += instSize;
1235 pcOffset += instSize;
1239 // Extract as many instructions and/or microops as we can from
1240 // the memory we've processed so far.
1242 if (!(curMacroop || inRom)) {
1243 if (decoder[tid]->instReady()) {
1244 staticInst = decoder[tid]->decode(thisPC);
1246 // Increment stat of fetched instructions.
1249 if (staticInst->isMacroop()) {
1250 curMacroop = staticInst;
1255 // We need more bytes for this instruction so blkOffset and
1256 // pcOffset will be updated
1260 // Whether we're moving to a new macroop because we're at the
1261 // end of the current one, or the branch predictor incorrectly
1263 bool newMacro = false;
1264 if (curMacroop || inRom) {
1266 staticInst = cpu->microcodeRom.fetchMicroop(
1267 thisPC.microPC(), curMacroop);
1269 staticInst = curMacroop->fetchMicroop(thisPC.microPC());
1271 newMacro |= staticInst->isLastMicroop();
1274 DynInstPtr instruction =
1275 buildInst(tid, staticInst, curMacroop,
1276 thisPC, nextPC, true);
1281 instruction->fetchTick = curTick();
1286 // If we're branching after this instruction, quite fetching
1287 // from the same block then.
1288 predictedBranch |= thisPC.branching();
1290 lookupAndUpdateNextPC(instruction, nextPC);
1291 if (predictedBranch) {
1292 DPRINTF(Fetch, "Branch detected with PC = %s\n", thisPC);
1295 newMacro |= thisPC.instAddr() != nextPC.instAddr();
1297 // Move to the next instruction, unless we have a branch.
1299 inRom = isRomMicroPC(thisPC.microPC());
1302 fetchAddr = thisPC.instAddr() & BaseCPU::PCMask;
1303 blkOffset = (fetchAddr - cacheDataPC[tid]) / instSize;
1308 if (instruction->isQuiesce()) {
1310 "Quiesce instruction encountered, halting fetch!");
1311 fetchStatus[tid] = QuiescePending;
1312 status_change = true;
1315 } while ((curMacroop || decoder[tid]->instReady()) &&
1316 numInst < fetchWidth);
1319 if (predictedBranch) {
1320 DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
1321 "instruction encountered.\n", tid);
1322 } else if (numInst >= fetchWidth) {
1323 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
1324 "for this cycle.\n", tid);
1325 } else if (blkOffset >= cacheBlkSize) {
1326 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of cache "
1330 macroop[tid] = curMacroop;
1331 fetchOffset[tid] = pcOffset;
1334 wroteToTimeBuffer = true;
1339 // pipeline a fetch if we're crossing a cache boundary and not in
1340 // a state that would preclude fetching
1341 fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1342 Addr block_PC = icacheBlockAlignPC(fetchAddr);
1343 issuePipelinedIfetch[tid] = block_PC != cacheDataPC[tid] &&
1344 fetchStatus[tid] != IcacheWaitResponse &&
1345 fetchStatus[tid] != ItlbWait &&
1346 fetchStatus[tid] != IcacheWaitRetry &&
1347 fetchStatus[tid] != QuiescePending &&
1351 template<class Impl>
1353 DefaultFetch<Impl>::recvRetry()
1355 if (retryPkt != NULL) {
1356 assert(cacheBlocked);
1357 assert(retryTid != InvalidThreadID);
1358 assert(fetchStatus[retryTid] == IcacheWaitRetry);
1360 if (cpu->getInstPort().sendTimingReq(retryPkt)) {
1361 fetchStatus[retryTid] = IcacheWaitResponse;
1363 retryTid = InvalidThreadID;
1364 cacheBlocked = false;
1367 assert(retryTid == InvalidThreadID);
1368 // Access has been squashed since it was sent out. Just clear
1369 // the cache being blocked.
1370 cacheBlocked = false;
1374 ///////////////////////////////////////
1376 // SMT FETCH POLICY MAINTAINED HERE //
1378 ///////////////////////////////////////
1379 template<class Impl>
1381 DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1383 if (numThreads > 1) {
1384 switch (fetch_priority) {
1390 return roundRobin();
1399 return branchCount();
1402 return InvalidThreadID;
1405 list<ThreadID>::iterator thread = activeThreads->begin();
1406 if (thread == activeThreads->end()) {
1407 return InvalidThreadID;
1410 ThreadID tid = *thread;
1412 if (fetchStatus[tid] == Running ||
1413 fetchStatus[tid] == IcacheAccessComplete ||
1414 fetchStatus[tid] == Idle) {
1417 return InvalidThreadID;
1423 template<class Impl>
1425 DefaultFetch<Impl>::roundRobin()
1427 list<ThreadID>::iterator pri_iter = priorityList.begin();
1428 list<ThreadID>::iterator end = priorityList.end();
1432 while (pri_iter != end) {
1433 high_pri = *pri_iter;
1435 assert(high_pri <= numThreads);
1437 if (fetchStatus[high_pri] == Running ||
1438 fetchStatus[high_pri] == IcacheAccessComplete ||
1439 fetchStatus[high_pri] == Idle) {
1441 priorityList.erase(pri_iter);
1442 priorityList.push_back(high_pri);
1450 return InvalidThreadID;
1453 template<class Impl>
1455 DefaultFetch<Impl>::iqCount()
1457 std::priority_queue<unsigned> PQ;
1458 std::map<unsigned, ThreadID> threadMap;
1460 list<ThreadID>::iterator threads = activeThreads->begin();
1461 list<ThreadID>::iterator end = activeThreads->end();
1463 while (threads != end) {
1464 ThreadID tid = *threads++;
1465 unsigned iqCount = fromIEW->iewInfo[tid].iqCount;
1468 threadMap[iqCount] = tid;
1471 while (!PQ.empty()) {
1472 ThreadID high_pri = threadMap[PQ.top()];
1474 if (fetchStatus[high_pri] == Running ||
1475 fetchStatus[high_pri] == IcacheAccessComplete ||
1476 fetchStatus[high_pri] == Idle)
1483 return InvalidThreadID;
1486 template<class Impl>
1488 DefaultFetch<Impl>::lsqCount()
1490 std::priority_queue<unsigned> PQ;
1491 std::map<unsigned, ThreadID> threadMap;
1493 list<ThreadID>::iterator threads = activeThreads->begin();
1494 list<ThreadID>::iterator end = activeThreads->end();
1496 while (threads != end) {
1497 ThreadID tid = *threads++;
1498 unsigned ldstqCount = fromIEW->iewInfo[tid].ldstqCount;
1500 PQ.push(ldstqCount);
1501 threadMap[ldstqCount] = tid;
1504 while (!PQ.empty()) {
1505 ThreadID high_pri = threadMap[PQ.top()];
1507 if (fetchStatus[high_pri] == Running ||
1508 fetchStatus[high_pri] == IcacheAccessComplete ||
1509 fetchStatus[high_pri] == Idle)
1515 return InvalidThreadID;
1518 template<class Impl>
1520 DefaultFetch<Impl>::branchCount()
1523 list<ThreadID>::iterator thread = activeThreads->begin();
1524 assert(thread != activeThreads->end());
1525 ThreadID tid = *thread;
1528 panic("Branch Count Fetch policy unimplemented\n");
1529 return InvalidThreadID;
1532 template<class Impl>
1534 DefaultFetch<Impl>::pipelineIcacheAccesses(ThreadID tid)
1536 if (!issuePipelinedIfetch[tid]) {
1540 // The next PC to access.
1541 TheISA::PCState thisPC = pc[tid];
1543 if (isRomMicroPC(thisPC.microPC())) {
1547 Addr pcOffset = fetchOffset[tid];
1548 Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1550 // Align the fetch PC so its at the start of a cache block.
1551 Addr block_PC = icacheBlockAlignPC(fetchAddr);
1553 // Unless buffer already got the block, fetch it from icache.
1554 if (!(cacheDataValid[tid] && block_PC == cacheDataPC[tid])) {
1555 DPRINTF(Fetch, "[tid:%i]: Issuing a pipelined I-cache access, "
1556 "starting at PC %s.\n", tid, thisPC);
1558 fetchCacheLine(fetchAddr, tid, thisPC.instAddr());
1562 template<class Impl>
1564 DefaultFetch<Impl>::profileStall(ThreadID tid) {
1565 DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
1567 // @todo Per-thread stats
1570 ++fetchPendingDrainCycles;
1571 DPRINTF(Fetch, "Fetch is waiting for a drain!\n");
1572 } else if (activeThreads->empty()) {
1573 ++fetchNoActiveThreadStallCycles;
1574 DPRINTF(Fetch, "Fetch has no active thread!\n");
1575 } else if (fetchStatus[tid] == Blocked) {
1576 ++fetchBlockedCycles;
1577 DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
1578 } else if (fetchStatus[tid] == Squashing) {
1579 ++fetchSquashCycles;
1580 DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
1581 } else if (fetchStatus[tid] == IcacheWaitResponse) {
1582 ++icacheStallCycles;
1583 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n",
1585 } else if (fetchStatus[tid] == ItlbWait) {
1587 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting ITLB walk to "
1589 } else if (fetchStatus[tid] == TrapPending) {
1590 ++fetchPendingTrapStallCycles;
1591 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending trap!\n",
1593 } else if (fetchStatus[tid] == QuiescePending) {
1594 ++fetchPendingQuiesceStallCycles;
1595 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending quiesce "
1596 "instruction!\n", tid);
1597 } else if (fetchStatus[tid] == IcacheWaitRetry) {
1598 ++fetchIcacheWaitRetryStallCycles;
1599 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for an I-cache retry!\n",
1601 } else if (fetchStatus[tid] == NoGoodAddr) {
1602 DPRINTF(Fetch, "[tid:%i]: Fetch predicted non-executable address\n",
1605 DPRINTF(Fetch, "[tid:%i]: Unexpected fetch stall reason (Status: %i).\n",
1606 tid, fetchStatus[tid]);