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