iew_impl.hh revision 10824:308771bd2647
1/*
2 * Copyright (c) 2010-2013 ARM Limited
3 * Copyright (c) 2013 Advanced Micro Devices, Inc.
4 * All rights reserved.
5 *
6 * The license below extends only to copyright in the software and shall
7 * not be construed as granting a license to any other intellectual
8 * property including but not limited to intellectual property relating
9 * to a hardware implementation of the functionality of the software
10 * licensed hereunder.  You may use the software subject to the license
11 * terms below provided that you ensure that this notice is replicated
12 * unmodified and in its entirety in all distributions of the software,
13 * modified or unmodified, in source code or in binary form.
14 *
15 * Copyright (c) 2004-2006 The Regents of The University of Michigan
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Kevin Lim
42 */
43
44#ifndef __CPU_O3_IEW_IMPL_IMPL_HH__
45#define __CPU_O3_IEW_IMPL_IMPL_HH__
46
47// @todo: Fix the instantaneous communication among all the stages within
48// iew.  There's a clear delay between issue and execute, yet backwards
49// communication happens simultaneously.
50
51#include <queue>
52
53#include "arch/utility.hh"
54#include "config/the_isa.hh"
55#include "cpu/checker/cpu.hh"
56#include "cpu/o3/fu_pool.hh"
57#include "cpu/o3/iew.hh"
58#include "cpu/timebuf.hh"
59#include "debug/Activity.hh"
60#include "debug/Drain.hh"
61#include "debug/IEW.hh"
62#include "debug/O3PipeView.hh"
63#include "params/DerivO3CPU.hh"
64
65using namespace std;
66
67template<class Impl>
68DefaultIEW<Impl>::DefaultIEW(O3CPU *_cpu, DerivO3CPUParams *params)
69    : issueToExecQueue(params->backComSize, params->forwardComSize),
70      cpu(_cpu),
71      instQueue(_cpu, this, params),
72      ldstQueue(_cpu, this, params),
73      fuPool(params->fuPool),
74      commitToIEWDelay(params->commitToIEWDelay),
75      renameToIEWDelay(params->renameToIEWDelay),
76      issueToExecuteDelay(params->issueToExecuteDelay),
77      dispatchWidth(params->dispatchWidth),
78      issueWidth(params->issueWidth),
79      wbWidth(params->wbWidth),
80      numThreads(params->numThreads)
81{
82    if (dispatchWidth > Impl::MaxWidth)
83        fatal("dispatchWidth (%d) is larger than compiled limit (%d),\n"
84             "\tincrease MaxWidth in src/cpu/o3/impl.hh\n",
85             dispatchWidth, static_cast<int>(Impl::MaxWidth));
86    if (issueWidth > Impl::MaxWidth)
87        fatal("issueWidth (%d) is larger than compiled limit (%d),\n"
88             "\tincrease MaxWidth in src/cpu/o3/impl.hh\n",
89             issueWidth, static_cast<int>(Impl::MaxWidth));
90    if (wbWidth > Impl::MaxWidth)
91        fatal("wbWidth (%d) is larger than compiled limit (%d),\n"
92             "\tincrease MaxWidth in src/cpu/o3/impl.hh\n",
93             wbWidth, static_cast<int>(Impl::MaxWidth));
94
95    _status = Active;
96    exeStatus = Running;
97    wbStatus = Idle;
98
99    // Setup wire to read instructions coming from issue.
100    fromIssue = issueToExecQueue.getWire(-issueToExecuteDelay);
101
102    // Instruction queue needs the queue between issue and execute.
103    instQueue.setIssueToExecuteQueue(&issueToExecQueue);
104
105    for (ThreadID tid = 0; tid < numThreads; tid++) {
106        dispatchStatus[tid] = Running;
107        fetchRedirect[tid] = false;
108    }
109
110    updateLSQNextCycle = false;
111
112    skidBufferMax = (renameToIEWDelay + 1) * params->renameWidth;
113}
114
115template <class Impl>
116std::string
117DefaultIEW<Impl>::name() const
118{
119    return cpu->name() + ".iew";
120}
121
122template <class Impl>
123void
124DefaultIEW<Impl>::regProbePoints()
125{
126    ppDispatch = new ProbePointArg<DynInstPtr>(cpu->getProbeManager(), "Dispatch");
127    ppMispredict = new ProbePointArg<DynInstPtr>(cpu->getProbeManager(), "Mispredict");
128}
129
130template <class Impl>
131void
132DefaultIEW<Impl>::regStats()
133{
134    using namespace Stats;
135
136    instQueue.regStats();
137    ldstQueue.regStats();
138
139    iewIdleCycles
140        .name(name() + ".iewIdleCycles")
141        .desc("Number of cycles IEW is idle");
142
143    iewSquashCycles
144        .name(name() + ".iewSquashCycles")
145        .desc("Number of cycles IEW is squashing");
146
147    iewBlockCycles
148        .name(name() + ".iewBlockCycles")
149        .desc("Number of cycles IEW is blocking");
150
151    iewUnblockCycles
152        .name(name() + ".iewUnblockCycles")
153        .desc("Number of cycles IEW is unblocking");
154
155    iewDispatchedInsts
156        .name(name() + ".iewDispatchedInsts")
157        .desc("Number of instructions dispatched to IQ");
158
159    iewDispSquashedInsts
160        .name(name() + ".iewDispSquashedInsts")
161        .desc("Number of squashed instructions skipped by dispatch");
162
163    iewDispLoadInsts
164        .name(name() + ".iewDispLoadInsts")
165        .desc("Number of dispatched load instructions");
166
167    iewDispStoreInsts
168        .name(name() + ".iewDispStoreInsts")
169        .desc("Number of dispatched store instructions");
170
171    iewDispNonSpecInsts
172        .name(name() + ".iewDispNonSpecInsts")
173        .desc("Number of dispatched non-speculative instructions");
174
175    iewIQFullEvents
176        .name(name() + ".iewIQFullEvents")
177        .desc("Number of times the IQ has become full, causing a stall");
178
179    iewLSQFullEvents
180        .name(name() + ".iewLSQFullEvents")
181        .desc("Number of times the LSQ has become full, causing a stall");
182
183    memOrderViolationEvents
184        .name(name() + ".memOrderViolationEvents")
185        .desc("Number of memory order violations");
186
187    predictedTakenIncorrect
188        .name(name() + ".predictedTakenIncorrect")
189        .desc("Number of branches that were predicted taken incorrectly");
190
191    predictedNotTakenIncorrect
192        .name(name() + ".predictedNotTakenIncorrect")
193        .desc("Number of branches that were predicted not taken incorrectly");
194
195    branchMispredicts
196        .name(name() + ".branchMispredicts")
197        .desc("Number of branch mispredicts detected at execute");
198
199    branchMispredicts = predictedTakenIncorrect + predictedNotTakenIncorrect;
200
201    iewExecutedInsts
202        .name(name() + ".iewExecutedInsts")
203        .desc("Number of executed instructions");
204
205    iewExecLoadInsts
206        .init(cpu->numThreads)
207        .name(name() + ".iewExecLoadInsts")
208        .desc("Number of load instructions executed")
209        .flags(total);
210
211    iewExecSquashedInsts
212        .name(name() + ".iewExecSquashedInsts")
213        .desc("Number of squashed instructions skipped in execute");
214
215    iewExecutedSwp
216        .init(cpu->numThreads)
217        .name(name() + ".exec_swp")
218        .desc("number of swp insts executed")
219        .flags(total);
220
221    iewExecutedNop
222        .init(cpu->numThreads)
223        .name(name() + ".exec_nop")
224        .desc("number of nop insts executed")
225        .flags(total);
226
227    iewExecutedRefs
228        .init(cpu->numThreads)
229        .name(name() + ".exec_refs")
230        .desc("number of memory reference insts executed")
231        .flags(total);
232
233    iewExecutedBranches
234        .init(cpu->numThreads)
235        .name(name() + ".exec_branches")
236        .desc("Number of branches executed")
237        .flags(total);
238
239    iewExecStoreInsts
240        .name(name() + ".exec_stores")
241        .desc("Number of stores executed")
242        .flags(total);
243    iewExecStoreInsts = iewExecutedRefs - iewExecLoadInsts;
244
245    iewExecRate
246        .name(name() + ".exec_rate")
247        .desc("Inst execution rate")
248        .flags(total);
249
250    iewExecRate = iewExecutedInsts / cpu->numCycles;
251
252    iewInstsToCommit
253        .init(cpu->numThreads)
254        .name(name() + ".wb_sent")
255        .desc("cumulative count of insts sent to commit")
256        .flags(total);
257
258    writebackCount
259        .init(cpu->numThreads)
260        .name(name() + ".wb_count")
261        .desc("cumulative count of insts written-back")
262        .flags(total);
263
264    producerInst
265        .init(cpu->numThreads)
266        .name(name() + ".wb_producers")
267        .desc("num instructions producing a value")
268        .flags(total);
269
270    consumerInst
271        .init(cpu->numThreads)
272        .name(name() + ".wb_consumers")
273        .desc("num instructions consuming a value")
274        .flags(total);
275
276    wbPenalized
277        .init(cpu->numThreads)
278        .name(name() + ".wb_penalized")
279        .desc("number of instrctions required to write to 'other' IQ")
280        .flags(total);
281
282    wbPenalizedRate
283        .name(name() + ".wb_penalized_rate")
284        .desc ("fraction of instructions written-back that wrote to 'other' IQ")
285        .flags(total);
286
287    wbPenalizedRate = wbPenalized / writebackCount;
288
289    wbFanout
290        .name(name() + ".wb_fanout")
291        .desc("average fanout of values written-back")
292        .flags(total);
293
294    wbFanout = producerInst / consumerInst;
295
296    wbRate
297        .name(name() + ".wb_rate")
298        .desc("insts written-back per cycle")
299        .flags(total);
300    wbRate = writebackCount / cpu->numCycles;
301}
302
303template<class Impl>
304void
305DefaultIEW<Impl>::startupStage()
306{
307    for (ThreadID tid = 0; tid < numThreads; tid++) {
308        toRename->iewInfo[tid].usedIQ = true;
309        toRename->iewInfo[tid].freeIQEntries =
310            instQueue.numFreeEntries(tid);
311
312        toRename->iewInfo[tid].usedLSQ = true;
313        toRename->iewInfo[tid].freeLQEntries = ldstQueue.numFreeLoadEntries(tid);
314        toRename->iewInfo[tid].freeSQEntries = ldstQueue.numFreeStoreEntries(tid);
315    }
316
317    // Initialize the checker's dcache port here
318    if (cpu->checker) {
319        cpu->checker->setDcachePort(&cpu->getDataPort());
320    }
321
322    cpu->activateStage(O3CPU::IEWIdx);
323}
324
325template<class Impl>
326void
327DefaultIEW<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
328{
329    timeBuffer = tb_ptr;
330
331    // Setup wire to read information from time buffer, from commit.
332    fromCommit = timeBuffer->getWire(-commitToIEWDelay);
333
334    // Setup wire to write information back to previous stages.
335    toRename = timeBuffer->getWire(0);
336
337    toFetch = timeBuffer->getWire(0);
338
339    // Instruction queue also needs main time buffer.
340    instQueue.setTimeBuffer(tb_ptr);
341}
342
343template<class Impl>
344void
345DefaultIEW<Impl>::setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr)
346{
347    renameQueue = rq_ptr;
348
349    // Setup wire to read information from rename queue.
350    fromRename = renameQueue->getWire(-renameToIEWDelay);
351}
352
353template<class Impl>
354void
355DefaultIEW<Impl>::setIEWQueue(TimeBuffer<IEWStruct> *iq_ptr)
356{
357    iewQueue = iq_ptr;
358
359    // Setup wire to write instructions to commit.
360    toCommit = iewQueue->getWire(0);
361}
362
363template<class Impl>
364void
365DefaultIEW<Impl>::setActiveThreads(list<ThreadID> *at_ptr)
366{
367    activeThreads = at_ptr;
368
369    ldstQueue.setActiveThreads(at_ptr);
370    instQueue.setActiveThreads(at_ptr);
371}
372
373template<class Impl>
374void
375DefaultIEW<Impl>::setScoreboard(Scoreboard *sb_ptr)
376{
377    scoreboard = sb_ptr;
378}
379
380template <class Impl>
381bool
382DefaultIEW<Impl>::isDrained() const
383{
384    bool drained = ldstQueue.isDrained() && instQueue.isDrained();
385
386    for (ThreadID tid = 0; tid < numThreads; tid++) {
387        if (!insts[tid].empty()) {
388            DPRINTF(Drain, "%i: Insts not empty.\n", tid);
389            drained = false;
390        }
391        if (!skidBuffer[tid].empty()) {
392            DPRINTF(Drain, "%i: Skid buffer not empty.\n", tid);
393            drained = false;
394        }
395    }
396
397    // Also check the FU pool as instructions are "stored" in FU
398    // completion events until they are done and not accounted for
399    // above
400    if (drained && !fuPool->isDrained()) {
401        DPRINTF(Drain, "FU pool still busy.\n");
402        drained = false;
403    }
404
405    return drained;
406}
407
408template <class Impl>
409void
410DefaultIEW<Impl>::drainSanityCheck() const
411{
412    assert(isDrained());
413
414    instQueue.drainSanityCheck();
415    ldstQueue.drainSanityCheck();
416}
417
418template <class Impl>
419void
420DefaultIEW<Impl>::takeOverFrom()
421{
422    // Reset all state.
423    _status = Active;
424    exeStatus = Running;
425    wbStatus = Idle;
426
427    instQueue.takeOverFrom();
428    ldstQueue.takeOverFrom();
429    fuPool->takeOverFrom();
430
431    startupStage();
432    cpu->activityThisCycle();
433
434    for (ThreadID tid = 0; tid < numThreads; tid++) {
435        dispatchStatus[tid] = Running;
436        fetchRedirect[tid] = false;
437    }
438
439    updateLSQNextCycle = false;
440
441    for (int i = 0; i < issueToExecQueue.getSize(); ++i) {
442        issueToExecQueue.advance();
443    }
444}
445
446template<class Impl>
447void
448DefaultIEW<Impl>::squash(ThreadID tid)
449{
450    DPRINTF(IEW, "[tid:%i]: Squashing all instructions.\n", tid);
451
452    // Tell the IQ to start squashing.
453    instQueue.squash(tid);
454
455    // Tell the LDSTQ to start squashing.
456    ldstQueue.squash(fromCommit->commitInfo[tid].doneSeqNum, tid);
457    updatedQueues = true;
458
459    // Clear the skid buffer in case it has any data in it.
460    DPRINTF(IEW, "[tid:%i]: Removing skidbuffer instructions until [sn:%i].\n",
461            tid, fromCommit->commitInfo[tid].doneSeqNum);
462
463    while (!skidBuffer[tid].empty()) {
464        if (skidBuffer[tid].front()->isLoad()) {
465            toRename->iewInfo[tid].dispatchedToLQ++;
466        }
467        if (skidBuffer[tid].front()->isStore()) {
468            toRename->iewInfo[tid].dispatchedToSQ++;
469        }
470
471        toRename->iewInfo[tid].dispatched++;
472
473        skidBuffer[tid].pop();
474    }
475
476    emptyRenameInsts(tid);
477}
478
479template<class Impl>
480void
481DefaultIEW<Impl>::squashDueToBranch(DynInstPtr &inst, ThreadID tid)
482{
483    DPRINTF(IEW, "[tid:%i]: Squashing from a specific instruction, PC: %s "
484            "[sn:%i].\n", tid, inst->pcState(), inst->seqNum);
485
486    if (!toCommit->squash[tid] ||
487            inst->seqNum < toCommit->squashedSeqNum[tid]) {
488        toCommit->squash[tid] = true;
489        toCommit->squashedSeqNum[tid] = inst->seqNum;
490        toCommit->branchTaken[tid] = inst->pcState().branching();
491
492        TheISA::PCState pc = inst->pcState();
493        TheISA::advancePC(pc, inst->staticInst);
494
495        toCommit->pc[tid] = pc;
496        toCommit->mispredictInst[tid] = inst;
497        toCommit->includeSquashInst[tid] = false;
498
499        wroteToTimeBuffer = true;
500    }
501
502}
503
504template<class Impl>
505void
506DefaultIEW<Impl>::squashDueToMemOrder(DynInstPtr &inst, ThreadID tid)
507{
508    DPRINTF(IEW, "[tid:%i]: Memory violation, squashing violator and younger "
509            "insts, PC: %s [sn:%i].\n", tid, inst->pcState(), inst->seqNum);
510    // Need to include inst->seqNum in the following comparison to cover the
511    // corner case when a branch misprediction and a memory violation for the
512    // same instruction (e.g. load PC) are detected in the same cycle.  In this
513    // case the memory violator should take precedence over the branch
514    // misprediction because it requires the violator itself to be included in
515    // the squash.
516    if (!toCommit->squash[tid] ||
517            inst->seqNum <= toCommit->squashedSeqNum[tid]) {
518        toCommit->squash[tid] = true;
519
520        toCommit->squashedSeqNum[tid] = inst->seqNum;
521        toCommit->pc[tid] = inst->pcState();
522        toCommit->mispredictInst[tid] = NULL;
523
524        // Must include the memory violator in the squash.
525        toCommit->includeSquashInst[tid] = true;
526
527        wroteToTimeBuffer = true;
528    }
529}
530
531template<class Impl>
532void
533DefaultIEW<Impl>::block(ThreadID tid)
534{
535    DPRINTF(IEW, "[tid:%u]: Blocking.\n", tid);
536
537    if (dispatchStatus[tid] != Blocked &&
538        dispatchStatus[tid] != Unblocking) {
539        toRename->iewBlock[tid] = true;
540        wroteToTimeBuffer = true;
541    }
542
543    // Add the current inputs to the skid buffer so they can be
544    // reprocessed when this stage unblocks.
545    skidInsert(tid);
546
547    dispatchStatus[tid] = Blocked;
548}
549
550template<class Impl>
551void
552DefaultIEW<Impl>::unblock(ThreadID tid)
553{
554    DPRINTF(IEW, "[tid:%i]: Reading instructions out of the skid "
555            "buffer %u.\n",tid, tid);
556
557    // If the skid bufffer is empty, signal back to previous stages to unblock.
558    // Also switch status to running.
559    if (skidBuffer[tid].empty()) {
560        toRename->iewUnblock[tid] = true;
561        wroteToTimeBuffer = true;
562        DPRINTF(IEW, "[tid:%i]: Done unblocking.\n",tid);
563        dispatchStatus[tid] = Running;
564    }
565}
566
567template<class Impl>
568void
569DefaultIEW<Impl>::wakeDependents(DynInstPtr &inst)
570{
571    instQueue.wakeDependents(inst);
572}
573
574template<class Impl>
575void
576DefaultIEW<Impl>::rescheduleMemInst(DynInstPtr &inst)
577{
578    instQueue.rescheduleMemInst(inst);
579}
580
581template<class Impl>
582void
583DefaultIEW<Impl>::replayMemInst(DynInstPtr &inst)
584{
585    instQueue.replayMemInst(inst);
586}
587
588template<class Impl>
589void
590DefaultIEW<Impl>::blockMemInst(DynInstPtr& inst)
591{
592    instQueue.blockMemInst(inst);
593}
594
595template<class Impl>
596void
597DefaultIEW<Impl>::cacheUnblocked()
598{
599    instQueue.cacheUnblocked();
600}
601
602template<class Impl>
603void
604DefaultIEW<Impl>::instToCommit(DynInstPtr &inst)
605{
606    // This function should not be called after writebackInsts in a
607    // single cycle.  That will cause problems with an instruction
608    // being added to the queue to commit without being processed by
609    // writebackInsts prior to being sent to commit.
610
611    // First check the time slot that this instruction will write
612    // to.  If there are free write ports at the time, then go ahead
613    // and write the instruction to that time.  If there are not,
614    // keep looking back to see where's the first time there's a
615    // free slot.
616    while ((*iewQueue)[wbCycle].insts[wbNumInst]) {
617        ++wbNumInst;
618        if (wbNumInst == wbWidth) {
619            ++wbCycle;
620            wbNumInst = 0;
621        }
622    }
623
624    DPRINTF(IEW, "Current wb cycle: %i, width: %i, numInst: %i\nwbActual:%i\n",
625            wbCycle, wbWidth, wbNumInst, wbCycle * wbWidth + wbNumInst);
626    // Add finished instruction to queue to commit.
627    (*iewQueue)[wbCycle].insts[wbNumInst] = inst;
628    (*iewQueue)[wbCycle].size++;
629}
630
631template <class Impl>
632unsigned
633DefaultIEW<Impl>::validInstsFromRename()
634{
635    unsigned inst_count = 0;
636
637    for (int i=0; i<fromRename->size; i++) {
638        if (!fromRename->insts[i]->isSquashed())
639            inst_count++;
640    }
641
642    return inst_count;
643}
644
645template<class Impl>
646void
647DefaultIEW<Impl>::skidInsert(ThreadID tid)
648{
649    DynInstPtr inst = NULL;
650
651    while (!insts[tid].empty()) {
652        inst = insts[tid].front();
653
654        insts[tid].pop();
655
656        DPRINTF(IEW,"[tid:%i]: Inserting [sn:%lli] PC:%s into "
657                "dispatch skidBuffer %i\n",tid, inst->seqNum,
658                inst->pcState(),tid);
659
660        skidBuffer[tid].push(inst);
661    }
662
663    assert(skidBuffer[tid].size() <= skidBufferMax &&
664           "Skidbuffer Exceeded Max Size");
665}
666
667template<class Impl>
668int
669DefaultIEW<Impl>::skidCount()
670{
671    int max=0;
672
673    list<ThreadID>::iterator threads = activeThreads->begin();
674    list<ThreadID>::iterator end = activeThreads->end();
675
676    while (threads != end) {
677        ThreadID tid = *threads++;
678        unsigned thread_count = skidBuffer[tid].size();
679        if (max < thread_count)
680            max = thread_count;
681    }
682
683    return max;
684}
685
686template<class Impl>
687bool
688DefaultIEW<Impl>::skidsEmpty()
689{
690    list<ThreadID>::iterator threads = activeThreads->begin();
691    list<ThreadID>::iterator end = activeThreads->end();
692
693    while (threads != end) {
694        ThreadID tid = *threads++;
695
696        if (!skidBuffer[tid].empty())
697            return false;
698    }
699
700    return true;
701}
702
703template <class Impl>
704void
705DefaultIEW<Impl>::updateStatus()
706{
707    bool any_unblocking = false;
708
709    list<ThreadID>::iterator threads = activeThreads->begin();
710    list<ThreadID>::iterator end = activeThreads->end();
711
712    while (threads != end) {
713        ThreadID tid = *threads++;
714
715        if (dispatchStatus[tid] == Unblocking) {
716            any_unblocking = true;
717            break;
718        }
719    }
720
721    // If there are no ready instructions waiting to be scheduled by the IQ,
722    // and there's no stores waiting to write back, and dispatch is not
723    // unblocking, then there is no internal activity for the IEW stage.
724    instQueue.intInstQueueReads++;
725    if (_status == Active && !instQueue.hasReadyInsts() &&
726        !ldstQueue.willWB() && !any_unblocking) {
727        DPRINTF(IEW, "IEW switching to idle\n");
728
729        deactivateStage();
730
731        _status = Inactive;
732    } else if (_status == Inactive && (instQueue.hasReadyInsts() ||
733                                       ldstQueue.willWB() ||
734                                       any_unblocking)) {
735        // Otherwise there is internal activity.  Set to active.
736        DPRINTF(IEW, "IEW switching to active\n");
737
738        activateStage();
739
740        _status = Active;
741    }
742}
743
744template <class Impl>
745void
746DefaultIEW<Impl>::resetEntries()
747{
748    instQueue.resetEntries();
749    ldstQueue.resetEntries();
750}
751
752template <class Impl>
753bool
754DefaultIEW<Impl>::checkStall(ThreadID tid)
755{
756    bool ret_val(false);
757
758    if (fromCommit->commitInfo[tid].robSquashing) {
759        DPRINTF(IEW,"[tid:%i]: Stall from Commit stage detected.\n",tid);
760        ret_val = true;
761    } else if (instQueue.isFull(tid)) {
762        DPRINTF(IEW,"[tid:%i]: Stall: IQ  is full.\n",tid);
763        ret_val = true;
764    }
765
766    return ret_val;
767}
768
769template <class Impl>
770void
771DefaultIEW<Impl>::checkSignalsAndUpdate(ThreadID tid)
772{
773    // Check if there's a squash signal, squash if there is
774    // Check stall signals, block if there is.
775    // If status was Blocked
776    //     if so then go to unblocking
777    // If status was Squashing
778    //     check if squashing is not high.  Switch to running this cycle.
779
780    if (fromCommit->commitInfo[tid].squash) {
781        squash(tid);
782
783        if (dispatchStatus[tid] == Blocked ||
784            dispatchStatus[tid] == Unblocking) {
785            toRename->iewUnblock[tid] = true;
786            wroteToTimeBuffer = true;
787        }
788
789        dispatchStatus[tid] = Squashing;
790        fetchRedirect[tid] = false;
791        return;
792    }
793
794    if (fromCommit->commitInfo[tid].robSquashing) {
795        DPRINTF(IEW, "[tid:%i]: ROB is still squashing.\n", tid);
796
797        dispatchStatus[tid] = Squashing;
798        emptyRenameInsts(tid);
799        wroteToTimeBuffer = true;
800    }
801
802    if (checkStall(tid)) {
803        block(tid);
804        dispatchStatus[tid] = Blocked;
805        return;
806    }
807
808    if (dispatchStatus[tid] == Blocked) {
809        // Status from previous cycle was blocked, but there are no more stall
810        // conditions.  Switch over to unblocking.
811        DPRINTF(IEW, "[tid:%i]: Done blocking, switching to unblocking.\n",
812                tid);
813
814        dispatchStatus[tid] = Unblocking;
815
816        unblock(tid);
817
818        return;
819    }
820
821    if (dispatchStatus[tid] == Squashing) {
822        // Switch status to running if rename isn't being told to block or
823        // squash this cycle.
824        DPRINTF(IEW, "[tid:%i]: Done squashing, switching to running.\n",
825                tid);
826
827        dispatchStatus[tid] = Running;
828
829        return;
830    }
831}
832
833template <class Impl>
834void
835DefaultIEW<Impl>::sortInsts()
836{
837    int insts_from_rename = fromRename->size;
838#ifdef DEBUG
839    for (ThreadID tid = 0; tid < numThreads; tid++)
840        assert(insts[tid].empty());
841#endif
842    for (int i = 0; i < insts_from_rename; ++i) {
843        insts[fromRename->insts[i]->threadNumber].push(fromRename->insts[i]);
844    }
845}
846
847template <class Impl>
848void
849DefaultIEW<Impl>::emptyRenameInsts(ThreadID tid)
850{
851    DPRINTF(IEW, "[tid:%i]: Removing incoming rename instructions\n", tid);
852
853    while (!insts[tid].empty()) {
854
855        if (insts[tid].front()->isLoad()) {
856            toRename->iewInfo[tid].dispatchedToLQ++;
857        }
858        if (insts[tid].front()->isStore()) {
859            toRename->iewInfo[tid].dispatchedToSQ++;
860        }
861
862        toRename->iewInfo[tid].dispatched++;
863
864        insts[tid].pop();
865    }
866}
867
868template <class Impl>
869void
870DefaultIEW<Impl>::wakeCPU()
871{
872    cpu->wakeCPU();
873}
874
875template <class Impl>
876void
877DefaultIEW<Impl>::activityThisCycle()
878{
879    DPRINTF(Activity, "Activity this cycle.\n");
880    cpu->activityThisCycle();
881}
882
883template <class Impl>
884inline void
885DefaultIEW<Impl>::activateStage()
886{
887    DPRINTF(Activity, "Activating stage.\n");
888    cpu->activateStage(O3CPU::IEWIdx);
889}
890
891template <class Impl>
892inline void
893DefaultIEW<Impl>::deactivateStage()
894{
895    DPRINTF(Activity, "Deactivating stage.\n");
896    cpu->deactivateStage(O3CPU::IEWIdx);
897}
898
899template<class Impl>
900void
901DefaultIEW<Impl>::dispatch(ThreadID tid)
902{
903    // If status is Running or idle,
904    //     call dispatchInsts()
905    // If status is Unblocking,
906    //     buffer any instructions coming from rename
907    //     continue trying to empty skid buffer
908    //     check if stall conditions have passed
909
910    if (dispatchStatus[tid] == Blocked) {
911        ++iewBlockCycles;
912
913    } else if (dispatchStatus[tid] == Squashing) {
914        ++iewSquashCycles;
915    }
916
917    // Dispatch should try to dispatch as many instructions as its bandwidth
918    // will allow, as long as it is not currently blocked.
919    if (dispatchStatus[tid] == Running ||
920        dispatchStatus[tid] == Idle) {
921        DPRINTF(IEW, "[tid:%i] Not blocked, so attempting to run "
922                "dispatch.\n", tid);
923
924        dispatchInsts(tid);
925    } else if (dispatchStatus[tid] == Unblocking) {
926        // Make sure that the skid buffer has something in it if the
927        // status is unblocking.
928        assert(!skidsEmpty());
929
930        // If the status was unblocking, then instructions from the skid
931        // buffer were used.  Remove those instructions and handle
932        // the rest of unblocking.
933        dispatchInsts(tid);
934
935        ++iewUnblockCycles;
936
937        if (validInstsFromRename()) {
938            // Add the current inputs to the skid buffer so they can be
939            // reprocessed when this stage unblocks.
940            skidInsert(tid);
941        }
942
943        unblock(tid);
944    }
945}
946
947template <class Impl>
948void
949DefaultIEW<Impl>::dispatchInsts(ThreadID tid)
950{
951    // Obtain instructions from skid buffer if unblocking, or queue from rename
952    // otherwise.
953    std::queue<DynInstPtr> &insts_to_dispatch =
954        dispatchStatus[tid] == Unblocking ?
955        skidBuffer[tid] : insts[tid];
956
957    int insts_to_add = insts_to_dispatch.size();
958
959    DynInstPtr inst;
960    bool add_to_iq = false;
961    int dis_num_inst = 0;
962
963    // Loop through the instructions, putting them in the instruction
964    // queue.
965    for ( ; dis_num_inst < insts_to_add &&
966              dis_num_inst < dispatchWidth;
967          ++dis_num_inst)
968    {
969        inst = insts_to_dispatch.front();
970
971        if (dispatchStatus[tid] == Unblocking) {
972            DPRINTF(IEW, "[tid:%i]: Issue: Examining instruction from skid "
973                    "buffer\n", tid);
974        }
975
976        // Make sure there's a valid instruction there.
977        assert(inst);
978
979        DPRINTF(IEW, "[tid:%i]: Issue: Adding PC %s [sn:%lli] [tid:%i] to "
980                "IQ.\n",
981                tid, inst->pcState(), inst->seqNum, inst->threadNumber);
982
983        // Be sure to mark these instructions as ready so that the
984        // commit stage can go ahead and execute them, and mark
985        // them as issued so the IQ doesn't reprocess them.
986
987        // Check for squashed instructions.
988        if (inst->isSquashed()) {
989            DPRINTF(IEW, "[tid:%i]: Issue: Squashed instruction encountered, "
990                    "not adding to IQ.\n", tid);
991
992            ++iewDispSquashedInsts;
993
994            insts_to_dispatch.pop();
995
996            //Tell Rename That An Instruction has been processed
997            if (inst->isLoad()) {
998                toRename->iewInfo[tid].dispatchedToLQ++;
999            }
1000            if (inst->isStore()) {
1001                toRename->iewInfo[tid].dispatchedToSQ++;
1002            }
1003
1004            toRename->iewInfo[tid].dispatched++;
1005
1006            continue;
1007        }
1008
1009        // Check for full conditions.
1010        if (instQueue.isFull(tid)) {
1011            DPRINTF(IEW, "[tid:%i]: Issue: IQ has become full.\n", tid);
1012
1013            // Call function to start blocking.
1014            block(tid);
1015
1016            // Set unblock to false. Special case where we are using
1017            // skidbuffer (unblocking) instructions but then we still
1018            // get full in the IQ.
1019            toRename->iewUnblock[tid] = false;
1020
1021            ++iewIQFullEvents;
1022            break;
1023        }
1024
1025        // Check LSQ if inst is LD/ST
1026        if ((inst->isLoad() && ldstQueue.lqFull(tid)) ||
1027            (inst->isStore() && ldstQueue.sqFull(tid))) {
1028            DPRINTF(IEW, "[tid:%i]: Issue: %s has become full.\n",tid,
1029                    inst->isLoad() ? "LQ" : "SQ");
1030
1031            // Call function to start blocking.
1032            block(tid);
1033
1034            // Set unblock to false. Special case where we are using
1035            // skidbuffer (unblocking) instructions but then we still
1036            // get full in the IQ.
1037            toRename->iewUnblock[tid] = false;
1038
1039            ++iewLSQFullEvents;
1040            break;
1041        }
1042
1043        // Otherwise issue the instruction just fine.
1044        if (inst->isLoad()) {
1045            DPRINTF(IEW, "[tid:%i]: Issue: Memory instruction "
1046                    "encountered, adding to LSQ.\n", tid);
1047
1048            // Reserve a spot in the load store queue for this
1049            // memory access.
1050            ldstQueue.insertLoad(inst);
1051
1052            ++iewDispLoadInsts;
1053
1054            add_to_iq = true;
1055
1056            toRename->iewInfo[tid].dispatchedToLQ++;
1057        } else if (inst->isStore()) {
1058            DPRINTF(IEW, "[tid:%i]: Issue: Memory instruction "
1059                    "encountered, adding to LSQ.\n", tid);
1060
1061            ldstQueue.insertStore(inst);
1062
1063            ++iewDispStoreInsts;
1064
1065            if (inst->isStoreConditional()) {
1066                // Store conditionals need to be set as "canCommit()"
1067                // so that commit can process them when they reach the
1068                // head of commit.
1069                // @todo: This is somewhat specific to Alpha.
1070                inst->setCanCommit();
1071                instQueue.insertNonSpec(inst);
1072                add_to_iq = false;
1073
1074                ++iewDispNonSpecInsts;
1075            } else {
1076                add_to_iq = true;
1077            }
1078
1079            toRename->iewInfo[tid].dispatchedToSQ++;
1080        } else if (inst->isMemBarrier() || inst->isWriteBarrier()) {
1081            // Same as non-speculative stores.
1082            inst->setCanCommit();
1083            instQueue.insertBarrier(inst);
1084            add_to_iq = false;
1085        } else if (inst->isNop()) {
1086            DPRINTF(IEW, "[tid:%i]: Issue: Nop instruction encountered, "
1087                    "skipping.\n", tid);
1088
1089            inst->setIssued();
1090            inst->setExecuted();
1091            inst->setCanCommit();
1092
1093            instQueue.recordProducer(inst);
1094
1095            iewExecutedNop[tid]++;
1096
1097            add_to_iq = false;
1098        } else {
1099            assert(!inst->isExecuted());
1100            add_to_iq = true;
1101        }
1102
1103        if (inst->isNonSpeculative()) {
1104            DPRINTF(IEW, "[tid:%i]: Issue: Nonspeculative instruction "
1105                    "encountered, skipping.\n", tid);
1106
1107            // Same as non-speculative stores.
1108            inst->setCanCommit();
1109
1110            // Specifically insert it as nonspeculative.
1111            instQueue.insertNonSpec(inst);
1112
1113            ++iewDispNonSpecInsts;
1114
1115            add_to_iq = false;
1116        }
1117
1118        // If the instruction queue is not full, then add the
1119        // instruction.
1120        if (add_to_iq) {
1121            instQueue.insert(inst);
1122        }
1123
1124        insts_to_dispatch.pop();
1125
1126        toRename->iewInfo[tid].dispatched++;
1127
1128        ++iewDispatchedInsts;
1129
1130#if TRACING_ON
1131        inst->dispatchTick = curTick() - inst->fetchTick;
1132#endif
1133        ppDispatch->notify(inst);
1134    }
1135
1136    if (!insts_to_dispatch.empty()) {
1137        DPRINTF(IEW,"[tid:%i]: Issue: Bandwidth Full. Blocking.\n", tid);
1138        block(tid);
1139        toRename->iewUnblock[tid] = false;
1140    }
1141
1142    if (dispatchStatus[tid] == Idle && dis_num_inst) {
1143        dispatchStatus[tid] = Running;
1144
1145        updatedQueues = true;
1146    }
1147
1148    dis_num_inst = 0;
1149}
1150
1151template <class Impl>
1152void
1153DefaultIEW<Impl>::printAvailableInsts()
1154{
1155    int inst = 0;
1156
1157    std::cout << "Available Instructions: ";
1158
1159    while (fromIssue->insts[inst]) {
1160
1161        if (inst%3==0) std::cout << "\n\t";
1162
1163        std::cout << "PC: " << fromIssue->insts[inst]->pcState()
1164             << " TN: " << fromIssue->insts[inst]->threadNumber
1165             << " SN: " << fromIssue->insts[inst]->seqNum << " | ";
1166
1167        inst++;
1168
1169    }
1170
1171    std::cout << "\n";
1172}
1173
1174template <class Impl>
1175void
1176DefaultIEW<Impl>::executeInsts()
1177{
1178    wbNumInst = 0;
1179    wbCycle = 0;
1180
1181    list<ThreadID>::iterator threads = activeThreads->begin();
1182    list<ThreadID>::iterator end = activeThreads->end();
1183
1184    while (threads != end) {
1185        ThreadID tid = *threads++;
1186        fetchRedirect[tid] = false;
1187    }
1188
1189    // Uncomment this if you want to see all available instructions.
1190    // @todo This doesn't actually work anymore, we should fix it.
1191//    printAvailableInsts();
1192
1193    // Execute/writeback any instructions that are available.
1194    int insts_to_execute = fromIssue->size;
1195    int inst_num = 0;
1196    for (; inst_num < insts_to_execute;
1197          ++inst_num) {
1198
1199        DPRINTF(IEW, "Execute: Executing instructions from IQ.\n");
1200
1201        DynInstPtr inst = instQueue.getInstToExecute();
1202
1203        DPRINTF(IEW, "Execute: Processing PC %s, [tid:%i] [sn:%i].\n",
1204                inst->pcState(), inst->threadNumber,inst->seqNum);
1205
1206        // Check if the instruction is squashed; if so then skip it
1207        if (inst->isSquashed()) {
1208            DPRINTF(IEW, "Execute: Instruction was squashed. PC: %s, [tid:%i]"
1209                         " [sn:%i]\n", inst->pcState(), inst->threadNumber,
1210                         inst->seqNum);
1211
1212            // Consider this instruction executed so that commit can go
1213            // ahead and retire the instruction.
1214            inst->setExecuted();
1215
1216            // Not sure if I should set this here or just let commit try to
1217            // commit any squashed instructions.  I like the latter a bit more.
1218            inst->setCanCommit();
1219
1220            ++iewExecSquashedInsts;
1221
1222            continue;
1223        }
1224
1225        Fault fault = NoFault;
1226
1227        // Execute instruction.
1228        // Note that if the instruction faults, it will be handled
1229        // at the commit stage.
1230        if (inst->isMemRef()) {
1231            DPRINTF(IEW, "Execute: Calculating address for memory "
1232                    "reference.\n");
1233
1234            // Tell the LDSTQ to execute this instruction (if it is a load).
1235            if (inst->isLoad()) {
1236                // Loads will mark themselves as executed, and their writeback
1237                // event adds the instruction to the queue to commit
1238                fault = ldstQueue.executeLoad(inst);
1239
1240                if (inst->isTranslationDelayed() &&
1241                    fault == NoFault) {
1242                    // A hw page table walk is currently going on; the
1243                    // instruction must be deferred.
1244                    DPRINTF(IEW, "Execute: Delayed translation, deferring "
1245                            "load.\n");
1246                    instQueue.deferMemInst(inst);
1247                    continue;
1248                }
1249
1250                if (inst->isDataPrefetch() || inst->isInstPrefetch()) {
1251                    inst->fault = NoFault;
1252                }
1253            } else if (inst->isStore()) {
1254                fault = ldstQueue.executeStore(inst);
1255
1256                if (inst->isTranslationDelayed() &&
1257                    fault == NoFault) {
1258                    // A hw page table walk is currently going on; the
1259                    // instruction must be deferred.
1260                    DPRINTF(IEW, "Execute: Delayed translation, deferring "
1261                            "store.\n");
1262                    instQueue.deferMemInst(inst);
1263                    continue;
1264                }
1265
1266                // If the store had a fault then it may not have a mem req
1267                if (fault != NoFault || !inst->readPredicate() ||
1268                        !inst->isStoreConditional()) {
1269                    // If the instruction faulted, then we need to send it along
1270                    // to commit without the instruction completing.
1271                    // Send this instruction to commit, also make sure iew stage
1272                    // realizes there is activity.
1273                    inst->setExecuted();
1274                    instToCommit(inst);
1275                    activityThisCycle();
1276                }
1277
1278                // Store conditionals will mark themselves as
1279                // executed, and their writeback event will add the
1280                // instruction to the queue to commit.
1281            } else {
1282                panic("Unexpected memory type!\n");
1283            }
1284
1285        } else {
1286            // If the instruction has already faulted, then skip executing it.
1287            // Such case can happen when it faulted during ITLB translation.
1288            // If we execute the instruction (even if it's a nop) the fault
1289            // will be replaced and we will lose it.
1290            if (inst->getFault() == NoFault) {
1291                inst->execute();
1292                if (!inst->readPredicate())
1293                    inst->forwardOldRegs();
1294            }
1295
1296            inst->setExecuted();
1297
1298            instToCommit(inst);
1299        }
1300
1301        updateExeInstStats(inst);
1302
1303        // Check if branch prediction was correct, if not then we need
1304        // to tell commit to squash in flight instructions.  Only
1305        // handle this if there hasn't already been something that
1306        // redirects fetch in this group of instructions.
1307
1308        // This probably needs to prioritize the redirects if a different
1309        // scheduler is used.  Currently the scheduler schedules the oldest
1310        // instruction first, so the branch resolution order will be correct.
1311        ThreadID tid = inst->threadNumber;
1312
1313        if (!fetchRedirect[tid] ||
1314            !toCommit->squash[tid] ||
1315            toCommit->squashedSeqNum[tid] > inst->seqNum) {
1316
1317            // Prevent testing for misprediction on load instructions,
1318            // that have not been executed.
1319            bool loadNotExecuted = !inst->isExecuted() && inst->isLoad();
1320
1321            if (inst->mispredicted() && !loadNotExecuted) {
1322                fetchRedirect[tid] = true;
1323
1324                DPRINTF(IEW, "Execute: Branch mispredict detected.\n");
1325                DPRINTF(IEW, "Predicted target was PC: %s.\n",
1326                        inst->readPredTarg());
1327                DPRINTF(IEW, "Execute: Redirecting fetch to PC: %s.\n",
1328                        inst->pcState());
1329                // If incorrect, then signal the ROB that it must be squashed.
1330                squashDueToBranch(inst, tid);
1331
1332                ppMispredict->notify(inst);
1333
1334                if (inst->readPredTaken()) {
1335                    predictedTakenIncorrect++;
1336                } else {
1337                    predictedNotTakenIncorrect++;
1338                }
1339            } else if (ldstQueue.violation(tid)) {
1340                assert(inst->isMemRef());
1341                // If there was an ordering violation, then get the
1342                // DynInst that caused the violation.  Note that this
1343                // clears the violation signal.
1344                DynInstPtr violator;
1345                violator = ldstQueue.getMemDepViolator(tid);
1346
1347                DPRINTF(IEW, "LDSTQ detected a violation. Violator PC: %s "
1348                        "[sn:%lli], inst PC: %s [sn:%lli]. Addr is: %#x.\n",
1349                        violator->pcState(), violator->seqNum,
1350                        inst->pcState(), inst->seqNum, inst->physEffAddr);
1351
1352                fetchRedirect[tid] = true;
1353
1354                // Tell the instruction queue that a violation has occured.
1355                instQueue.violation(inst, violator);
1356
1357                // Squash.
1358                squashDueToMemOrder(violator, tid);
1359
1360                ++memOrderViolationEvents;
1361            }
1362        } else {
1363            // Reset any state associated with redirects that will not
1364            // be used.
1365            if (ldstQueue.violation(tid)) {
1366                assert(inst->isMemRef());
1367
1368                DynInstPtr violator = ldstQueue.getMemDepViolator(tid);
1369
1370                DPRINTF(IEW, "LDSTQ detected a violation.  Violator PC: "
1371                        "%s, inst PC: %s.  Addr is: %#x.\n",
1372                        violator->pcState(), inst->pcState(),
1373                        inst->physEffAddr);
1374                DPRINTF(IEW, "Violation will not be handled because "
1375                        "already squashing\n");
1376
1377                ++memOrderViolationEvents;
1378            }
1379        }
1380    }
1381
1382    // Update and record activity if we processed any instructions.
1383    if (inst_num) {
1384        if (exeStatus == Idle) {
1385            exeStatus = Running;
1386        }
1387
1388        updatedQueues = true;
1389
1390        cpu->activityThisCycle();
1391    }
1392
1393    // Need to reset this in case a writeback event needs to write into the
1394    // iew queue.  That way the writeback event will write into the correct
1395    // spot in the queue.
1396    wbNumInst = 0;
1397
1398}
1399
1400template <class Impl>
1401void
1402DefaultIEW<Impl>::writebackInsts()
1403{
1404    // Loop through the head of the time buffer and wake any
1405    // dependents.  These instructions are about to write back.  Also
1406    // mark scoreboard that this instruction is finally complete.
1407    // Either have IEW have direct access to scoreboard, or have this
1408    // as part of backwards communication.
1409    for (int inst_num = 0; inst_num < wbWidth &&
1410             toCommit->insts[inst_num]; inst_num++) {
1411        DynInstPtr inst = toCommit->insts[inst_num];
1412        ThreadID tid = inst->threadNumber;
1413
1414        DPRINTF(IEW, "Sending instructions to commit, [sn:%lli] PC %s.\n",
1415                inst->seqNum, inst->pcState());
1416
1417        iewInstsToCommit[tid]++;
1418
1419        // Some instructions will be sent to commit without having
1420        // executed because they need commit to handle them.
1421        // E.g. Strictly ordered loads have not actually executed when they
1422        // are first sent to commit.  Instead commit must tell the LSQ
1423        // when it's ready to execute the strictly ordered load.
1424        if (!inst->isSquashed() && inst->isExecuted() && inst->getFault() == NoFault) {
1425            int dependents = instQueue.wakeDependents(inst);
1426
1427            for (int i = 0; i < inst->numDestRegs(); i++) {
1428                //mark as Ready
1429                DPRINTF(IEW,"Setting Destination Register %i\n",
1430                        inst->renamedDestRegIdx(i));
1431                scoreboard->setReg(inst->renamedDestRegIdx(i));
1432            }
1433
1434            if (dependents) {
1435                producerInst[tid]++;
1436                consumerInst[tid]+= dependents;
1437            }
1438            writebackCount[tid]++;
1439        }
1440    }
1441}
1442
1443template<class Impl>
1444void
1445DefaultIEW<Impl>::tick()
1446{
1447    wbNumInst = 0;
1448    wbCycle = 0;
1449
1450    wroteToTimeBuffer = false;
1451    updatedQueues = false;
1452
1453    sortInsts();
1454
1455    // Free function units marked as being freed this cycle.
1456    fuPool->processFreeUnits();
1457
1458    list<ThreadID>::iterator threads = activeThreads->begin();
1459    list<ThreadID>::iterator end = activeThreads->end();
1460
1461    // Check stall and squash signals, dispatch any instructions.
1462    while (threads != end) {
1463        ThreadID tid = *threads++;
1464
1465        DPRINTF(IEW,"Issue: Processing [tid:%i]\n",tid);
1466
1467        checkSignalsAndUpdate(tid);
1468        dispatch(tid);
1469    }
1470
1471    if (exeStatus != Squashing) {
1472        executeInsts();
1473
1474        writebackInsts();
1475
1476        // Have the instruction queue try to schedule any ready instructions.
1477        // (In actuality, this scheduling is for instructions that will
1478        // be executed next cycle.)
1479        instQueue.scheduleReadyInsts();
1480
1481        // Also should advance its own time buffers if the stage ran.
1482        // Not the best place for it, but this works (hopefully).
1483        issueToExecQueue.advance();
1484    }
1485
1486    bool broadcast_free_entries = false;
1487
1488    if (updatedQueues || exeStatus == Running || updateLSQNextCycle) {
1489        exeStatus = Idle;
1490        updateLSQNextCycle = false;
1491
1492        broadcast_free_entries = true;
1493    }
1494
1495    // Writeback any stores using any leftover bandwidth.
1496    ldstQueue.writebackStores();
1497
1498    // Check the committed load/store signals to see if there's a load
1499    // or store to commit.  Also check if it's being told to execute a
1500    // nonspeculative instruction.
1501    // This is pretty inefficient...
1502
1503    threads = activeThreads->begin();
1504    while (threads != end) {
1505        ThreadID tid = (*threads++);
1506
1507        DPRINTF(IEW,"Processing [tid:%i]\n",tid);
1508
1509        // Update structures based on instructions committed.
1510        if (fromCommit->commitInfo[tid].doneSeqNum != 0 &&
1511            !fromCommit->commitInfo[tid].squash &&
1512            !fromCommit->commitInfo[tid].robSquashing) {
1513
1514            ldstQueue.commitStores(fromCommit->commitInfo[tid].doneSeqNum,tid);
1515
1516            ldstQueue.commitLoads(fromCommit->commitInfo[tid].doneSeqNum,tid);
1517
1518            updateLSQNextCycle = true;
1519            instQueue.commit(fromCommit->commitInfo[tid].doneSeqNum,tid);
1520        }
1521
1522        if (fromCommit->commitInfo[tid].nonSpecSeqNum != 0) {
1523
1524            //DPRINTF(IEW,"NonspecInst from thread %i",tid);
1525            if (fromCommit->commitInfo[tid].strictlyOrdered) {
1526                instQueue.replayMemInst(
1527                    fromCommit->commitInfo[tid].strictlyOrderedLoad);
1528                fromCommit->commitInfo[tid].strictlyOrderedLoad->setAtCommit();
1529            } else {
1530                instQueue.scheduleNonSpec(
1531                    fromCommit->commitInfo[tid].nonSpecSeqNum);
1532            }
1533        }
1534
1535        if (broadcast_free_entries) {
1536            toFetch->iewInfo[tid].iqCount =
1537                instQueue.getCount(tid);
1538            toFetch->iewInfo[tid].ldstqCount =
1539                ldstQueue.getCount(tid);
1540
1541            toRename->iewInfo[tid].usedIQ = true;
1542            toRename->iewInfo[tid].freeIQEntries =
1543                instQueue.numFreeEntries(tid);
1544            toRename->iewInfo[tid].usedLSQ = true;
1545
1546            toRename->iewInfo[tid].freeLQEntries =
1547                ldstQueue.numFreeLoadEntries(tid);
1548            toRename->iewInfo[tid].freeSQEntries =
1549                ldstQueue.numFreeStoreEntries(tid);
1550
1551            wroteToTimeBuffer = true;
1552        }
1553
1554        DPRINTF(IEW, "[tid:%i], Dispatch dispatched %i instructions.\n",
1555                tid, toRename->iewInfo[tid].dispatched);
1556    }
1557
1558    DPRINTF(IEW, "IQ has %i free entries (Can schedule: %i).  "
1559            "LQ has %i free entries. SQ has %i free entries.\n",
1560            instQueue.numFreeEntries(), instQueue.hasReadyInsts(),
1561            ldstQueue.numFreeLoadEntries(), ldstQueue.numFreeStoreEntries());
1562
1563    updateStatus();
1564
1565    if (wroteToTimeBuffer) {
1566        DPRINTF(Activity, "Activity this cycle.\n");
1567        cpu->activityThisCycle();
1568    }
1569}
1570
1571template <class Impl>
1572void
1573DefaultIEW<Impl>::updateExeInstStats(DynInstPtr &inst)
1574{
1575    ThreadID tid = inst->threadNumber;
1576
1577    iewExecutedInsts++;
1578
1579#if TRACING_ON
1580    if (DTRACE(O3PipeView)) {
1581        inst->completeTick = curTick() - inst->fetchTick;
1582    }
1583#endif
1584
1585    //
1586    //  Control operations
1587    //
1588    if (inst->isControl())
1589        iewExecutedBranches[tid]++;
1590
1591    //
1592    //  Memory operations
1593    //
1594    if (inst->isMemRef()) {
1595        iewExecutedRefs[tid]++;
1596
1597        if (inst->isLoad()) {
1598            iewExecLoadInsts[tid]++;
1599        }
1600    }
1601}
1602
1603template <class Impl>
1604void
1605DefaultIEW<Impl>::checkMisprediction(DynInstPtr &inst)
1606{
1607    ThreadID tid = inst->threadNumber;
1608
1609    if (!fetchRedirect[tid] ||
1610        !toCommit->squash[tid] ||
1611        toCommit->squashedSeqNum[tid] > inst->seqNum) {
1612
1613        if (inst->mispredicted()) {
1614            fetchRedirect[tid] = true;
1615
1616            DPRINTF(IEW, "Execute: Branch mispredict detected.\n");
1617            DPRINTF(IEW, "Predicted target was PC:%#x, NPC:%#x.\n",
1618                    inst->predInstAddr(), inst->predNextInstAddr());
1619            DPRINTF(IEW, "Execute: Redirecting fetch to PC: %#x,"
1620                    " NPC: %#x.\n", inst->nextInstAddr(),
1621                    inst->nextInstAddr());
1622            // If incorrect, then signal the ROB that it must be squashed.
1623            squashDueToBranch(inst, tid);
1624
1625            if (inst->readPredTaken()) {
1626                predictedTakenIncorrect++;
1627            } else {
1628                predictedNotTakenIncorrect++;
1629            }
1630        }
1631    }
1632}
1633
1634#endif//__CPU_O3_IEW_IMPL_IMPL_HH__
1635