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