2 * Copyright (c) 2010 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.
47 #include "arch/isa_traits.hh"
48 #include "arch/utility.hh"
49 #include "base/types.hh"
50 #include "config/the_isa.hh"
51 #include "config/use_checker.hh"
52 #include "cpu/checker/cpu.hh"
53 #include "cpu/exetrace.hh"
54 #include "cpu/o3/fetch.hh"
55 #include "mem/packet.hh"
56 #include "mem/request.hh"
57 #include "params/DerivO3CPU.hh"
58 #include "sim/byteswap.hh"
59 #include "sim/core.hh"
62 #include "arch/tlb.hh"
63 #include "arch/vtophys.hh"
64 #include "sim/system.hh"
71 DefaultFetch<Impl>::IcachePort::setPeer(Port *port)
80 DefaultFetch<Impl>::IcachePort::recvAtomic(PacketPtr pkt)
82 panic("DefaultFetch doesn't expect recvAtomic callback!");
88 DefaultFetch<Impl>::IcachePort::recvFunctional(PacketPtr pkt)
90 DPRINTF(Fetch, "DefaultFetch doesn't update its state from a "
96 DefaultFetch<Impl>::IcachePort::recvStatusChange(Status status)
98 if (status == RangeChange) {
99 if (!snoopRangeSent) {
100 snoopRangeSent = true;
101 sendStatusChange(Port::RangeChange);
106 panic("DefaultFetch doesn't expect recvStatusChange callback!");
111 DefaultFetch<Impl>::IcachePort::recvTiming(PacketPtr pkt)
113 DPRINTF(Fetch, "Received timing\n");
114 if (pkt->isResponse()) {
115 fetch->processCacheCompletion(pkt);
117 //else Snooped a coherence request, just return
123 DefaultFetch<Impl>::IcachePort::recvRetry()
129 DefaultFetch<Impl>::DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params)
133 decodeToFetchDelay(params->decodeToFetchDelay),
134 renameToFetchDelay(params->renameToFetchDelay),
135 iewToFetchDelay(params->iewToFetchDelay),
136 commitToFetchDelay(params->commitToFetchDelay),
137 fetchWidth(params->fetchWidth),
140 retryTid(InvalidThreadID),
141 numThreads(params->numThreads),
142 numFetchingThreads(params->smtNumFetchingThreads),
143 interruptPending(false),
147 if (numThreads > Impl::MaxThreads)
148 fatal("numThreads (%d) is larger than compiled limit (%d),\n"
149 "\tincrease MaxThreads in src/cpu/o3/impl.hh\n",
150 numThreads, static_cast<int>(Impl::MaxThreads));
152 // Set fetch stage's status to inactive.
155 std::string policy = params->smtFetchPolicy;
157 // Convert string to lowercase
158 std::transform(policy.begin(), policy.end(), policy.begin(),
159 (int(*)(int)) tolower);
161 // Figure out fetch policy
162 if (policy == "singlethread") {
163 fetchPolicy = SingleThread;
165 panic("Invalid Fetch Policy for a SMT workload.");
166 } else if (policy == "roundrobin") {
167 fetchPolicy = RoundRobin;
168 DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
169 } else if (policy == "branch") {
170 fetchPolicy = Branch;
171 DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
172 } else if (policy == "iqcount") {
174 DPRINTF(Fetch, "Fetch policy set to IQ count\n");
175 } else if (policy == "lsqcount") {
177 DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
179 fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
180 " RoundRobin,LSQcount,IQcount}\n");
183 // Get the size of an instruction.
184 instSize = sizeof(TheISA::MachInst);
186 // Name is finally available, so create the port.
187 icachePort = new IcachePort(this);
189 icachePort->snoopRangeSent = false;
193 cpu->checker->setIcachePort(icachePort);
198 template <class Impl>
200 DefaultFetch<Impl>::name() const
202 return cpu->name() + ".fetch";
205 template <class Impl>
207 DefaultFetch<Impl>::regStats()
210 .name(name() + ".icacheStallCycles")
211 .desc("Number of cycles fetch is stalled on an Icache miss")
212 .prereq(icacheStallCycles);
215 .name(name() + ".Insts")
216 .desc("Number of instructions fetch has processed")
217 .prereq(fetchedInsts);
220 .name(name() + ".Branches")
221 .desc("Number of branches that fetch encountered")
222 .prereq(fetchedBranches);
225 .name(name() + ".predictedBranches")
226 .desc("Number of branches that fetch has predicted taken")
227 .prereq(predictedBranches);
230 .name(name() + ".Cycles")
231 .desc("Number of cycles fetch has run and was not squashing or"
233 .prereq(fetchCycles);
236 .name(name() + ".SquashCycles")
237 .desc("Number of cycles fetch has spent squashing")
238 .prereq(fetchSquashCycles);
241 .name(name() + ".TlbCycles")
242 .desc("Number of cycles fetch has spent waiting for tlb")
243 .prereq(fetchTlbCycles);
246 .name(name() + ".IdleCycles")
247 .desc("Number of cycles fetch was idle")
248 .prereq(fetchIdleCycles);
251 .name(name() + ".BlockedCycles")
252 .desc("Number of cycles fetch has spent blocked")
253 .prereq(fetchBlockedCycles);
256 .name(name() + ".CacheLines")
257 .desc("Number of cache lines fetched")
258 .prereq(fetchedCacheLines);
261 .name(name() + ".MiscStallCycles")
262 .desc("Number of cycles fetch has spent waiting on interrupts, or "
263 "bad addresses, or out of MSHRs")
264 .prereq(fetchMiscStallCycles);
267 .name(name() + ".IcacheSquashes")
268 .desc("Number of outstanding Icache misses that were squashed")
269 .prereq(fetchIcacheSquashes);
272 .name(name() + ".ItlbSquashes")
273 .desc("Number of outstanding ITLB misses that were squashed")
274 .prereq(fetchTlbSquashes);
277 .init(/* base value */ 0,
278 /* last value */ fetchWidth,
280 .name(name() + ".rateDist")
281 .desc("Number of instructions fetched each cycle (Total)")
285 .name(name() + ".idleRate")
286 .desc("Percent of cycles fetch was idle")
288 idleRate = fetchIdleCycles * 100 / cpu->numCycles;
291 .name(name() + ".branchRate")
292 .desc("Number of branch fetches per cycle")
293 .flags(Stats::total);
294 branchRate = fetchedBranches / cpu->numCycles;
297 .name(name() + ".rate")
298 .desc("Number of inst fetches per cycle")
299 .flags(Stats::total);
300 fetchRate = fetchedInsts / cpu->numCycles;
302 branchPred.regStats();
307 DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
309 timeBuffer = time_buffer;
311 // Create wires to get information from proper places in time buffer.
312 fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
313 fromRename = timeBuffer->getWire(-renameToFetchDelay);
314 fromIEW = timeBuffer->getWire(-iewToFetchDelay);
315 fromCommit = timeBuffer->getWire(-commitToFetchDelay);
320 DefaultFetch<Impl>::setActiveThreads(std::list<ThreadID> *at_ptr)
322 activeThreads = at_ptr;
327 DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
331 // Create wire to write information to proper place in fetch queue.
332 toDecode = fetchQueue->getWire(0);
337 DefaultFetch<Impl>::initStage()
339 // Setup PC and nextPC with initial state.
340 for (ThreadID tid = 0; tid < numThreads; tid++) {
341 pc[tid] = cpu->pcState(tid);
342 fetchOffset[tid] = 0;
346 for (ThreadID tid = 0; tid < numThreads; tid++) {
348 fetchStatus[tid] = Running;
350 priorityList.push_back(tid);
354 stalls[tid].decode = false;
355 stalls[tid].rename = false;
356 stalls[tid].iew = false;
357 stalls[tid].commit = false;
360 // Schedule fetch to get the correct PC from the CPU
361 // scheduleFetchStartupEvent(1);
363 // Fetch needs to start fetching instructions at the very beginning,
364 // so it must start up in active state.
370 DefaultFetch<Impl>::setIcache()
372 // Size of cache block.
373 cacheBlkSize = icachePort->peerBlockSize();
375 // Create mask to get rid of offset bits.
376 cacheBlkMask = (cacheBlkSize - 1);
378 for (ThreadID tid = 0; tid < numThreads; tid++) {
379 // Create space to store a cache line.
380 cacheData[tid] = new uint8_t[cacheBlkSize];
381 cacheDataPC[tid] = 0;
382 cacheDataValid[tid] = false;
388 DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
390 ThreadID tid = pkt->req->threadId();
392 DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n", tid);
394 assert(!pkt->wasNacked());
396 // Only change the status if it's still waiting on the icache access
398 if (fetchStatus[tid] != IcacheWaitResponse ||
399 pkt->req != memReq[tid] ||
401 ++fetchIcacheSquashes;
407 memcpy(cacheData[tid], pkt->getPtr<uint8_t>(), cacheBlkSize);
408 cacheDataValid[tid] = true;
411 // Wake up the CPU (if it went to sleep and was waiting on
412 // this completion event).
415 DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
421 // Only switch to IcacheAccessComplete if we're not stalled as well.
422 if (checkStall(tid)) {
423 fetchStatus[tid] = Blocked;
425 fetchStatus[tid] = IcacheAccessComplete;
428 // Reset the mem req to NULL.
434 template <class Impl>
436 DefaultFetch<Impl>::drain()
438 // Fetch is ready to drain at any time.
439 cpu->signalDrained();
444 template <class Impl>
446 DefaultFetch<Impl>::resume()
448 drainPending = false;
451 template <class Impl>
453 DefaultFetch<Impl>::switchOut()
456 // Branch predictor needs to have its state cleared.
457 branchPred.switchOut();
460 template <class Impl>
462 DefaultFetch<Impl>::takeOverFrom()
465 for (ThreadID i = 0; i < Impl::MaxThreads; ++i) {
466 stalls[i].decode = 0;
467 stalls[i].rename = 0;
469 stalls[i].commit = 0;
470 pc[i] = cpu->pcState(i);
471 fetchStatus[i] = Running;
474 wroteToTimeBuffer = false;
477 interruptPending = false;
478 branchPred.takeOverFrom();
481 template <class Impl>
483 DefaultFetch<Impl>::wakeFromQuiesce()
485 DPRINTF(Fetch, "Waking up from quiesce\n");
486 // Hopefully this is safe
487 // @todo: Allow other threads to wake from quiesce.
488 fetchStatus[0] = Running;
491 template <class Impl>
493 DefaultFetch<Impl>::switchToActive()
495 if (_status == Inactive) {
496 DPRINTF(Activity, "Activating stage.\n");
498 cpu->activateStage(O3CPU::FetchIdx);
504 template <class Impl>
506 DefaultFetch<Impl>::switchToInactive()
508 if (_status == Active) {
509 DPRINTF(Activity, "Deactivating stage.\n");
511 cpu->deactivateStage(O3CPU::FetchIdx);
517 template <class Impl>
519 DefaultFetch<Impl>::lookupAndUpdateNextPC(
520 DynInstPtr &inst, TheISA::PCState &nextPC)
522 // Do branch prediction check here.
523 // A bit of a misnomer...next_PC is actually the current PC until
524 // this function updates it.
527 if (!inst->isControl()) {
528 TheISA::advancePC(nextPC, inst->staticInst);
529 inst->setPredTarg(nextPC);
530 inst->setPredTaken(false);
534 ThreadID tid = inst->threadNumber;
535 predict_taken = branchPred.predict(inst, nextPC, tid);
538 DPRINTF(Fetch, "[tid:%i]: [sn:%i]: Branch predicted to be taken to %s.\n",
539 tid, inst->seqNum, nextPC);
541 DPRINTF(Fetch, "[tid:%i]: [sn:%i]:Branch predicted to be not taken.\n",
545 DPRINTF(Fetch, "[tid:%i]: [sn:%i] Branch predicted to go to %s.\n",
546 tid, inst->seqNum, nextPC);
547 inst->setPredTarg(nextPC);
548 inst->setPredTaken(predict_taken);
556 return predict_taken;
559 template <class Impl>
561 DefaultFetch<Impl>::fetchCacheLine(Addr vaddr, ThreadID tid, Addr pc)
563 Fault fault = NoFault;
565 // @todo: not sure if these should block translation.
568 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
571 } else if (isSwitchedOut()) {
572 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, switched out\n",
575 } else if (checkInterrupt(pc)) {
576 // Hold off fetch from getting new instructions when:
577 // Cache is blocked, or
578 // while an interrupt is pending and we're not in PAL mode, or
579 // fetch is switched out.
580 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n",
585 // Align the fetch address so it's at the start of a cache block.
586 Addr block_PC = icacheBlockAlignPC(vaddr);
588 DPRINTF(Fetch, "[tid:%i] Fetching cache line %#x for addr %#x\n",
589 tid, block_PC, vaddr);
591 // Setup the memReq to do a read of the first instruction's address.
592 // Set the appropriate read size and flags as well.
593 // Build request here.
595 new Request(tid, block_PC, cacheBlkSize, Request::INST_FETCH,
596 pc, cpu->thread[tid]->contextId(), tid);
598 memReq[tid] = mem_req;
600 // Initiate translation of the icache block
601 fetchStatus[tid] = ItlbWait;
602 FetchTranslation *trans = new FetchTranslation(this);
603 cpu->itb->translateTiming(mem_req, cpu->thread[tid]->getTC(),
604 trans, BaseTLB::Execute);
608 template <class Impl>
610 DefaultFetch<Impl>::finishTranslation(Fault fault, RequestPtr mem_req)
612 ThreadID tid = mem_req->threadId();
613 Addr block_PC = mem_req->getVaddr();
615 // Wake up CPU if it was idle
618 if (fetchStatus[tid] != ItlbWait || mem_req != memReq[tid] ||
619 mem_req->getVaddr() != memReq[tid]->getVaddr() || isSwitchedOut()) {
620 DPRINTF(Fetch, "[tid:%i] Ignoring itlb completed after squash\n",
628 // If translation was successful, attempt to read the icache block.
629 if (fault == NoFault) {
630 // Build packet here.
631 PacketPtr data_pkt = new Packet(mem_req,
632 MemCmd::ReadReq, Packet::Broadcast);
633 data_pkt->dataDynamicArray(new uint8_t[cacheBlkSize]);
635 cacheDataPC[tid] = block_PC;
636 cacheDataValid[tid] = false;
637 DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
642 if (!icachePort->sendTiming(data_pkt)) {
643 assert(retryPkt == NULL);
644 assert(retryTid == InvalidThreadID);
645 DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
647 fetchStatus[tid] = IcacheWaitRetry;
652 DPRINTF(Fetch, "[tid:%i]: Doing Icache access.\n", tid);
653 DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
656 lastIcacheStall[tid] = curTick();
657 fetchStatus[tid] = IcacheWaitResponse;
660 DPRINTF(Fetch, "[tid:%i] Got back req with addr %#x but expected %#x\n",
661 mem_req->getVaddr(), memReq[tid]->getVaddr());
662 // Translation faulted, icache request won't be sent.
666 // Send the fault to commit. This thread will not do anything
667 // until commit handles the fault. The only other way it can
668 // wake up is if a squash comes along and changes the PC.
669 TheISA::PCState fetchPC = pc[tid];
671 DPRINTF(Fetch, "[tid:%i]: Translation faulted, building noop.\n", tid);
672 // We will use a nop in ordier to carry the fault.
673 DynInstPtr instruction = buildInst(tid,
674 StaticInstPtr(TheISA::NoopMachInst, fetchPC.instAddr()),
675 NULL, fetchPC, fetchPC, false);
677 instruction->setPredTarg(fetchPC);
678 instruction->fault = fault;
679 wroteToTimeBuffer = true;
681 DPRINTF(Activity, "Activity this cycle.\n");
682 cpu->activityThisCycle();
684 fetchStatus[tid] = TrapPending;
686 DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n", tid);
687 DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %s.\n",
688 tid, fault->name(), pc[tid]);
690 _status = updateFetchStatus();
693 template <class Impl>
695 DefaultFetch<Impl>::doSquash(const TheISA::PCState &newPC, ThreadID tid)
697 DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %s.\n",
701 fetchOffset[tid] = 0;
705 // Clear the icache miss if it's outstanding.
706 if (fetchStatus[tid] == IcacheWaitResponse) {
707 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
710 } else if (fetchStatus[tid] == ItlbWait) {
711 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding ITLB miss.\n",
716 // Get rid of the retrying packet if it was from this thread.
717 if (retryTid == tid) {
718 assert(cacheBlocked);
720 delete retryPkt->req;
724 retryTid = InvalidThreadID;
727 fetchStatus[tid] = Squashing;
734 DefaultFetch<Impl>::squashFromDecode(const TheISA::PCState &newPC,
735 const InstSeqNum &seq_num, ThreadID tid)
737 DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n", tid);
739 doSquash(newPC, tid);
741 // Tell the CPU to remove any instructions that are in flight between
743 cpu->removeInstsUntil(seq_num, tid);
748 DefaultFetch<Impl>::checkStall(ThreadID tid) const
750 bool ret_val = false;
752 if (cpu->contextSwitch) {
753 DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
755 } else if (stalls[tid].decode) {
756 DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
758 } else if (stalls[tid].rename) {
759 DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
761 } else if (stalls[tid].iew) {
762 DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
764 } else if (stalls[tid].commit) {
765 DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
773 typename DefaultFetch<Impl>::FetchStatus
774 DefaultFetch<Impl>::updateFetchStatus()
777 list<ThreadID>::iterator threads = activeThreads->begin();
778 list<ThreadID>::iterator end = activeThreads->end();
780 while (threads != end) {
781 ThreadID tid = *threads++;
783 if (fetchStatus[tid] == Running ||
784 fetchStatus[tid] == Squashing ||
785 fetchStatus[tid] == IcacheAccessComplete) {
787 if (_status == Inactive) {
788 DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
790 if (fetchStatus[tid] == IcacheAccessComplete) {
791 DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
795 cpu->activateStage(O3CPU::FetchIdx);
802 // Stage is switching from active to inactive, notify CPU of it.
803 if (_status == Active) {
804 DPRINTF(Activity, "Deactivating stage.\n");
806 cpu->deactivateStage(O3CPU::FetchIdx);
812 template <class Impl>
814 DefaultFetch<Impl>::squash(const TheISA::PCState &newPC,
815 const InstSeqNum &seq_num, ThreadID tid)
817 DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n", tid);
819 doSquash(newPC, tid);
821 // Tell the CPU to remove any instructions that are not in the ROB.
822 cpu->removeInstsNotInROB(tid);
825 template <class Impl>
827 DefaultFetch<Impl>::tick()
829 list<ThreadID>::iterator threads = activeThreads->begin();
830 list<ThreadID>::iterator end = activeThreads->end();
831 bool status_change = false;
833 wroteToTimeBuffer = false;
835 while (threads != end) {
836 ThreadID tid = *threads++;
838 // Check the signals for each thread to determine the proper status
840 bool updated_status = checkSignalsAndUpdate(tid);
841 status_change = status_change || updated_status;
844 DPRINTF(Fetch, "Running stage.\n");
846 // Reset the number of the instruction we're fetching.
850 if (fromCommit->commitInfo[0].interruptPending) {
851 interruptPending = true;
854 if (fromCommit->commitInfo[0].clearInterrupt) {
855 interruptPending = false;
859 for (threadFetched = 0; threadFetched < numFetchingThreads;
861 // Fetch each of the actively fetching threads.
862 fetch(status_change);
865 // Record number of instructions fetched this cycle for distribution.
866 fetchNisnDist.sample(numInst);
869 // Change the fetch stage status if there was a status change.
870 _status = updateFetchStatus();
873 // If there was activity this cycle, inform the CPU of it.
874 if (wroteToTimeBuffer || cpu->contextSwitch) {
875 DPRINTF(Activity, "Activity this cycle.\n");
877 cpu->activityThisCycle();
881 template <class Impl>
883 DefaultFetch<Impl>::checkSignalsAndUpdate(ThreadID tid)
885 // Update the per thread stall statuses.
886 if (fromDecode->decodeBlock[tid]) {
887 stalls[tid].decode = true;
890 if (fromDecode->decodeUnblock[tid]) {
891 assert(stalls[tid].decode);
892 assert(!fromDecode->decodeBlock[tid]);
893 stalls[tid].decode = false;
896 if (fromRename->renameBlock[tid]) {
897 stalls[tid].rename = true;
900 if (fromRename->renameUnblock[tid]) {
901 assert(stalls[tid].rename);
902 assert(!fromRename->renameBlock[tid]);
903 stalls[tid].rename = false;
906 if (fromIEW->iewBlock[tid]) {
907 stalls[tid].iew = true;
910 if (fromIEW->iewUnblock[tid]) {
911 assert(stalls[tid].iew);
912 assert(!fromIEW->iewBlock[tid]);
913 stalls[tid].iew = false;
916 if (fromCommit->commitBlock[tid]) {
917 stalls[tid].commit = true;
920 if (fromCommit->commitUnblock[tid]) {
921 assert(stalls[tid].commit);
922 assert(!fromCommit->commitBlock[tid]);
923 stalls[tid].commit = false;
926 // Check squash signals from commit.
927 if (fromCommit->commitInfo[tid].squash) {
929 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
930 "from commit.\n",tid);
931 // In any case, squash.
932 squash(fromCommit->commitInfo[tid].pc,
933 fromCommit->commitInfo[tid].doneSeqNum,
936 // If it was a branch mispredict on a control instruction, update the
937 // branch predictor with that instruction, otherwise just kill the
938 // invalid state we generated in after sequence number
939 assert(!fromCommit->commitInfo[tid].branchMispredict ||
940 fromCommit->commitInfo[tid].mispredictInst);
942 if (fromCommit->commitInfo[tid].branchMispredict &&
943 fromCommit->commitInfo[tid].mispredictInst->isControl()) {
944 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
945 fromCommit->commitInfo[tid].pc,
946 fromCommit->commitInfo[tid].branchTaken,
949 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
954 } else if (fromCommit->commitInfo[tid].doneSeqNum) {
955 // Update the branch predictor if it wasn't a squashed instruction
956 // that was broadcasted.
957 branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
960 // Check ROB squash signals from commit.
961 if (fromCommit->commitInfo[tid].robSquashing) {
962 DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
964 // Continue to squash.
965 fetchStatus[tid] = Squashing;
970 // Check squash signals from decode.
971 if (fromDecode->decodeInfo[tid].squash) {
972 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
973 "from decode.\n",tid);
975 // Update the branch predictor.
976 if (fromDecode->decodeInfo[tid].branchMispredict) {
977 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
978 fromDecode->decodeInfo[tid].nextPC,
979 fromDecode->decodeInfo[tid].branchTaken,
982 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
986 if (fetchStatus[tid] != Squashing) {
988 TheISA::PCState nextPC = fromDecode->decodeInfo[tid].nextPC;
989 DPRINTF(Fetch, "Squashing from decode with PC = %s\n", nextPC);
990 // Squash unless we're already squashing
991 squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
992 fromDecode->decodeInfo[tid].doneSeqNum,
999 if (checkStall(tid) &&
1000 fetchStatus[tid] != IcacheWaitResponse &&
1001 fetchStatus[tid] != IcacheWaitRetry) {
1002 DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
1004 fetchStatus[tid] = Blocked;
1009 if (fetchStatus[tid] == Blocked ||
1010 fetchStatus[tid] == Squashing) {
1011 // Switch status to running if fetch isn't being told to block or
1012 // squash this cycle.
1013 DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
1016 fetchStatus[tid] = Running;
1021 // If we've reached this point, we have not gotten any signals that
1022 // cause fetch to change its status. Fetch remains the same as before.
1026 template<class Impl>
1027 typename Impl::DynInstPtr
1028 DefaultFetch<Impl>::buildInst(ThreadID tid, StaticInstPtr staticInst,
1029 StaticInstPtr curMacroop, TheISA::PCState thisPC,
1030 TheISA::PCState nextPC, bool trace)
1032 // Get a sequence number.
1033 InstSeqNum seq = cpu->getAndIncrementInstSeq();
1035 // Create a new DynInst from the instruction fetched.
1036 DynInstPtr instruction =
1037 new DynInst(staticInst, thisPC, nextPC, seq, cpu);
1038 instruction->setTid(tid);
1040 instruction->setASID(tid);
1042 instruction->setThreadState(cpu->thread[tid]);
1044 DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x (%d) created "
1045 "[sn:%lli].\n", tid, thisPC.instAddr(),
1046 thisPC.microPC(), seq);
1048 DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n", tid,
1049 instruction->staticInst->
1050 disassemble(thisPC.instAddr()));
1054 instruction->traceData =
1055 cpu->getTracer()->getInstRecord(curTick(), cpu->tcBase(tid),
1056 instruction->staticInst, thisPC, curMacroop);
1059 instruction->traceData = NULL;
1062 // Add instruction to the CPU's list of instructions.
1063 instruction->setInstListIt(cpu->addInst(instruction));
1065 // Write the instruction to the first slot in the queue
1066 // that heads to decode.
1067 assert(numInst < fetchWidth);
1068 toDecode->insts[toDecode->size++] = instruction;
1073 template<class Impl>
1075 DefaultFetch<Impl>::fetch(bool &status_change)
1077 //////////////////////////////////////////
1078 // Start actual fetch
1079 //////////////////////////////////////////
1080 ThreadID tid = getFetchingThread(fetchPolicy);
1082 if (tid == InvalidThreadID || drainPending) {
1083 DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
1085 // Breaks looping condition in tick()
1086 threadFetched = numFetchingThreads;
1090 DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
1093 TheISA::PCState thisPC = pc[tid];
1095 Addr pcOffset = fetchOffset[tid];
1096 Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1098 bool inRom = isRomMicroPC(thisPC.microPC());
1100 // If returning from the delay of a cache miss, then update the status
1101 // to running, otherwise do the cache access. Possibly move this up
1102 // to tick() function.
1103 if (fetchStatus[tid] == IcacheAccessComplete) {
1104 DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n", tid);
1106 fetchStatus[tid] = Running;
1107 status_change = true;
1108 } else if (fetchStatus[tid] == Running) {
1109 // Align the fetch PC so its at the start of a cache block.
1110 Addr block_PC = icacheBlockAlignPC(fetchAddr);
1112 // Unless buffer already got the block, fetch it from icache.
1113 if (!(cacheDataValid[tid] && block_PC == cacheDataPC[tid]) && !inRom) {
1114 DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
1115 "instruction, starting at PC %s.\n", tid, thisPC);
1117 fetchCacheLine(fetchAddr, tid, thisPC.instAddr());
1119 if (fetchStatus[tid] == IcacheWaitResponse)
1120 ++icacheStallCycles;
1121 else if (fetchStatus[tid] == ItlbWait)
1124 ++fetchMiscStallCycles;
1126 } else if (checkInterrupt(thisPC.instAddr()) || isSwitchedOut()) {
1127 ++fetchMiscStallCycles;
1131 if (fetchStatus[tid] == Idle) {
1133 DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
1134 } else if (fetchStatus[tid] == Blocked) {
1135 ++fetchBlockedCycles;
1136 DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
1137 } else if (fetchStatus[tid] == Squashing) {
1138 ++fetchSquashCycles;
1139 DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
1140 } else if (fetchStatus[tid] == IcacheWaitResponse) {
1141 ++icacheStallCycles;
1142 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n",
1144 } else if (fetchStatus[tid] == ItlbWait) {
1145 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting ITLB walk to "
1148 } else if (fetchStatus[tid] == TrapPending) {
1149 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending trap\n",
1154 // Status is Idle, Squashing, Blocked, ItlbWait or IcacheWaitResponse
1155 // so fetch should do nothing.
1161 TheISA::PCState nextPC = thisPC;
1163 StaticInstPtr staticInst = NULL;
1164 StaticInstPtr curMacroop = macroop[tid];
1166 // If the read of the first instruction was successful, then grab the
1167 // instructions from the rest of the cache line and put them into the
1168 // queue heading to decode.
1170 DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
1173 // Need to keep track of whether or not a predicted branch
1174 // ended this fetch block.
1175 bool predictedBranch = false;
1177 TheISA::MachInst *cacheInsts =
1178 reinterpret_cast<TheISA::MachInst *>(cacheData[tid]);
1180 const unsigned numInsts = cacheBlkSize / instSize;
1181 unsigned blkOffset = (fetchAddr - cacheDataPC[tid]) / instSize;
1183 // Loop through instruction memory from the cache.
1184 while (blkOffset < numInsts &&
1185 numInst < fetchWidth &&
1188 // If we need to process more memory, do it now.
1189 if (!(curMacroop || inRom) && !predecoder.extMachInstReady()) {
1190 if (ISA_HAS_DELAY_SLOT && pcOffset == 0) {
1191 // Walk past any annulled delay slot instructions.
1192 Addr pcAddr = thisPC.instAddr() & BaseCPU::PCMask;
1193 while (fetchAddr != pcAddr && blkOffset < numInsts) {
1195 fetchAddr += instSize;
1197 if (blkOffset >= numInsts)
1200 MachInst inst = TheISA::gtoh(cacheInsts[blkOffset]);
1202 predecoder.setTC(cpu->thread[tid]->getTC());
1203 predecoder.moreBytes(thisPC, fetchAddr, inst);
1205 if (predecoder.needMoreBytes()) {
1207 fetchAddr += instSize;
1208 pcOffset += instSize;
1212 // Extract as many instructions and/or microops as we can from
1213 // the memory we've processed so far.
1215 if (!(curMacroop || inRom)) {
1216 if (predecoder.extMachInstReady()) {
1217 ExtMachInst extMachInst;
1219 extMachInst = predecoder.getExtMachInst(thisPC);
1220 staticInst = StaticInstPtr(extMachInst,
1223 // Increment stat of fetched instructions.
1226 if (staticInst->isMacroop()) {
1227 curMacroop = staticInst;
1232 // We need more bytes for this instruction.
1236 if (curMacroop || inRom) {
1238 staticInst = cpu->microcodeRom.fetchMicroop(
1239 thisPC.microPC(), curMacroop);
1241 staticInst = curMacroop->fetchMicroop(thisPC.microPC());
1243 if (staticInst->isLastMicroop()) {
1249 DynInstPtr instruction =
1250 buildInst(tid, staticInst, curMacroop,
1251 thisPC, nextPC, true);
1257 // If we're branching after this instruction, quite fetching
1258 // from the same block then.
1259 predictedBranch |= thisPC.branching();
1261 lookupAndUpdateNextPC(instruction, nextPC);
1262 if (predictedBranch) {
1263 DPRINTF(Fetch, "Branch detected with PC = %s\n", thisPC);
1266 // Move to the next instruction, unless we have a branch.
1269 if (instruction->isQuiesce()) {
1271 "Quiesce instruction encountered, halting fetch!");
1272 fetchStatus[tid] = QuiescePending;
1273 status_change = true;
1276 } while ((curMacroop || predecoder.extMachInstReady()) &&
1277 numInst < fetchWidth);
1280 if (predictedBranch) {
1281 DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
1282 "instruction encountered.\n", tid);
1283 } else if (numInst >= fetchWidth) {
1284 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
1285 "for this cycle.\n", tid);
1286 } else if (blkOffset >= cacheBlkSize) {
1287 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of cache "
1291 macroop[tid] = curMacroop;
1292 fetchOffset[tid] = pcOffset;
1295 wroteToTimeBuffer = true;
1301 template<class Impl>
1303 DefaultFetch<Impl>::recvRetry()
1305 if (retryPkt != NULL) {
1306 assert(cacheBlocked);
1307 assert(retryTid != InvalidThreadID);
1308 assert(fetchStatus[retryTid] == IcacheWaitRetry);
1310 if (icachePort->sendTiming(retryPkt)) {
1311 fetchStatus[retryTid] = IcacheWaitResponse;
1313 retryTid = InvalidThreadID;
1314 cacheBlocked = false;
1317 assert(retryTid == InvalidThreadID);
1318 // Access has been squashed since it was sent out. Just clear
1319 // the cache being blocked.
1320 cacheBlocked = false;
1324 ///////////////////////////////////////
1326 // SMT FETCH POLICY MAINTAINED HERE //
1328 ///////////////////////////////////////
1329 template<class Impl>
1331 DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1333 if (numThreads > 1) {
1334 switch (fetch_priority) {
1340 return roundRobin();
1349 return branchCount();
1352 return InvalidThreadID;
1355 list<ThreadID>::iterator thread = activeThreads->begin();
1356 if (thread == activeThreads->end()) {
1357 return InvalidThreadID;
1360 ThreadID tid = *thread;
1362 if (fetchStatus[tid] == Running ||
1363 fetchStatus[tid] == IcacheAccessComplete ||
1364 fetchStatus[tid] == Idle) {
1367 return InvalidThreadID;
1373 template<class Impl>
1375 DefaultFetch<Impl>::roundRobin()
1377 list<ThreadID>::iterator pri_iter = priorityList.begin();
1378 list<ThreadID>::iterator end = priorityList.end();
1382 while (pri_iter != end) {
1383 high_pri = *pri_iter;
1385 assert(high_pri <= numThreads);
1387 if (fetchStatus[high_pri] == Running ||
1388 fetchStatus[high_pri] == IcacheAccessComplete ||
1389 fetchStatus[high_pri] == Idle) {
1391 priorityList.erase(pri_iter);
1392 priorityList.push_back(high_pri);
1400 return InvalidThreadID;
1403 template<class Impl>
1405 DefaultFetch<Impl>::iqCount()
1407 std::priority_queue<ThreadID> PQ;
1409 list<ThreadID>::iterator threads = activeThreads->begin();
1410 list<ThreadID>::iterator end = activeThreads->end();
1412 while (threads != end) {
1413 ThreadID tid = *threads++;
1415 PQ.push(fromIEW->iewInfo[tid].iqCount);
1418 while (!PQ.empty()) {
1419 ThreadID high_pri = PQ.top();
1421 if (fetchStatus[high_pri] == Running ||
1422 fetchStatus[high_pri] == IcacheAccessComplete ||
1423 fetchStatus[high_pri] == Idle)
1430 return InvalidThreadID;
1433 template<class Impl>
1435 DefaultFetch<Impl>::lsqCount()
1437 std::priority_queue<ThreadID> PQ;
1439 list<ThreadID>::iterator threads = activeThreads->begin();
1440 list<ThreadID>::iterator end = activeThreads->end();
1442 while (threads != end) {
1443 ThreadID tid = *threads++;
1445 PQ.push(fromIEW->iewInfo[tid].ldstqCount);
1448 while (!PQ.empty()) {
1449 ThreadID high_pri = PQ.top();
1451 if (fetchStatus[high_pri] == Running ||
1452 fetchStatus[high_pri] == IcacheAccessComplete ||
1453 fetchStatus[high_pri] == Idle)
1459 return InvalidThreadID;
1462 template<class Impl>
1464 DefaultFetch<Impl>::branchCount()
1467 list<ThreadID>::iterator thread = activeThreads->begin();
1468 assert(thread != activeThreads->end());
1469 ThreadID tid = *thread;
1472 panic("Branch Count Fetch policy unimplemented\n");
1473 return InvalidThreadID;