fetch.hh revision 7847:0c6613ad8f18
1/*
2 * Copyright (c) 2004-2006 The Regents of The University of Michigan
3 * All rights reserved.
4 *
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.
15 *
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.
27 *
28 * Authors: Kevin Lim
29 *          Korey Sewell
30 */
31
32#ifndef __CPU_O3_FETCH_HH__
33#define __CPU_O3_FETCH_HH__
34
35#include "arch/utility.hh"
36#include "arch/predecoder.hh"
37#include "base/statistics.hh"
38#include "cpu/timebuf.hh"
39#include "config/the_isa.hh"
40#include "cpu/pc_event.hh"
41#include "mem/packet.hh"
42#include "mem/port.hh"
43#include "sim/eventq.hh"
44
45class DerivO3CPUParams;
46
47/**
48 * DefaultFetch class handles both single threaded and SMT fetch. Its
49 * width is specified by the parameters; each cycle it tries to fetch
50 * that many instructions. It supports using a branch predictor to
51 * predict direction and targets.
52 * It supports the idling functionality of the CPU by indicating to
53 * the CPU when it is active and inactive.
54 */
55template <class Impl>
56class DefaultFetch
57{
58  public:
59    /** Typedefs from Impl. */
60    typedef typename Impl::CPUPol CPUPol;
61    typedef typename Impl::DynInst DynInst;
62    typedef typename Impl::DynInstPtr DynInstPtr;
63    typedef typename Impl::O3CPU O3CPU;
64
65    /** Typedefs from the CPU policy. */
66    typedef typename CPUPol::BPredUnit BPredUnit;
67    typedef typename CPUPol::FetchStruct FetchStruct;
68    typedef typename CPUPol::TimeStruct TimeStruct;
69
70    /** Typedefs from ISA. */
71    typedef TheISA::MachInst MachInst;
72    typedef TheISA::ExtMachInst ExtMachInst;
73
74    /** IcachePort class for DefaultFetch.  Handles doing the
75     * communication with the cache/memory.
76     */
77    class IcachePort : public Port
78    {
79      protected:
80        /** Pointer to fetch. */
81        DefaultFetch<Impl> *fetch;
82
83      public:
84        /** Default constructor. */
85        IcachePort(DefaultFetch<Impl> *_fetch)
86            : Port(_fetch->name() + "-iport", _fetch->cpu), fetch(_fetch)
87        { }
88
89        bool snoopRangeSent;
90
91        virtual void setPeer(Port *port);
92
93      protected:
94        /** Atomic version of receive.  Panics. */
95        virtual Tick recvAtomic(PacketPtr pkt);
96
97        /** Functional version of receive.  Panics. */
98        virtual void recvFunctional(PacketPtr pkt);
99
100        /** Receives status change.  Other than range changing, panics. */
101        virtual void recvStatusChange(Status status);
102
103        /** Returns the address ranges of this device. */
104        virtual void getDeviceAddressRanges(AddrRangeList &resp,
105                                            bool &snoop)
106        { resp.clear(); snoop = true; }
107
108        /** Timing version of receive.  Handles setting fetch to the
109         * proper status to start fetching. */
110        virtual bool recvTiming(PacketPtr pkt);
111
112        /** Handles doing a retry of a failed fetch. */
113        virtual void recvRetry();
114    };
115
116
117  public:
118    /** Overall fetch status. Used to determine if the CPU can
119     * deschedule itsef due to a lack of activity.
120     */
121    enum FetchStatus {
122        Active,
123        Inactive
124    };
125
126    /** Individual thread status. */
127    enum ThreadStatus {
128        Running,
129        Idle,
130        Squashing,
131        Blocked,
132        Fetching,
133        TrapPending,
134        QuiescePending,
135        SwitchOut,
136        IcacheWaitResponse,
137        IcacheWaitRetry,
138        IcacheAccessComplete
139    };
140
141    /** Fetching Policy, Add new policies here.*/
142    enum FetchPriority {
143        SingleThread,
144        RoundRobin,
145        Branch,
146        IQ,
147        LSQ
148    };
149
150  private:
151    /** Fetch status. */
152    FetchStatus _status;
153
154    /** Per-thread status. */
155    ThreadStatus fetchStatus[Impl::MaxThreads];
156
157    /** Fetch policy. */
158    FetchPriority fetchPolicy;
159
160    /** List that has the threads organized by priority. */
161    std::list<ThreadID> priorityList;
162
163  public:
164    /** DefaultFetch constructor. */
165    DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params);
166
167    /** Returns the name of fetch. */
168    std::string name() const;
169
170    /** Registers statistics. */
171    void regStats();
172
173    /** Returns the icache port. */
174    Port *getIcachePort() { return icachePort; }
175
176    /** Sets the main backwards communication time buffer pointer. */
177    void setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer);
178
179    /** Sets pointer to list of active threads. */
180    void setActiveThreads(std::list<ThreadID> *at_ptr);
181
182    /** Sets pointer to time buffer used to communicate to the next stage. */
183    void setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr);
184
185    /** Initialize stage. */
186    void initStage();
187
188    /** Tells the fetch stage that the Icache is set. */
189    void setIcache();
190
191    /** Processes cache completion event. */
192    void processCacheCompletion(PacketPtr pkt);
193
194    /** Begins the drain of the fetch stage. */
195    bool drain();
196
197    /** Resumes execution after a drain. */
198    void resume();
199
200    /** Tells fetch stage to prepare to be switched out. */
201    void switchOut();
202
203    /** Takes over from another CPU's thread. */
204    void takeOverFrom();
205
206    /** Checks if the fetch stage is switched out. */
207    bool isSwitchedOut() { return switchedOut; }
208
209    /** Tells fetch to wake up from a quiesce instruction. */
210    void wakeFromQuiesce();
211
212  private:
213    /** Changes the status of this stage to active, and indicates this
214     * to the CPU.
215     */
216    inline void switchToActive();
217
218    /** Changes the status of this stage to inactive, and indicates
219     * this to the CPU.
220     */
221    inline void switchToInactive();
222
223    /**
224     * Looks up in the branch predictor to see if the next PC should be
225     * either next PC+=MachInst or a branch target.
226     * @param next_PC Next PC variable passed in by reference.  It is
227     * expected to be set to the current PC; it will be updated with what
228     * the next PC will be.
229     * @param next_NPC Used for ISAs which use delay slots.
230     * @return Whether or not a branch was predicted as taken.
231     */
232    bool lookupAndUpdateNextPC(DynInstPtr &inst, TheISA::PCState &pc);
233
234    /**
235     * Fetches the cache line that contains fetch_PC.  Returns any
236     * fault that happened.  Puts the data into the class variable
237     * cacheData.
238     * @param vaddr The memory address that is being fetched from.
239     * @param ret_fault The fault reference that will be set to the result of
240     * the icache access.
241     * @param tid Thread id.
242     * @param pc The actual PC of the current instruction.
243     * @return Any fault that occured.
244     */
245    bool fetchCacheLine(Addr vaddr, Fault &ret_fault, ThreadID tid, Addr pc);
246
247
248    /** Check if an interrupt is pending and that we need to handle
249     */
250    bool
251    checkInterrupt(Addr pc)
252    {
253        return (interruptPending && (THE_ISA != ALPHA_ISA || !(pc & 0x3)));
254    }
255
256    /** Squashes a specific thread and resets the PC. */
257    inline void doSquash(const TheISA::PCState &newPC, ThreadID tid);
258
259    /** Squashes a specific thread and resets the PC. Also tells the CPU to
260     * remove any instructions between fetch and decode that should be sqaushed.
261     */
262    void squashFromDecode(const TheISA::PCState &newPC,
263                          const InstSeqNum &seq_num, ThreadID tid);
264
265    /** Checks if a thread is stalled. */
266    bool checkStall(ThreadID tid) const;
267
268    /** Updates overall fetch stage status; to be called at the end of each
269     * cycle. */
270    FetchStatus updateFetchStatus();
271
272  public:
273    /** Squashes a specific thread and resets the PC. Also tells the CPU to
274     * remove any instructions that are not in the ROB. The source of this
275     * squash should be the commit stage.
276     */
277    void squash(const TheISA::PCState &newPC,
278                const InstSeqNum &seq_num, ThreadID tid);
279
280    /** Ticks the fetch stage, processing all inputs signals and fetching
281     * as many instructions as possible.
282     */
283    void tick();
284
285    /** Checks all input signals and updates the status as necessary.
286     *  @return: Returns if the status has changed due to input signals.
287     */
288    bool checkSignalsAndUpdate(ThreadID tid);
289
290    /** Does the actual fetching of instructions and passing them on to the
291     * next stage.
292     * @param status_change fetch() sets this variable if there was a status
293     * change (ie switching to IcacheMissStall).
294     */
295    void fetch(bool &status_change);
296
297    /** Align a PC to the start of an I-cache block. */
298    Addr icacheBlockAlignPC(Addr addr)
299    {
300        return (addr & ~(cacheBlkMask));
301    }
302
303  private:
304    DynInstPtr buildInst(ThreadID tid, StaticInstPtr staticInst,
305                         StaticInstPtr curMacroop, TheISA::PCState thisPC,
306                         TheISA::PCState nextPC, bool trace);
307
308    /** Handles retrying the fetch access. */
309    void recvRetry();
310
311    /** Returns the appropriate thread to fetch, given the fetch policy. */
312    ThreadID getFetchingThread(FetchPriority &fetch_priority);
313
314    /** Returns the appropriate thread to fetch using a round robin policy. */
315    ThreadID roundRobin();
316
317    /** Returns the appropriate thread to fetch using the IQ count policy. */
318    ThreadID iqCount();
319
320    /** Returns the appropriate thread to fetch using the LSQ count policy. */
321    ThreadID lsqCount();
322
323    /** Returns the appropriate thread to fetch using the branch count
324     * policy. */
325    ThreadID branchCount();
326
327  private:
328    /** Pointer to the O3CPU. */
329    O3CPU *cpu;
330
331    /** Time buffer interface. */
332    TimeBuffer<TimeStruct> *timeBuffer;
333
334    /** Wire to get decode's information from backwards time buffer. */
335    typename TimeBuffer<TimeStruct>::wire fromDecode;
336
337    /** Wire to get rename's information from backwards time buffer. */
338    typename TimeBuffer<TimeStruct>::wire fromRename;
339
340    /** Wire to get iew's information from backwards time buffer. */
341    typename TimeBuffer<TimeStruct>::wire fromIEW;
342
343    /** Wire to get commit's information from backwards time buffer. */
344    typename TimeBuffer<TimeStruct>::wire fromCommit;
345
346    /** Internal fetch instruction queue. */
347    TimeBuffer<FetchStruct> *fetchQueue;
348
349    //Might be annoying how this name is different than the queue.
350    /** Wire used to write any information heading to decode. */
351    typename TimeBuffer<FetchStruct>::wire toDecode;
352
353    /** Icache interface. */
354    IcachePort *icachePort;
355
356    /** BPredUnit. */
357    BPredUnit branchPred;
358
359    /** Predecoder. */
360    TheISA::Predecoder predecoder;
361
362    TheISA::PCState pc[Impl::MaxThreads];
363
364    Addr fetchOffset[Impl::MaxThreads];
365
366    StaticInstPtr macroop[Impl::MaxThreads];
367
368    /** Memory request used to access cache. */
369    RequestPtr memReq[Impl::MaxThreads];
370
371    /** Variable that tracks if fetch has written to the time buffer this
372     * cycle. Used to tell CPU if there is activity this cycle.
373     */
374    bool wroteToTimeBuffer;
375
376    /** Tracks how many instructions has been fetched this cycle. */
377    int numInst;
378
379    /** Source of possible stalls. */
380    struct Stalls {
381        bool decode;
382        bool rename;
383        bool iew;
384        bool commit;
385    };
386
387    /** Tracks which stages are telling fetch to stall. */
388    Stalls stalls[Impl::MaxThreads];
389
390    /** Decode to fetch delay, in ticks. */
391    unsigned decodeToFetchDelay;
392
393    /** Rename to fetch delay, in ticks. */
394    unsigned renameToFetchDelay;
395
396    /** IEW to fetch delay, in ticks. */
397    unsigned iewToFetchDelay;
398
399    /** Commit to fetch delay, in ticks. */
400    unsigned commitToFetchDelay;
401
402    /** The width of fetch in instructions. */
403    unsigned fetchWidth;
404
405    /** Is the cache blocked?  If so no threads can access it. */
406    bool cacheBlocked;
407
408    /** The packet that is waiting to be retried. */
409    PacketPtr retryPkt;
410
411    /** The thread that is waiting on the cache to tell fetch to retry. */
412    ThreadID retryTid;
413
414    /** Cache block size. */
415    int cacheBlkSize;
416
417    /** Mask to get a cache block's address. */
418    Addr cacheBlkMask;
419
420    /** The cache line being fetched. */
421    uint8_t *cacheData[Impl::MaxThreads];
422
423    /** The PC of the cacheline that has been loaded. */
424    Addr cacheDataPC[Impl::MaxThreads];
425
426    /** Whether or not the cache data is valid. */
427    bool cacheDataValid[Impl::MaxThreads];
428
429    /** Size of instructions. */
430    int instSize;
431
432    /** Icache stall statistics. */
433    Counter lastIcacheStall[Impl::MaxThreads];
434
435    /** List of Active Threads */
436    std::list<ThreadID> *activeThreads;
437
438    /** Number of threads. */
439    ThreadID numThreads;
440
441    /** Number of threads that are actively fetching. */
442    ThreadID numFetchingThreads;
443
444    /** Thread ID being fetched. */
445    ThreadID threadFetched;
446
447    /** Checks if there is an interrupt pending.  If there is, fetch
448     * must stop once it is not fetching PAL instructions.
449     */
450    bool interruptPending;
451
452    /** Is there a drain pending. */
453    bool drainPending;
454
455    /** Records if fetch is switched out. */
456    bool switchedOut;
457
458    // @todo: Consider making these vectors and tracking on a per thread basis.
459    /** Stat for total number of cycles stalled due to an icache miss. */
460    Stats::Scalar icacheStallCycles;
461    /** Stat for total number of fetched instructions. */
462    Stats::Scalar fetchedInsts;
463    /** Total number of fetched branches. */
464    Stats::Scalar fetchedBranches;
465    /** Stat for total number of predicted branches. */
466    Stats::Scalar predictedBranches;
467    /** Stat for total number of cycles spent fetching. */
468    Stats::Scalar fetchCycles;
469    /** Stat for total number of cycles spent squashing. */
470    Stats::Scalar fetchSquashCycles;
471    /** Stat for total number of cycles spent blocked due to other stages in
472     * the pipeline.
473     */
474    Stats::Scalar fetchIdleCycles;
475    /** Total number of cycles spent blocked. */
476    Stats::Scalar fetchBlockedCycles;
477    /** Total number of cycles spent in any other state. */
478    Stats::Scalar fetchMiscStallCycles;
479    /** Stat for total number of fetched cache lines. */
480    Stats::Scalar fetchedCacheLines;
481    /** Total number of outstanding icache accesses that were dropped
482     * due to a squash.
483     */
484    Stats::Scalar fetchIcacheSquashes;
485    /** Distribution of number of instructions fetched each cycle. */
486    Stats::Distribution fetchNisnDist;
487    /** Rate of how often fetch was idle. */
488    Stats::Formula idleRate;
489    /** Number of branch fetches per cycle. */
490    Stats::Formula branchRate;
491    /** Number of instruction fetched per cycle. */
492    Stats::Formula fetchRate;
493};
494
495#endif //__CPU_O3_FETCH_HH__
496