iew.hh revision 2871:7ed5c9ef3eb6
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 */
30
31#ifndef __CPU_O3_IEW_HH__
32#define __CPU_O3_IEW_HH__
33
34#include <queue>
35
36#include "base/statistics.hh"
37#include "base/timebuf.hh"
38#include "config/full_system.hh"
39#include "cpu/o3/comm.hh"
40#include "cpu/o3/scoreboard.hh"
41#include "cpu/o3/lsq.hh"
42
43class FUPool;
44
45/**
46 * DefaultIEW handles both single threaded and SMT IEW
47 * (issue/execute/writeback).  It handles the dispatching of
48 * instructions to the LSQ/IQ as part of the issue stage, and has the
49 * IQ try to issue instructions each cycle. The execute latency is
50 * actually tied into the issue latency to allow the IQ to be able to
51 * do back-to-back scheduling without having to speculatively schedule
52 * instructions. This happens by having the IQ have access to the
53 * functional units, and the IQ gets the execution latencies from the
54 * FUs when it issues instructions. Instructions reach the execute
55 * stage on the last cycle of their execution, which is when the IQ
56 * knows to wake up any dependent instructions, allowing back to back
57 * scheduling. The execute portion of IEW separates memory
58 * instructions from non-memory instructions, either telling the LSQ
59 * to execute the instruction, or executing the instruction directly.
60 * The writeback portion of IEW completes the instructions by waking
61 * up any dependents, and marking the register ready on the
62 * scoreboard.
63 */
64template<class Impl>
65class DefaultIEW
66{
67  private:
68    //Typedefs from Impl
69    typedef typename Impl::CPUPol CPUPol;
70    typedef typename Impl::DynInstPtr DynInstPtr;
71    typedef typename Impl::O3CPU O3CPU;
72    typedef typename Impl::Params Params;
73
74    typedef typename CPUPol::IQ IQ;
75    typedef typename CPUPol::RenameMap RenameMap;
76    typedef typename CPUPol::LSQ LSQ;
77
78    typedef typename CPUPol::TimeStruct TimeStruct;
79    typedef typename CPUPol::IEWStruct IEWStruct;
80    typedef typename CPUPol::RenameStruct RenameStruct;
81    typedef typename CPUPol::IssueStruct IssueStruct;
82
83    friend class Impl::O3CPU;
84    friend class CPUPol::IQ;
85
86  public:
87    /** Overall IEW stage status. Used to determine if the CPU can
88     * deschedule itself due to a lack of activity.
89     */
90    enum Status {
91        Active,
92        Inactive
93    };
94
95    /** Status for Issue, Execute, and Writeback stages. */
96    enum StageStatus {
97        Running,
98        Blocked,
99        Idle,
100        StartSquash,
101        Squashing,
102        Unblocking
103    };
104
105  private:
106    /** Overall stage status. */
107    Status _status;
108    /** Dispatch status. */
109    StageStatus dispatchStatus[Impl::MaxThreads];
110    /** Execute status. */
111    StageStatus exeStatus;
112    /** Writeback status. */
113    StageStatus wbStatus;
114
115  public:
116    /** Constructs a DefaultIEW with the given parameters. */
117    DefaultIEW(Params *params);
118
119    /** Returns the name of the DefaultIEW stage. */
120    std::string name() const;
121
122    /** Registers statistics. */
123    void regStats();
124
125    /** Initializes stage; sends back the number of free IQ and LSQ entries. */
126    void initStage();
127
128    /** Returns the dcache port. */
129    Port *getDcachePort() { return ldstQueue.getDcachePort(); }
130
131    /** Sets CPU pointer for IEW, IQ, and LSQ. */
132    void setCPU(O3CPU *cpu_ptr);
133
134    /** Sets main time buffer used for backwards communication. */
135    void setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr);
136
137    /** Sets time buffer for getting instructions coming from rename. */
138    void setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr);
139
140    /** Sets time buffer to pass on instructions to commit. */
141    void setIEWQueue(TimeBuffer<IEWStruct> *iq_ptr);
142
143    /** Sets pointer to list of active threads. */
144    void setActiveThreads(std::list<unsigned> *at_ptr);
145
146    /** Sets pointer to the scoreboard. */
147    void setScoreboard(Scoreboard *sb_ptr);
148
149    /** Drains IEW stage. */
150    bool drain();
151
152    /** Resumes execution after a drain. */
153    void resume();
154
155    /** Completes switch out of IEW stage. */
156    void switchOut();
157
158    /** Takes over from another CPU's thread. */
159    void takeOverFrom();
160
161    /** Returns if IEW is switched out. */
162    bool isSwitchedOut() { return switchedOut; }
163
164    /** Squashes instructions in IEW for a specific thread. */
165    void squash(unsigned tid);
166
167    /** Wakes all dependents of a completed instruction. */
168    void wakeDependents(DynInstPtr &inst);
169
170    /** Tells memory dependence unit that a memory instruction needs to be
171     * rescheduled. It will re-execute once replayMemInst() is called.
172     */
173    void rescheduleMemInst(DynInstPtr &inst);
174
175    /** Re-executes all rescheduled memory instructions. */
176    void replayMemInst(DynInstPtr &inst);
177
178    /** Sends an instruction to commit through the time buffer. */
179    void instToCommit(DynInstPtr &inst);
180
181    /** Inserts unused instructions of a thread into the skid buffer. */
182    void skidInsert(unsigned tid);
183
184    /** Returns the max of the number of entries in all of the skid buffers. */
185    int skidCount();
186
187    /** Returns if all of the skid buffers are empty. */
188    bool skidsEmpty();
189
190    /** Updates overall IEW status based on all of the stages' statuses. */
191    void updateStatus();
192
193    /** Resets entries of the IQ and the LSQ. */
194    void resetEntries();
195
196    /** Tells the CPU to wakeup if it has descheduled itself due to no
197     * activity. Used mainly by the LdWritebackEvent.
198     */
199    void wakeCPU();
200
201    /** Reports to the CPU that there is activity this cycle. */
202    void activityThisCycle();
203
204    /** Tells CPU that the IEW stage is active and running. */
205    inline void activateStage();
206
207    /** Tells CPU that the IEW stage is inactive and idle. */
208    inline void deactivateStage();
209
210    /** Returns if the LSQ has any stores to writeback. */
211    bool hasStoresToWB() { return ldstQueue.hasStoresToWB(); }
212
213    void incrWb(InstSeqNum &sn)
214    {
215        if (++wbOutstanding == wbMax)
216            ableToIssue = false;
217        DPRINTF(IEW, "wbOutstanding: %i\n", wbOutstanding);
218#if DEBUG
219        wbList.insert(sn);
220#endif
221    }
222
223    void decrWb(InstSeqNum &sn)
224    {
225        if (wbOutstanding-- == wbMax)
226            ableToIssue = true;
227        DPRINTF(IEW, "wbOutstanding: %i\n", wbOutstanding);
228#if DEBUG
229        assert(wbList.find(sn) != wbList.end());
230        wbList.erase(sn);
231#endif
232    }
233
234#if DEBUG
235    std::set<InstSeqNum> wbList;
236
237    void dumpWb()
238    {
239        std::set<InstSeqNum>::iterator wb_it = wbList.begin();
240        while (wb_it != wbList.end()) {
241            cprintf("[sn:%lli]\n",
242                    (*wb_it));
243            wb_it++;
244        }
245    }
246#endif
247
248    bool canIssue() { return ableToIssue; }
249
250    bool ableToIssue;
251
252  private:
253    /** Sends commit proper information for a squash due to a branch
254     * mispredict.
255     */
256    void squashDueToBranch(DynInstPtr &inst, unsigned thread_id);
257
258    /** Sends commit proper information for a squash due to a memory order
259     * violation.
260     */
261    void squashDueToMemOrder(DynInstPtr &inst, unsigned thread_id);
262
263    /** Sends commit proper information for a squash due to memory becoming
264     * blocked (younger issued instructions must be retried).
265     */
266    void squashDueToMemBlocked(DynInstPtr &inst, unsigned thread_id);
267
268    /** Sets Dispatch to blocked, and signals back to other stages to block. */
269    void block(unsigned thread_id);
270
271    /** Unblocks Dispatch if the skid buffer is empty, and signals back to
272     * other stages to unblock.
273     */
274    void unblock(unsigned thread_id);
275
276    /** Determines proper actions to take given Dispatch's status. */
277    void dispatch(unsigned tid);
278
279    /** Dispatches instructions to IQ and LSQ. */
280    void dispatchInsts(unsigned tid);
281
282    /** Executes instructions. In the case of memory operations, it informs the
283     * LSQ to execute the instructions. Also handles any redirects that occur
284     * due to the executed instructions.
285     */
286    void executeInsts();
287
288    /** Writebacks instructions. In our model, the instruction's execute()
289     * function atomically reads registers, executes, and writes registers.
290     * Thus this writeback only wakes up dependent instructions, and informs
291     * the scoreboard of registers becoming ready.
292     */
293    void writebackInsts();
294
295    /** Returns the number of valid, non-squashed instructions coming from
296     * rename to dispatch.
297     */
298    unsigned validInstsFromRename();
299
300    /** Reads the stall signals. */
301    void readStallSignals(unsigned tid);
302
303    /** Checks if any of the stall conditions are currently true. */
304    bool checkStall(unsigned tid);
305
306    /** Processes inputs and changes state accordingly. */
307    void checkSignalsAndUpdate(unsigned tid);
308
309    /** Removes instructions from rename from a thread's instruction list. */
310    void emptyRenameInsts(unsigned tid);
311
312    /** Sorts instructions coming from rename into lists separated by thread. */
313    void sortInsts();
314
315  public:
316    /** Ticks IEW stage, causing Dispatch, the IQ, the LSQ, Execute, and
317     * Writeback to run for one cycle.
318     */
319    void tick();
320
321  private:
322    /** Updates execution stats based on the instruction. */
323    void updateExeInstStats(DynInstPtr &inst);
324
325    /** Pointer to main time buffer used for backwards communication. */
326    TimeBuffer<TimeStruct> *timeBuffer;
327
328    /** Wire to write information heading to previous stages. */
329    typename TimeBuffer<TimeStruct>::wire toFetch;
330
331    /** Wire to get commit's output from backwards time buffer. */
332    typename TimeBuffer<TimeStruct>::wire fromCommit;
333
334    /** Wire to write information heading to previous stages. */
335    typename TimeBuffer<TimeStruct>::wire toRename;
336
337    /** Rename instruction queue interface. */
338    TimeBuffer<RenameStruct> *renameQueue;
339
340    /** Wire to get rename's output from rename queue. */
341    typename TimeBuffer<RenameStruct>::wire fromRename;
342
343    /** Issue stage queue. */
344    TimeBuffer<IssueStruct> issueToExecQueue;
345
346    /** Wire to read information from the issue stage time queue. */
347    typename TimeBuffer<IssueStruct>::wire fromIssue;
348
349    /**
350     * IEW stage time buffer.  Holds ROB indices of instructions that
351     * can be marked as completed.
352     */
353    TimeBuffer<IEWStruct> *iewQueue;
354
355    /** Wire to write infromation heading to commit. */
356    typename TimeBuffer<IEWStruct>::wire toCommit;
357
358    /** Queue of all instructions coming from rename this cycle. */
359    std::queue<DynInstPtr> insts[Impl::MaxThreads];
360
361    /** Skid buffer between rename and IEW. */
362    std::queue<DynInstPtr> skidBuffer[Impl::MaxThreads];
363
364    /** Scoreboard pointer. */
365    Scoreboard* scoreboard;
366
367  public:
368    /** Instruction queue. */
369    IQ instQueue;
370
371    /** Load / store queue. */
372    LSQ ldstQueue;
373
374    /** Pointer to the functional unit pool. */
375    FUPool *fuPool;
376
377  private:
378    /** CPU pointer. */
379    O3CPU *cpu;
380
381    /** Records if IEW has written to the time buffer this cycle, so that the
382     * CPU can deschedule itself if there is no activity.
383     */
384    bool wroteToTimeBuffer;
385
386    /** Source of possible stalls. */
387    struct Stalls {
388        bool commit;
389    };
390
391    /** Stages that are telling IEW to stall. */
392    Stalls stalls[Impl::MaxThreads];
393
394    /** Debug function to print instructions that are issued this cycle. */
395    void printAvailableInsts();
396
397  public:
398    /** Records if the LSQ needs to be updated on the next cycle, so that
399     * IEW knows if there will be activity on the next cycle.
400     */
401    bool updateLSQNextCycle;
402
403  private:
404    /** Records if there is a fetch redirect on this cycle for each thread. */
405    bool fetchRedirect[Impl::MaxThreads];
406
407    /** Used to track if all instructions have been dispatched this cycle.
408     * If they have not, then blocking must have occurred, and the instructions
409     * would already be added to the skid buffer.
410     * @todo: Fix this hack.
411     */
412    bool dispatchedAllInsts;
413
414    /** Records if the queues have been changed (inserted or issued insts),
415     * so that IEW knows to broadcast the updated amount of free entries.
416     */
417    bool updatedQueues;
418
419    /** Commit to IEW delay, in ticks. */
420    unsigned commitToIEWDelay;
421
422    /** Rename to IEW delay, in ticks. */
423    unsigned renameToIEWDelay;
424
425    /**
426     * Issue to execute delay, in ticks.  What this actually represents is
427     * the amount of time it takes for an instruction to wake up, be
428     * scheduled, and sent to a FU for execution.
429     */
430    unsigned issueToExecuteDelay;
431
432    /** Width of dispatch, in instructions. */
433    unsigned dispatchWidth;
434
435    /** Width of issue, in instructions. */
436    unsigned issueWidth;
437
438    /** Index into queue of instructions being written back. */
439    unsigned wbNumInst;
440
441    /** Cycle number within the queue of instructions being written back.
442     * Used in case there are too many instructions writing back at the current
443     * cycle and writesbacks need to be scheduled for the future. See comments
444     * in instToCommit().
445     */
446    unsigned wbCycle;
447
448    /** Number of instructions in flight that will writeback. */
449    unsigned wbOutstanding;
450
451    /** Writeback width. */
452    unsigned wbWidth;
453
454    /** Writeback width * writeback depth, where writeback depth is
455     * the number of cycles of writing back instructions that can be
456     * buffered. */
457    unsigned wbMax;
458
459    /** Number of active threads. */
460    unsigned numThreads;
461
462    /** Pointer to list of active threads. */
463    std::list<unsigned> *activeThreads;
464
465    /** Maximum size of the skid buffer. */
466    unsigned skidBufferMax;
467
468    /** Is this stage switched out. */
469    bool switchedOut;
470
471    /** Stat for total number of idle cycles. */
472    Stats::Scalar<> iewIdleCycles;
473    /** Stat for total number of squashing cycles. */
474    Stats::Scalar<> iewSquashCycles;
475    /** Stat for total number of blocking cycles. */
476    Stats::Scalar<> iewBlockCycles;
477    /** Stat for total number of unblocking cycles. */
478    Stats::Scalar<> iewUnblockCycles;
479    /** Stat for total number of instructions dispatched. */
480    Stats::Scalar<> iewDispatchedInsts;
481    /** Stat for total number of squashed instructions dispatch skips. */
482    Stats::Scalar<> iewDispSquashedInsts;
483    /** Stat for total number of dispatched load instructions. */
484    Stats::Scalar<> iewDispLoadInsts;
485    /** Stat for total number of dispatched store instructions. */
486    Stats::Scalar<> iewDispStoreInsts;
487    /** Stat for total number of dispatched non speculative instructions. */
488    Stats::Scalar<> iewDispNonSpecInsts;
489    /** Stat for number of times the IQ becomes full. */
490    Stats::Scalar<> iewIQFullEvents;
491    /** Stat for number of times the LSQ becomes full. */
492    Stats::Scalar<> iewLSQFullEvents;
493    /** Stat for total number of memory ordering violation events. */
494    Stats::Scalar<> memOrderViolationEvents;
495    /** Stat for total number of incorrect predicted taken branches. */
496    Stats::Scalar<> predictedTakenIncorrect;
497    /** Stat for total number of incorrect predicted not taken branches. */
498    Stats::Scalar<> predictedNotTakenIncorrect;
499    /** Stat for total number of mispredicted branches detected at execute. */
500    Stats::Formula branchMispredicts;
501
502    /** Stat for total number of executed instructions. */
503    Stats::Scalar<> iewExecutedInsts;
504    /** Stat for total number of executed load instructions. */
505    Stats::Vector<> iewExecLoadInsts;
506    /** Stat for total number of squashed instructions skipped at execute. */
507    Stats::Scalar<> iewExecSquashedInsts;
508    /** Number of executed software prefetches. */
509    Stats::Vector<> iewExecutedSwp;
510    /** Number of executed nops. */
511    Stats::Vector<> iewExecutedNop;
512    /** Number of executed meomory references. */
513    Stats::Vector<> iewExecutedRefs;
514    /** Number of executed branches. */
515    Stats::Vector<> iewExecutedBranches;
516    /** Number of executed store instructions. */
517    Stats::Formula iewExecStoreInsts;
518    /** Number of instructions executed per cycle. */
519    Stats::Formula iewExecRate;
520
521    /** Number of instructions sent to commit. */
522    Stats::Vector<> iewInstsToCommit;
523    /** Number of instructions that writeback. */
524    Stats::Vector<> writebackCount;
525    /** Number of instructions that wake consumers. */
526    Stats::Vector<> producerInst;
527    /** Number of instructions that wake up from producers. */
528    Stats::Vector<> consumerInst;
529    /** Number of instructions that were delayed in writing back due
530     * to resource contention.
531     */
532    Stats::Vector<> wbPenalized;
533    /** Number of instructions per cycle written back. */
534    Stats::Formula wbRate;
535    /** Average number of woken instructions per writeback. */
536    Stats::Formula wbFanout;
537    /** Number of instructions per cycle delayed in writing back . */
538    Stats::Formula wbPenalizedRate;
539};
540
541#endif // __CPU_O3_IEW_HH__
542