2 * Copyright (c) 2010-2012, 2014 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.
44 #ifndef __CPU_O3_FETCH_HH__
45 #define __CPU_O3_FETCH_HH__
47 #include "arch/decoder.hh"
48 #include "arch/utility.hh"
49 #include "base/statistics.hh"
50 #include "config/the_isa.hh"
51 #include "cpu/pc_event.hh"
52 #include "cpu/pred/bpred_unit.hh"
53 #include "cpu/timebuf.hh"
54 #include "cpu/translation.hh"
55 #include "enums/FetchPolicy.hh"
56 #include "mem/packet.hh"
57 #include "mem/port.hh"
58 #include "sim/eventq.hh"
59 #include "sim/probe/probe.hh"
61 struct DerivO3CPUParams;
64 * DefaultFetch class handles both single threaded and SMT fetch. Its
65 * width is specified by the parameters; each cycle it tries to fetch
66 * that many instructions. It supports using a branch predictor to
67 * predict direction and targets.
68 * It supports the idling functionality of the CPU by indicating to
69 * the CPU when it is active and inactive.
75 /** Typedefs from Impl. */
76 typedef typename Impl::CPUPol CPUPol;
77 typedef typename Impl::DynInst DynInst;
78 typedef typename Impl::DynInstPtr DynInstPtr;
79 typedef typename Impl::O3CPU O3CPU;
81 /** Typedefs from the CPU policy. */
82 typedef typename CPUPol::FetchStruct FetchStruct;
83 typedef typename CPUPol::TimeStruct TimeStruct;
85 /** Typedefs from ISA. */
86 typedef TheISA::MachInst MachInst;
88 class FetchTranslation : public BaseTLB::Translation
91 DefaultFetch<Impl> *fetch;
94 FetchTranslation(DefaultFetch<Impl> *_fetch)
103 finish(const Fault &fault, const RequestPtr &req, ThreadContext *tc,
106 assert(mode == BaseTLB::Execute);
107 fetch->finishTranslation(fault, req);
113 /* Event to delay delivery of a fetch translation result in case of
114 * a fault and the nop to carry the fault cannot be generated
116 class FinishTranslationEvent : public Event
119 DefaultFetch<Impl> *fetch;
124 FinishTranslationEvent(DefaultFetch<Impl> *_fetch)
125 : fetch(_fetch), req(nullptr)
128 void setFault(Fault _fault)
133 void setReq(const RequestPtr &_req)
138 /** Process the delayed finish translation */
141 assert(fetch->numInst < fetch->fetchWidth);
142 fetch->finishTranslation(fault, req);
145 const char *description() const
147 return "FullO3CPU FetchFinishTranslation";
152 /** Overall fetch status. Used to determine if the CPU can
153 * deschedule itsef due to a lack of activity.
160 /** Individual thread status. */
172 IcacheAccessComplete,
180 /** Per-thread status. */
181 ThreadStatus fetchStatus[Impl::MaxThreads];
184 FetchPolicy fetchPolicy;
186 /** List that has the threads organized by priority. */
187 std::list<ThreadID> priorityList;
190 ProbePointArg<DynInstPtr> *ppFetch;
191 /** To probe when a fetch request is successfully sent. */
192 ProbePointArg<RequestPtr> *ppFetchRequestSent;
195 /** DefaultFetch constructor. */
196 DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params);
198 /** Returns the name of fetch. */
199 std::string name() const;
201 /** Registers statistics. */
204 /** Registers probes. */
205 void regProbePoints();
207 /** Sets the main backwards communication time buffer pointer. */
208 void setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer);
210 /** Sets pointer to list of active threads. */
211 void setActiveThreads(std::list<ThreadID> *at_ptr);
213 /** Sets pointer to time buffer used to communicate to the next stage. */
214 void setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr);
216 /** Initialize stage. */
219 /** Clear all thread-specific states*/
220 void clearStates(ThreadID tid);
222 /** Handles retrying the fetch access. */
225 /** Processes cache completion event. */
226 void processCacheCompletion(PacketPtr pkt);
228 /** Resume after a drain. */
231 /** Perform sanity checks after a drain. */
232 void drainSanityCheck() const;
234 /** Has the stage drained? */
235 bool isDrained() const;
237 /** Takes over from another CPU's thread. */
241 * Stall the fetch stage after reaching a safe drain point.
243 * The CPU uses this method to stop fetching instructions from a
244 * thread that has been drained. The drain stall is different from
245 * all other stalls in that it is signaled instantly from the
246 * commit stage (without the normal communication delay) when it
247 * has reached a safe point to drain from.
249 void drainStall(ThreadID tid);
251 /** Tells fetch to wake up from a quiesce instruction. */
252 void wakeFromQuiesce();
254 /** For priority-based fetch policies, need to keep update priorityList */
255 void deactivateThread(ThreadID tid);
257 /** Reset this pipeline stage */
260 /** Changes the status of this stage to active, and indicates this
263 inline void switchToActive();
265 /** Changes the status of this stage to inactive, and indicates
268 inline void switchToInactive();
271 * Looks up in the branch predictor to see if the next PC should be
272 * either next PC+=MachInst or a branch target.
273 * @param next_PC Next PC variable passed in by reference. It is
274 * expected to be set to the current PC; it will be updated with what
275 * the next PC will be.
276 * @param next_NPC Used for ISAs which use delay slots.
277 * @return Whether or not a branch was predicted as taken.
279 bool lookupAndUpdateNextPC(const DynInstPtr &inst, TheISA::PCState &pc);
282 * Fetches the cache line that contains the fetch PC. Returns any
283 * fault that happened. Puts the data into the class variable
284 * fetchBuffer, which may not hold the entire fetched cache line.
285 * @param vaddr The memory address that is being fetched from.
286 * @param ret_fault The fault reference that will be set to the result of
288 * @param tid Thread id.
289 * @param pc The actual PC of the current instruction.
290 * @return Any fault that occured.
292 bool fetchCacheLine(Addr vaddr, ThreadID tid, Addr pc);
293 void finishTranslation(const Fault &fault, const RequestPtr &mem_req);
296 /** Check if an interrupt is pending and that we need to handle
299 checkInterrupt(Addr pc)
301 return (interruptPending && (THE_ISA != ALPHA_ISA || !(pc & 0x3)));
304 /** Squashes a specific thread and resets the PC. */
305 inline void doSquash(const TheISA::PCState &newPC,
306 const DynInstPtr squashInst, ThreadID tid);
308 /** Squashes a specific thread and resets the PC. Also tells the CPU to
309 * remove any instructions between fetch and decode that should be sqaushed.
311 void squashFromDecode(const TheISA::PCState &newPC,
312 const DynInstPtr squashInst,
313 const InstSeqNum seq_num, ThreadID tid);
315 /** Checks if a thread is stalled. */
316 bool checkStall(ThreadID tid) const;
318 /** Updates overall fetch stage status; to be called at the end of each
320 FetchStatus updateFetchStatus();
323 /** Squashes a specific thread and resets the PC. Also tells the CPU to
324 * remove any instructions that are not in the ROB. The source of this
325 * squash should be the commit stage.
327 void squash(const TheISA::PCState &newPC, const InstSeqNum seq_num,
328 DynInstPtr squashInst, ThreadID tid);
330 /** Ticks the fetch stage, processing all inputs signals and fetching
331 * as many instructions as possible.
335 /** Checks all input signals and updates the status as necessary.
336 * @return: Returns if the status has changed due to input signals.
338 bool checkSignalsAndUpdate(ThreadID tid);
340 /** Does the actual fetching of instructions and passing them on to the
342 * @param status_change fetch() sets this variable if there was a status
343 * change (ie switching to IcacheMissStall).
345 void fetch(bool &status_change);
347 /** Align a PC to the start of a fetch buffer block. */
348 Addr fetchBufferAlignPC(Addr addr)
350 return (addr & ~(fetchBufferMask));
354 TheISA::Decoder *decoder[Impl::MaxThreads];
357 DynInstPtr buildInst(ThreadID tid, StaticInstPtr staticInst,
358 StaticInstPtr curMacroop, TheISA::PCState thisPC,
359 TheISA::PCState nextPC, bool trace);
361 /** Returns the appropriate thread to fetch, given the fetch policy. */
362 ThreadID getFetchingThread();
364 /** Returns the appropriate thread to fetch using a round robin policy. */
365 ThreadID roundRobin();
367 /** Returns the appropriate thread to fetch using the IQ count policy. */
370 /** Returns the appropriate thread to fetch using the LSQ count policy. */
373 /** Returns the appropriate thread to fetch using the branch count
375 ThreadID branchCount();
377 /** Pipeline the next I-cache access to the current one. */
378 void pipelineIcacheAccesses(ThreadID tid);
380 /** Profile the reasons of fetch stall. */
381 void profileStall(ThreadID tid);
384 /** Pointer to the O3CPU. */
387 /** Time buffer interface. */
388 TimeBuffer<TimeStruct> *timeBuffer;
390 /** Wire to get decode's information from backwards time buffer. */
391 typename TimeBuffer<TimeStruct>::wire fromDecode;
393 /** Wire to get rename's information from backwards time buffer. */
394 typename TimeBuffer<TimeStruct>::wire fromRename;
396 /** Wire to get iew's information from backwards time buffer. */
397 typename TimeBuffer<TimeStruct>::wire fromIEW;
399 /** Wire to get commit's information from backwards time buffer. */
400 typename TimeBuffer<TimeStruct>::wire fromCommit;
402 //Might be annoying how this name is different than the queue.
403 /** Wire used to write any information heading to decode. */
404 typename TimeBuffer<FetchStruct>::wire toDecode;
407 BPredUnit *branchPred;
409 TheISA::PCState pc[Impl::MaxThreads];
411 Addr fetchOffset[Impl::MaxThreads];
413 StaticInstPtr macroop[Impl::MaxThreads];
415 /** Can the fetch stage redirect from an interrupt on this instruction? */
416 bool delayedCommit[Impl::MaxThreads];
418 /** Memory request used to access cache. */
419 RequestPtr memReq[Impl::MaxThreads];
421 /** Variable that tracks if fetch has written to the time buffer this
422 * cycle. Used to tell CPU if there is activity this cycle.
424 bool wroteToTimeBuffer;
426 /** Tracks how many instructions has been fetched this cycle. */
429 /** Source of possible stalls. */
435 /** Tracks which stages are telling fetch to stall. */
436 Stalls stalls[Impl::MaxThreads];
438 /** Decode to fetch delay. */
439 Cycles decodeToFetchDelay;
441 /** Rename to fetch delay. */
442 Cycles renameToFetchDelay;
444 /** IEW to fetch delay. */
445 Cycles iewToFetchDelay;
447 /** Commit to fetch delay. */
448 Cycles commitToFetchDelay;
450 /** The width of fetch in instructions. */
453 /** The width of decode in instructions. */
454 unsigned decodeWidth;
456 /** Is the cache blocked? If so no threads can access it. */
459 /** The packet that is waiting to be retried. */
462 /** The thread that is waiting on the cache to tell fetch to retry. */
465 /** Cache block size. */
466 unsigned int cacheBlkSize;
468 /** The size of the fetch buffer in bytes. The fetch buffer
469 * itself may be smaller than a cache line.
471 unsigned fetchBufferSize;
473 /** Mask to align a fetch address to a fetch buffer boundary. */
474 Addr fetchBufferMask;
476 /** The fetch data that is being fetched and buffered. */
477 uint8_t *fetchBuffer[Impl::MaxThreads];
479 /** The PC of the first instruction loaded into the fetch buffer. */
480 Addr fetchBufferPC[Impl::MaxThreads];
482 /** The size of the fetch queue in micro-ops */
483 unsigned fetchQueueSize;
485 /** Queue of fetched instructions. Per-thread to prevent HoL blocking. */
486 std::deque<DynInstPtr> fetchQueue[Impl::MaxThreads];
488 /** Whether or not the fetch buffer data is valid. */
489 bool fetchBufferValid[Impl::MaxThreads];
491 /** Size of instructions. */
494 /** Icache stall statistics. */
495 Counter lastIcacheStall[Impl::MaxThreads];
497 /** List of Active Threads */
498 std::list<ThreadID> *activeThreads;
500 /** Number of threads. */
503 /** Number of threads that are actively fetching. */
504 ThreadID numFetchingThreads;
506 /** Thread ID being fetched. */
507 ThreadID threadFetched;
509 /** Checks if there is an interrupt pending. If there is, fetch
510 * must stop once it is not fetching PAL instructions.
512 bool interruptPending;
514 /** Set to true if a pipelined I-cache request should be issued. */
515 bool issuePipelinedIfetch[Impl::MaxThreads];
517 /** Event used to delay fault generation of translation faults */
518 FinishTranslationEvent finishTranslationEvent;
520 // @todo: Consider making these vectors and tracking on a per thread basis.
521 /** Stat for total number of cycles stalled due to an icache miss. */
522 Stats::Scalar icacheStallCycles;
523 /** Stat for total number of fetched instructions. */
524 Stats::Scalar fetchedInsts;
525 /** Total number of fetched branches. */
526 Stats::Scalar fetchedBranches;
527 /** Stat for total number of predicted branches. */
528 Stats::Scalar predictedBranches;
529 /** Stat for total number of cycles spent fetching. */
530 Stats::Scalar fetchCycles;
531 /** Stat for total number of cycles spent squashing. */
532 Stats::Scalar fetchSquashCycles;
533 /** Stat for total number of cycles spent waiting for translation */
534 Stats::Scalar fetchTlbCycles;
535 /** Stat for total number of cycles spent blocked due to other stages in
538 Stats::Scalar fetchIdleCycles;
539 /** Total number of cycles spent blocked. */
540 Stats::Scalar fetchBlockedCycles;
541 /** Total number of cycles spent in any other state. */
542 Stats::Scalar fetchMiscStallCycles;
543 /** Total number of cycles spent in waiting for drains. */
544 Stats::Scalar fetchPendingDrainCycles;
545 /** Total number of stall cycles caused by no active threads to run. */
546 Stats::Scalar fetchNoActiveThreadStallCycles;
547 /** Total number of stall cycles caused by pending traps. */
548 Stats::Scalar fetchPendingTrapStallCycles;
549 /** Total number of stall cycles caused by pending quiesce instructions. */
550 Stats::Scalar fetchPendingQuiesceStallCycles;
551 /** Total number of stall cycles caused by I-cache wait retrys. */
552 Stats::Scalar fetchIcacheWaitRetryStallCycles;
553 /** Stat for total number of fetched cache lines. */
554 Stats::Scalar fetchedCacheLines;
555 /** Total number of outstanding icache accesses that were dropped
558 Stats::Scalar fetchIcacheSquashes;
559 /** Total number of outstanding tlb accesses that were dropped
562 Stats::Scalar fetchTlbSquashes;
563 /** Distribution of number of instructions fetched each cycle. */
564 Stats::Distribution fetchNisnDist;
565 /** Rate of how often fetch was idle. */
566 Stats::Formula idleRate;
567 /** Number of branch fetches per cycle. */
568 Stats::Formula branchRate;
569 /** Number of instruction fetched per cycle. */
570 Stats::Formula fetchRate;
573 #endif //__CPU_O3_FETCH_HH__