iew.hh revision 8809:bb10807da889
1/*
2 * Copyright (c) 2010 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 initStage();
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    /** Drains IEW stage. */
154    bool drain();
155
156    /** Resumes execution after a drain. */
157    void resume();
158
159    /** Completes switch out of IEW stage. */
160    void switchOut();
161
162    /** Takes over from another CPU's thread. */
163    void takeOverFrom();
164
165    /** Returns if IEW is switched out. */
166    bool isSwitchedOut() { return switchedOut; }
167
168    /** Squashes instructions in IEW for a specific thread. */
169    void squash(ThreadID tid);
170
171    /** Wakes all dependents of a completed instruction. */
172    void wakeDependents(DynInstPtr &inst);
173
174    /** Tells memory dependence unit that a memory instruction needs to be
175     * rescheduled. It will re-execute once replayMemInst() is called.
176     */
177    void rescheduleMemInst(DynInstPtr &inst);
178
179    /** Re-executes all rescheduled memory instructions. */
180    void replayMemInst(DynInstPtr &inst);
181
182    /** Sends an instruction to commit through the time buffer. */
183    void instToCommit(DynInstPtr &inst);
184
185    /** Inserts unused instructions of a thread into the skid buffer. */
186    void skidInsert(ThreadID tid);
187
188    /** Returns the max of the number of entries in all of the skid buffers. */
189    int skidCount();
190
191    /** Returns if all of the skid buffers are empty. */
192    bool skidsEmpty();
193
194    /** Updates overall IEW status based on all of the stages' statuses. */
195    void updateStatus();
196
197    /** Resets entries of the IQ and the LSQ. */
198    void resetEntries();
199
200    /** Tells the CPU to wakeup if it has descheduled itself due to no
201     * activity. Used mainly by the LdWritebackEvent.
202     */
203    void wakeCPU();
204
205    /** Reports to the CPU that there is activity this cycle. */
206    void activityThisCycle();
207
208    /** Tells CPU that the IEW stage is active and running. */
209    inline void activateStage();
210
211    /** Tells CPU that the IEW stage is inactive and idle. */
212    inline void deactivateStage();
213
214    /** Returns if the LSQ has any stores to writeback. */
215    bool hasStoresToWB() { return ldstQueue.hasStoresToWB(); }
216
217    /** Returns if the LSQ has any stores to writeback. */
218    bool hasStoresToWB(ThreadID tid) { return ldstQueue.hasStoresToWB(tid); }
219
220    void incrWb(InstSeqNum &sn)
221    {
222        if (++wbOutstanding == wbMax)
223            ableToIssue = false;
224        DPRINTF(IEW, "wbOutstanding: %i [sn:%lli]\n", wbOutstanding, sn);
225        assert(wbOutstanding <= wbMax);
226#ifdef DEBUG
227        wbList.insert(sn);
228#endif
229    }
230
231    void decrWb(InstSeqNum &sn)
232    {
233        if (wbOutstanding-- == wbMax)
234            ableToIssue = true;
235        DPRINTF(IEW, "wbOutstanding: %i [sn:%lli]\n", wbOutstanding, sn);
236        assert(wbOutstanding >= 0);
237#ifdef DEBUG
238        assert(wbList.find(sn) != wbList.end());
239        wbList.erase(sn);
240#endif
241    }
242
243#ifdef DEBUG
244    std::set<InstSeqNum> wbList;
245
246    void dumpWb()
247    {
248        std::set<InstSeqNum>::iterator wb_it = wbList.begin();
249        while (wb_it != wbList.end()) {
250            cprintf("[sn:%lli]\n",
251                    (*wb_it));
252            wb_it++;
253        }
254    }
255#endif
256
257    bool canIssue() { return ableToIssue; }
258
259    bool ableToIssue;
260
261    /** Check misprediction  */
262    void checkMisprediction(DynInstPtr &inst);
263
264  private:
265    /** Sends commit proper information for a squash due to a branch
266     * mispredict.
267     */
268    void squashDueToBranch(DynInstPtr &inst, ThreadID tid);
269
270    /** Sends commit proper information for a squash due to a memory order
271     * violation.
272     */
273    void squashDueToMemOrder(DynInstPtr &inst, ThreadID tid);
274
275    /** Sends commit proper information for a squash due to memory becoming
276     * blocked (younger issued instructions must be retried).
277     */
278    void squashDueToMemBlocked(DynInstPtr &inst, ThreadID tid);
279
280    /** Sets Dispatch to blocked, and signals back to other stages to block. */
281    void block(ThreadID tid);
282
283    /** Unblocks Dispatch if the skid buffer is empty, and signals back to
284     * other stages to unblock.
285     */
286    void unblock(ThreadID tid);
287
288    /** Determines proper actions to take given Dispatch's status. */
289    void dispatch(ThreadID tid);
290
291    /** Dispatches instructions to IQ and LSQ. */
292    void dispatchInsts(ThreadID tid);
293
294    /** Executes instructions. In the case of memory operations, it informs the
295     * LSQ to execute the instructions. Also handles any redirects that occur
296     * due to the executed instructions.
297     */
298    void executeInsts();
299
300    /** Writebacks instructions. In our model, the instruction's execute()
301     * function atomically reads registers, executes, and writes registers.
302     * Thus this writeback only wakes up dependent instructions, and informs
303     * the scoreboard of registers becoming ready.
304     */
305    void writebackInsts();
306
307    /** Returns the number of valid, non-squashed instructions coming from
308     * rename to dispatch.
309     */
310    unsigned validInstsFromRename();
311
312    /** Reads the stall signals. */
313    void readStallSignals(ThreadID tid);
314
315    /** Checks if any of the stall conditions are currently true. */
316    bool checkStall(ThreadID tid);
317
318    /** Processes inputs and changes state accordingly. */
319    void checkSignalsAndUpdate(ThreadID tid);
320
321    /** Removes instructions from rename from a thread's instruction list. */
322    void emptyRenameInsts(ThreadID tid);
323
324    /** Sorts instructions coming from rename into lists separated by thread. */
325    void sortInsts();
326
327  public:
328    /** Ticks IEW stage, causing Dispatch, the IQ, the LSQ, Execute, and
329     * Writeback to run for one cycle.
330     */
331    void tick();
332
333  private:
334    /** Updates execution stats based on the instruction. */
335    void updateExeInstStats(DynInstPtr &inst);
336
337    /** Pointer to main time buffer used for backwards communication. */
338    TimeBuffer<TimeStruct> *timeBuffer;
339
340    /** Wire to write information heading to previous stages. */
341    typename TimeBuffer<TimeStruct>::wire toFetch;
342
343    /** Wire to get commit's output from backwards time buffer. */
344    typename TimeBuffer<TimeStruct>::wire fromCommit;
345
346    /** Wire to write information heading to previous stages. */
347    typename TimeBuffer<TimeStruct>::wire toRename;
348
349    /** Rename instruction queue interface. */
350    TimeBuffer<RenameStruct> *renameQueue;
351
352    /** Wire to get rename's output from rename queue. */
353    typename TimeBuffer<RenameStruct>::wire fromRename;
354
355    /** Issue stage queue. */
356    TimeBuffer<IssueStruct> issueToExecQueue;
357
358    /** Wire to read information from the issue stage time queue. */
359    typename TimeBuffer<IssueStruct>::wire fromIssue;
360
361    /**
362     * IEW stage time buffer.  Holds ROB indices of instructions that
363     * can be marked as completed.
364     */
365    TimeBuffer<IEWStruct> *iewQueue;
366
367    /** Wire to write infromation heading to commit. */
368    typename TimeBuffer<IEWStruct>::wire toCommit;
369
370    /** Queue of all instructions coming from rename this cycle. */
371    std::queue<DynInstPtr> insts[Impl::MaxThreads];
372
373    /** Skid buffer between rename and IEW. */
374    std::queue<DynInstPtr> skidBuffer[Impl::MaxThreads];
375
376    /** Scoreboard pointer. */
377    Scoreboard* scoreboard;
378
379  private:
380    /** CPU pointer. */
381    O3CPU *cpu;
382
383    /** Records if IEW has written to the time buffer this cycle, so that the
384     * CPU can deschedule itself if there is no activity.
385     */
386    bool wroteToTimeBuffer;
387
388    /** Source of possible stalls. */
389    struct Stalls {
390        bool commit;
391    };
392
393    /** Stages that are telling IEW to stall. */
394    Stalls stalls[Impl::MaxThreads];
395
396    /** Debug function to print instructions that are issued this cycle. */
397    void printAvailableInsts();
398
399  public:
400    /** Instruction queue. */
401    IQ instQueue;
402
403    /** Load / store queue. */
404    LSQ ldstQueue;
405
406    /** Pointer to the functional unit pool. */
407    FUPool *fuPool;
408    /** Records if the LSQ needs to be updated on the next cycle, so that
409     * IEW knows if there will be activity on the next cycle.
410     */
411    bool updateLSQNextCycle;
412
413  private:
414    /** Records if there is a fetch redirect on this cycle for each thread. */
415    bool fetchRedirect[Impl::MaxThreads];
416
417    /** Records if the queues have been changed (inserted or issued insts),
418     * so that IEW knows to broadcast the updated amount of free entries.
419     */
420    bool updatedQueues;
421
422    /** Commit to IEW delay, in ticks. */
423    unsigned commitToIEWDelay;
424
425    /** Rename to IEW delay, in ticks. */
426    unsigned renameToIEWDelay;
427
428    /**
429     * Issue to execute delay, in ticks.  What this actually represents is
430     * the amount of time it takes for an instruction to wake up, be
431     * scheduled, and sent to a FU for execution.
432     */
433    unsigned issueToExecuteDelay;
434
435    /** Width of dispatch, in instructions. */
436    unsigned dispatchWidth;
437
438    /** Width of issue, in instructions. */
439    unsigned issueWidth;
440
441    /** Index into queue of instructions being written back. */
442    unsigned wbNumInst;
443
444    /** Cycle number within the queue of instructions being written back.
445     * Used in case there are too many instructions writing back at the current
446     * cycle and writesbacks need to be scheduled for the future. See comments
447     * in instToCommit().
448     */
449    unsigned wbCycle;
450
451    /** Number of instructions in flight that will writeback. */
452
453    /** Number of instructions in flight that will writeback. */
454    int wbOutstanding;
455
456    /** Writeback width. */
457    unsigned wbWidth;
458
459    /** Writeback width * writeback depth, where writeback depth is
460     * the number of cycles of writing back instructions that can be
461     * buffered. */
462    unsigned wbMax;
463
464    /** Number of active threads. */
465    ThreadID numThreads;
466
467    /** Pointer to list of active threads. */
468    std::list<ThreadID> *activeThreads;
469
470    /** Maximum size of the skid buffer. */
471    unsigned skidBufferMax;
472
473    /** Is this stage switched out. */
474    bool switchedOut;
475
476    /** Stat for total number of idle cycles. */
477    Stats::Scalar iewIdleCycles;
478    /** Stat for total number of squashing cycles. */
479    Stats::Scalar iewSquashCycles;
480    /** Stat for total number of blocking cycles. */
481    Stats::Scalar iewBlockCycles;
482    /** Stat for total number of unblocking cycles. */
483    Stats::Scalar iewUnblockCycles;
484    /** Stat for total number of instructions dispatched. */
485    Stats::Scalar iewDispatchedInsts;
486    /** Stat for total number of squashed instructions dispatch skips. */
487    Stats::Scalar iewDispSquashedInsts;
488    /** Stat for total number of dispatched load instructions. */
489    Stats::Scalar iewDispLoadInsts;
490    /** Stat for total number of dispatched store instructions. */
491    Stats::Scalar iewDispStoreInsts;
492    /** Stat for total number of dispatched non speculative instructions. */
493    Stats::Scalar iewDispNonSpecInsts;
494    /** Stat for number of times the IQ becomes full. */
495    Stats::Scalar iewIQFullEvents;
496    /** Stat for number of times the LSQ becomes full. */
497    Stats::Scalar iewLSQFullEvents;
498    /** Stat for total number of memory ordering violation events. */
499    Stats::Scalar memOrderViolationEvents;
500    /** Stat for total number of incorrect predicted taken branches. */
501    Stats::Scalar predictedTakenIncorrect;
502    /** Stat for total number of incorrect predicted not taken branches. */
503    Stats::Scalar predictedNotTakenIncorrect;
504    /** Stat for total number of mispredicted branches detected at execute. */
505    Stats::Formula branchMispredicts;
506
507    /** Stat for total number of executed instructions. */
508    Stats::Scalar iewExecutedInsts;
509    /** Stat for total number of executed load instructions. */
510    Stats::Vector iewExecLoadInsts;
511    /** Stat for total number of executed store instructions. */
512//    Stats::Scalar iewExecStoreInsts;
513    /** Stat for total number of squashed instructions skipped at execute. */
514    Stats::Scalar iewExecSquashedInsts;
515    /** Number of executed software prefetches. */
516    Stats::Vector iewExecutedSwp;
517    /** Number of executed nops. */
518    Stats::Vector iewExecutedNop;
519    /** Number of executed meomory references. */
520    Stats::Vector iewExecutedRefs;
521    /** Number of executed branches. */
522    Stats::Vector iewExecutedBranches;
523    /** Number of executed store instructions. */
524    Stats::Formula iewExecStoreInsts;
525    /** Number of instructions executed per cycle. */
526    Stats::Formula iewExecRate;
527
528    /** Number of instructions sent to commit. */
529    Stats::Vector iewInstsToCommit;
530    /** Number of instructions that writeback. */
531    Stats::Vector writebackCount;
532    /** Number of instructions that wake consumers. */
533    Stats::Vector producerInst;
534    /** Number of instructions that wake up from producers. */
535    Stats::Vector consumerInst;
536    /** Number of instructions that were delayed in writing back due
537     * to resource contention.
538     */
539    Stats::Vector wbPenalized;
540    /** Number of instructions per cycle written back. */
541    Stats::Formula wbRate;
542    /** Average number of woken instructions per writeback. */
543    Stats::Formula wbFanout;
544    /** Number of instructions per cycle delayed in writing back . */
545    Stats::Formula wbPenalizedRate;
546};
547
548#endif // __CPU_O3_IEW_HH__
549