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