iew_impl.hh revision 10328:867b536a68be
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());
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>::squashDueToMemBlocked(DynInstPtr &inst, ThreadID tid)
534{
535    DPRINTF(IEW, "[tid:%i]: Memory blocked, squashing load and younger insts, "
536            "PC: %s [sn:%i].\n", tid, inst->pcState(), inst->seqNum);
537    if (!toCommit->squash[tid] ||
538            inst->seqNum < toCommit->squashedSeqNum[tid]) {
539        toCommit->squash[tid] = true;
540
541        toCommit->squashedSeqNum[tid] = inst->seqNum;
542        toCommit->pc[tid] = inst->pcState();
543        toCommit->mispredictInst[tid] = NULL;
544
545        // Must include the broadcasted SN in the squash.
546        toCommit->includeSquashInst[tid] = true;
547
548        ldstQueue.setLoadBlockedHandled(tid);
549
550        wroteToTimeBuffer = true;
551    }
552}
553
554template<class Impl>
555void
556DefaultIEW<Impl>::block(ThreadID tid)
557{
558    DPRINTF(IEW, "[tid:%u]: Blocking.\n", tid);
559
560    if (dispatchStatus[tid] != Blocked &&
561        dispatchStatus[tid] != Unblocking) {
562        toRename->iewBlock[tid] = true;
563        wroteToTimeBuffer = true;
564    }
565
566    // Add the current inputs to the skid buffer so they can be
567    // reprocessed when this stage unblocks.
568    skidInsert(tid);
569
570    dispatchStatus[tid] = Blocked;
571}
572
573template<class Impl>
574void
575DefaultIEW<Impl>::unblock(ThreadID tid)
576{
577    DPRINTF(IEW, "[tid:%i]: Reading instructions out of the skid "
578            "buffer %u.\n",tid, tid);
579
580    // If the skid bufffer is empty, signal back to previous stages to unblock.
581    // Also switch status to running.
582    if (skidBuffer[tid].empty()) {
583        toRename->iewUnblock[tid] = true;
584        wroteToTimeBuffer = true;
585        DPRINTF(IEW, "[tid:%i]: Done unblocking.\n",tid);
586        dispatchStatus[tid] = Running;
587    }
588}
589
590template<class Impl>
591void
592DefaultIEW<Impl>::wakeDependents(DynInstPtr &inst)
593{
594    instQueue.wakeDependents(inst);
595}
596
597template<class Impl>
598void
599DefaultIEW<Impl>::rescheduleMemInst(DynInstPtr &inst)
600{
601    instQueue.rescheduleMemInst(inst);
602}
603
604template<class Impl>
605void
606DefaultIEW<Impl>::replayMemInst(DynInstPtr &inst)
607{
608    instQueue.replayMemInst(inst);
609}
610
611template<class Impl>
612void
613DefaultIEW<Impl>::instToCommit(DynInstPtr &inst)
614{
615    // This function should not be called after writebackInsts in a
616    // single cycle.  That will cause problems with an instruction
617    // being added to the queue to commit without being processed by
618    // writebackInsts prior to being sent to commit.
619
620    // First check the time slot that this instruction will write
621    // to.  If there are free write ports at the time, then go ahead
622    // and write the instruction to that time.  If there are not,
623    // keep looking back to see where's the first time there's a
624    // free slot.
625    while ((*iewQueue)[wbCycle].insts[wbNumInst]) {
626        ++wbNumInst;
627        if (wbNumInst == wbWidth) {
628            ++wbCycle;
629            wbNumInst = 0;
630        }
631    }
632
633    DPRINTF(IEW, "Current wb cycle: %i, width: %i, numInst: %i\nwbActual:%i\n",
634            wbCycle, wbWidth, wbNumInst, wbCycle * wbWidth + wbNumInst);
635    // Add finished instruction to queue to commit.
636    (*iewQueue)[wbCycle].insts[wbNumInst] = inst;
637    (*iewQueue)[wbCycle].size++;
638}
639
640template <class Impl>
641unsigned
642DefaultIEW<Impl>::validInstsFromRename()
643{
644    unsigned inst_count = 0;
645
646    for (int i=0; i<fromRename->size; i++) {
647        if (!fromRename->insts[i]->isSquashed())
648            inst_count++;
649    }
650
651    return inst_count;
652}
653
654template<class Impl>
655void
656DefaultIEW<Impl>::skidInsert(ThreadID tid)
657{
658    DynInstPtr inst = NULL;
659
660    while (!insts[tid].empty()) {
661        inst = insts[tid].front();
662
663        insts[tid].pop();
664
665        DPRINTF(IEW,"[tid:%i]: Inserting [sn:%lli] PC:%s into "
666                "dispatch skidBuffer %i\n",tid, inst->seqNum,
667                inst->pcState(),tid);
668
669        skidBuffer[tid].push(inst);
670    }
671
672    assert(skidBuffer[tid].size() <= skidBufferMax &&
673           "Skidbuffer Exceeded Max Size");
674}
675
676template<class Impl>
677int
678DefaultIEW<Impl>::skidCount()
679{
680    int max=0;
681
682    list<ThreadID>::iterator threads = activeThreads->begin();
683    list<ThreadID>::iterator end = activeThreads->end();
684
685    while (threads != end) {
686        ThreadID tid = *threads++;
687        unsigned thread_count = skidBuffer[tid].size();
688        if (max < thread_count)
689            max = thread_count;
690    }
691
692    return max;
693}
694
695template<class Impl>
696bool
697DefaultIEW<Impl>::skidsEmpty()
698{
699    list<ThreadID>::iterator threads = activeThreads->begin();
700    list<ThreadID>::iterator end = activeThreads->end();
701
702    while (threads != end) {
703        ThreadID tid = *threads++;
704
705        if (!skidBuffer[tid].empty())
706            return false;
707    }
708
709    return true;
710}
711
712template <class Impl>
713void
714DefaultIEW<Impl>::updateStatus()
715{
716    bool any_unblocking = false;
717
718    list<ThreadID>::iterator threads = activeThreads->begin();
719    list<ThreadID>::iterator end = activeThreads->end();
720
721    while (threads != end) {
722        ThreadID tid = *threads++;
723
724        if (dispatchStatus[tid] == Unblocking) {
725            any_unblocking = true;
726            break;
727        }
728    }
729
730    // If there are no ready instructions waiting to be scheduled by the IQ,
731    // and there's no stores waiting to write back, and dispatch is not
732    // unblocking, then there is no internal activity for the IEW stage.
733    instQueue.intInstQueueReads++;
734    if (_status == Active && !instQueue.hasReadyInsts() &&
735        !ldstQueue.willWB() && !any_unblocking) {
736        DPRINTF(IEW, "IEW switching to idle\n");
737
738        deactivateStage();
739
740        _status = Inactive;
741    } else if (_status == Inactive && (instQueue.hasReadyInsts() ||
742                                       ldstQueue.willWB() ||
743                                       any_unblocking)) {
744        // Otherwise there is internal activity.  Set to active.
745        DPRINTF(IEW, "IEW switching to active\n");
746
747        activateStage();
748
749        _status = Active;
750    }
751}
752
753template <class Impl>
754void
755DefaultIEW<Impl>::resetEntries()
756{
757    instQueue.resetEntries();
758    ldstQueue.resetEntries();
759}
760
761template <class Impl>
762bool
763DefaultIEW<Impl>::checkStall(ThreadID tid)
764{
765    bool ret_val(false);
766
767    if (fromCommit->commitInfo[tid].robSquashing) {
768        DPRINTF(IEW,"[tid:%i]: Stall from Commit stage detected.\n",tid);
769        ret_val = true;
770    } else if (instQueue.isFull(tid)) {
771        DPRINTF(IEW,"[tid:%i]: Stall: IQ  is full.\n",tid);
772        ret_val = true;
773    }
774
775    return ret_val;
776}
777
778template <class Impl>
779void
780DefaultIEW<Impl>::checkSignalsAndUpdate(ThreadID tid)
781{
782    // Check if there's a squash signal, squash if there is
783    // Check stall signals, block if there is.
784    // If status was Blocked
785    //     if so then go to unblocking
786    // If status was Squashing
787    //     check if squashing is not high.  Switch to running this cycle.
788
789    if (fromCommit->commitInfo[tid].squash) {
790        squash(tid);
791
792        if (dispatchStatus[tid] == Blocked ||
793            dispatchStatus[tid] == Unblocking) {
794            toRename->iewUnblock[tid] = true;
795            wroteToTimeBuffer = true;
796        }
797
798        dispatchStatus[tid] = Squashing;
799        fetchRedirect[tid] = false;
800        return;
801    }
802
803    if (fromCommit->commitInfo[tid].robSquashing) {
804        DPRINTF(IEW, "[tid:%i]: ROB is still squashing.\n", tid);
805
806        dispatchStatus[tid] = Squashing;
807        emptyRenameInsts(tid);
808        wroteToTimeBuffer = true;
809    }
810
811    if (checkStall(tid)) {
812        block(tid);
813        dispatchStatus[tid] = Blocked;
814        return;
815    }
816
817    if (dispatchStatus[tid] == Blocked) {
818        // Status from previous cycle was blocked, but there are no more stall
819        // conditions.  Switch over to unblocking.
820        DPRINTF(IEW, "[tid:%i]: Done blocking, switching to unblocking.\n",
821                tid);
822
823        dispatchStatus[tid] = Unblocking;
824
825        unblock(tid);
826
827        return;
828    }
829
830    if (dispatchStatus[tid] == Squashing) {
831        // Switch status to running if rename isn't being told to block or
832        // squash this cycle.
833        DPRINTF(IEW, "[tid:%i]: Done squashing, switching to running.\n",
834                tid);
835
836        dispatchStatus[tid] = Running;
837
838        return;
839    }
840}
841
842template <class Impl>
843void
844DefaultIEW<Impl>::sortInsts()
845{
846    int insts_from_rename = fromRename->size;
847#ifdef DEBUG
848    for (ThreadID tid = 0; tid < numThreads; tid++)
849        assert(insts[tid].empty());
850#endif
851    for (int i = 0; i < insts_from_rename; ++i) {
852        insts[fromRename->insts[i]->threadNumber].push(fromRename->insts[i]);
853    }
854}
855
856template <class Impl>
857void
858DefaultIEW<Impl>::emptyRenameInsts(ThreadID tid)
859{
860    DPRINTF(IEW, "[tid:%i]: Removing incoming rename instructions\n", tid);
861
862    while (!insts[tid].empty()) {
863
864        if (insts[tid].front()->isLoad()) {
865            toRename->iewInfo[tid].dispatchedToLQ++;
866        }
867        if (insts[tid].front()->isStore()) {
868            toRename->iewInfo[tid].dispatchedToSQ++;
869        }
870
871        toRename->iewInfo[tid].dispatched++;
872
873        insts[tid].pop();
874    }
875}
876
877template <class Impl>
878void
879DefaultIEW<Impl>::wakeCPU()
880{
881    cpu->wakeCPU();
882}
883
884template <class Impl>
885void
886DefaultIEW<Impl>::activityThisCycle()
887{
888    DPRINTF(Activity, "Activity this cycle.\n");
889    cpu->activityThisCycle();
890}
891
892template <class Impl>
893inline void
894DefaultIEW<Impl>::activateStage()
895{
896    DPRINTF(Activity, "Activating stage.\n");
897    cpu->activateStage(O3CPU::IEWIdx);
898}
899
900template <class Impl>
901inline void
902DefaultIEW<Impl>::deactivateStage()
903{
904    DPRINTF(Activity, "Deactivating stage.\n");
905    cpu->deactivateStage(O3CPU::IEWIdx);
906}
907
908template<class Impl>
909void
910DefaultIEW<Impl>::dispatch(ThreadID tid)
911{
912    // If status is Running or idle,
913    //     call dispatchInsts()
914    // If status is Unblocking,
915    //     buffer any instructions coming from rename
916    //     continue trying to empty skid buffer
917    //     check if stall conditions have passed
918
919    if (dispatchStatus[tid] == Blocked) {
920        ++iewBlockCycles;
921
922    } else if (dispatchStatus[tid] == Squashing) {
923        ++iewSquashCycles;
924    }
925
926    // Dispatch should try to dispatch as many instructions as its bandwidth
927    // will allow, as long as it is not currently blocked.
928    if (dispatchStatus[tid] == Running ||
929        dispatchStatus[tid] == Idle) {
930        DPRINTF(IEW, "[tid:%i] Not blocked, so attempting to run "
931                "dispatch.\n", tid);
932
933        dispatchInsts(tid);
934    } else if (dispatchStatus[tid] == Unblocking) {
935        // Make sure that the skid buffer has something in it if the
936        // status is unblocking.
937        assert(!skidsEmpty());
938
939        // If the status was unblocking, then instructions from the skid
940        // buffer were used.  Remove those instructions and handle
941        // the rest of unblocking.
942        dispatchInsts(tid);
943
944        ++iewUnblockCycles;
945
946        if (validInstsFromRename()) {
947            // Add the current inputs to the skid buffer so they can be
948            // reprocessed when this stage unblocks.
949            skidInsert(tid);
950        }
951
952        unblock(tid);
953    }
954}
955
956template <class Impl>
957void
958DefaultIEW<Impl>::dispatchInsts(ThreadID tid)
959{
960    // Obtain instructions from skid buffer if unblocking, or queue from rename
961    // otherwise.
962    std::queue<DynInstPtr> &insts_to_dispatch =
963        dispatchStatus[tid] == Unblocking ?
964        skidBuffer[tid] : insts[tid];
965
966    int insts_to_add = insts_to_dispatch.size();
967
968    DynInstPtr inst;
969    bool add_to_iq = false;
970    int dis_num_inst = 0;
971
972    // Loop through the instructions, putting them in the instruction
973    // queue.
974    for ( ; dis_num_inst < insts_to_add &&
975              dis_num_inst < dispatchWidth;
976          ++dis_num_inst)
977    {
978        inst = insts_to_dispatch.front();
979
980        if (dispatchStatus[tid] == Unblocking) {
981            DPRINTF(IEW, "[tid:%i]: Issue: Examining instruction from skid "
982                    "buffer\n", tid);
983        }
984
985        // Make sure there's a valid instruction there.
986        assert(inst);
987
988        DPRINTF(IEW, "[tid:%i]: Issue: Adding PC %s [sn:%lli] [tid:%i] to "
989                "IQ.\n",
990                tid, inst->pcState(), inst->seqNum, inst->threadNumber);
991
992        // Be sure to mark these instructions as ready so that the
993        // commit stage can go ahead and execute them, and mark
994        // them as issued so the IQ doesn't reprocess them.
995
996        // Check for squashed instructions.
997        if (inst->isSquashed()) {
998            DPRINTF(IEW, "[tid:%i]: Issue: Squashed instruction encountered, "
999                    "not adding to IQ.\n", tid);
1000
1001            ++iewDispSquashedInsts;
1002
1003            insts_to_dispatch.pop();
1004
1005            //Tell Rename That An Instruction has been processed
1006            if (inst->isLoad()) {
1007                toRename->iewInfo[tid].dispatchedToLQ++;
1008            }
1009            if (inst->isStore()) {
1010                toRename->iewInfo[tid].dispatchedToSQ++;
1011            }
1012
1013            toRename->iewInfo[tid].dispatched++;
1014
1015            continue;
1016        }
1017
1018        // Check for full conditions.
1019        if (instQueue.isFull(tid)) {
1020            DPRINTF(IEW, "[tid:%i]: Issue: IQ has become full.\n", tid);
1021
1022            // Call function to start blocking.
1023            block(tid);
1024
1025            // Set unblock to false. Special case where we are using
1026            // skidbuffer (unblocking) instructions but then we still
1027            // get full in the IQ.
1028            toRename->iewUnblock[tid] = false;
1029
1030            ++iewIQFullEvents;
1031            break;
1032        }
1033
1034        // Check LSQ if inst is LD/ST
1035        if ((inst->isLoad() && ldstQueue.lqFull(tid)) ||
1036            (inst->isStore() && ldstQueue.sqFull(tid))) {
1037            DPRINTF(IEW, "[tid:%i]: Issue: %s has become full.\n",tid,
1038                    inst->isLoad() ? "LQ" : "SQ");
1039
1040            // Call function to start blocking.
1041            block(tid);
1042
1043            // Set unblock to false. Special case where we are using
1044            // skidbuffer (unblocking) instructions but then we still
1045            // get full in the IQ.
1046            toRename->iewUnblock[tid] = false;
1047
1048            ++iewLSQFullEvents;
1049            break;
1050        }
1051
1052        // Otherwise issue the instruction just fine.
1053        if (inst->isLoad()) {
1054            DPRINTF(IEW, "[tid:%i]: Issue: Memory instruction "
1055                    "encountered, adding to LSQ.\n", tid);
1056
1057            // Reserve a spot in the load store queue for this
1058            // memory access.
1059            ldstQueue.insertLoad(inst);
1060
1061            ++iewDispLoadInsts;
1062
1063            add_to_iq = true;
1064
1065            toRename->iewInfo[tid].dispatchedToLQ++;
1066        } else if (inst->isStore()) {
1067            DPRINTF(IEW, "[tid:%i]: Issue: Memory instruction "
1068                    "encountered, adding to LSQ.\n", tid);
1069
1070            ldstQueue.insertStore(inst);
1071
1072            ++iewDispStoreInsts;
1073
1074            if (inst->isStoreConditional()) {
1075                // Store conditionals need to be set as "canCommit()"
1076                // so that commit can process them when they reach the
1077                // head of commit.
1078                // @todo: This is somewhat specific to Alpha.
1079                inst->setCanCommit();
1080                instQueue.insertNonSpec(inst);
1081                add_to_iq = false;
1082
1083                ++iewDispNonSpecInsts;
1084            } else {
1085                add_to_iq = true;
1086            }
1087
1088            toRename->iewInfo[tid].dispatchedToSQ++;
1089        } else if (inst->isMemBarrier() || inst->isWriteBarrier()) {
1090            // Same as non-speculative stores.
1091            inst->setCanCommit();
1092            instQueue.insertBarrier(inst);
1093            add_to_iq = false;
1094        } else if (inst->isNop()) {
1095            DPRINTF(IEW, "[tid:%i]: Issue: Nop instruction encountered, "
1096                    "skipping.\n", tid);
1097
1098            inst->setIssued();
1099            inst->setExecuted();
1100            inst->setCanCommit();
1101
1102            instQueue.recordProducer(inst);
1103
1104            iewExecutedNop[tid]++;
1105
1106            add_to_iq = false;
1107        } else if (inst->isExecuted()) {
1108            assert(0 && "Instruction shouldn't be executed.\n");
1109            DPRINTF(IEW, "Issue: Executed branch encountered, "
1110                    "skipping.\n");
1111
1112            inst->setIssued();
1113            inst->setCanCommit();
1114
1115            instQueue.recordProducer(inst);
1116
1117            add_to_iq = false;
1118        } else {
1119            add_to_iq = true;
1120        }
1121        if (inst->isNonSpeculative()) {
1122            DPRINTF(IEW, "[tid:%i]: Issue: Nonspeculative instruction "
1123                    "encountered, skipping.\n", tid);
1124
1125            // Same as non-speculative stores.
1126            inst->setCanCommit();
1127
1128            // Specifically insert it as nonspeculative.
1129            instQueue.insertNonSpec(inst);
1130
1131            ++iewDispNonSpecInsts;
1132
1133            add_to_iq = false;
1134        }
1135
1136        // If the instruction queue is not full, then add the
1137        // instruction.
1138        if (add_to_iq) {
1139            instQueue.insert(inst);
1140        }
1141
1142        insts_to_dispatch.pop();
1143
1144        toRename->iewInfo[tid].dispatched++;
1145
1146        ++iewDispatchedInsts;
1147
1148#if TRACING_ON
1149        inst->dispatchTick = curTick() - inst->fetchTick;
1150#endif
1151        ppDispatch->notify(inst);
1152    }
1153
1154    if (!insts_to_dispatch.empty()) {
1155        DPRINTF(IEW,"[tid:%i]: Issue: Bandwidth Full. Blocking.\n", tid);
1156        block(tid);
1157        toRename->iewUnblock[tid] = false;
1158    }
1159
1160    if (dispatchStatus[tid] == Idle && dis_num_inst) {
1161        dispatchStatus[tid] = Running;
1162
1163        updatedQueues = true;
1164    }
1165
1166    dis_num_inst = 0;
1167}
1168
1169template <class Impl>
1170void
1171DefaultIEW<Impl>::printAvailableInsts()
1172{
1173    int inst = 0;
1174
1175    std::cout << "Available Instructions: ";
1176
1177    while (fromIssue->insts[inst]) {
1178
1179        if (inst%3==0) std::cout << "\n\t";
1180
1181        std::cout << "PC: " << fromIssue->insts[inst]->pcState()
1182             << " TN: " << fromIssue->insts[inst]->threadNumber
1183             << " SN: " << fromIssue->insts[inst]->seqNum << " | ";
1184
1185        inst++;
1186
1187    }
1188
1189    std::cout << "\n";
1190}
1191
1192template <class Impl>
1193void
1194DefaultIEW<Impl>::executeInsts()
1195{
1196    wbNumInst = 0;
1197    wbCycle = 0;
1198
1199    list<ThreadID>::iterator threads = activeThreads->begin();
1200    list<ThreadID>::iterator end = activeThreads->end();
1201
1202    while (threads != end) {
1203        ThreadID tid = *threads++;
1204        fetchRedirect[tid] = false;
1205    }
1206
1207    // Uncomment this if you want to see all available instructions.
1208    // @todo This doesn't actually work anymore, we should fix it.
1209//    printAvailableInsts();
1210
1211    // Execute/writeback any instructions that are available.
1212    int insts_to_execute = fromIssue->size;
1213    int inst_num = 0;
1214    for (; inst_num < insts_to_execute;
1215          ++inst_num) {
1216
1217        DPRINTF(IEW, "Execute: Executing instructions from IQ.\n");
1218
1219        DynInstPtr inst = instQueue.getInstToExecute();
1220
1221        DPRINTF(IEW, "Execute: Processing PC %s, [tid:%i] [sn:%i].\n",
1222                inst->pcState(), inst->threadNumber,inst->seqNum);
1223
1224        // Check if the instruction is squashed; if so then skip it
1225        if (inst->isSquashed()) {
1226            DPRINTF(IEW, "Execute: Instruction was squashed. PC: %s, [tid:%i]"
1227                         " [sn:%i]\n", inst->pcState(), inst->threadNumber,
1228                         inst->seqNum);
1229
1230            // Consider this instruction executed so that commit can go
1231            // ahead and retire the instruction.
1232            inst->setExecuted();
1233
1234            // Not sure if I should set this here or just let commit try to
1235            // commit any squashed instructions.  I like the latter a bit more.
1236            inst->setCanCommit();
1237
1238            ++iewExecSquashedInsts;
1239
1240            continue;
1241        }
1242
1243        Fault fault = NoFault;
1244
1245        // Execute instruction.
1246        // Note that if the instruction faults, it will be handled
1247        // at the commit stage.
1248        if (inst->isMemRef()) {
1249            DPRINTF(IEW, "Execute: Calculating address for memory "
1250                    "reference.\n");
1251
1252            // Tell the LDSTQ to execute this instruction (if it is a load).
1253            if (inst->isLoad()) {
1254                // Loads will mark themselves as executed, and their writeback
1255                // event adds the instruction to the queue to commit
1256                fault = ldstQueue.executeLoad(inst);
1257
1258                if (inst->isTranslationDelayed() &&
1259                    fault == NoFault) {
1260                    // A hw page table walk is currently going on; the
1261                    // instruction must be deferred.
1262                    DPRINTF(IEW, "Execute: Delayed translation, deferring "
1263                            "load.\n");
1264                    instQueue.deferMemInst(inst);
1265                    continue;
1266                }
1267
1268                if (inst->isDataPrefetch() || inst->isInstPrefetch()) {
1269                    inst->fault = NoFault;
1270                }
1271            } else if (inst->isStore()) {
1272                fault = ldstQueue.executeStore(inst);
1273
1274                if (inst->isTranslationDelayed() &&
1275                    fault == NoFault) {
1276                    // A hw page table walk is currently going on; the
1277                    // instruction must be deferred.
1278                    DPRINTF(IEW, "Execute: Delayed translation, deferring "
1279                            "store.\n");
1280                    instQueue.deferMemInst(inst);
1281                    continue;
1282                }
1283
1284                // If the store had a fault then it may not have a mem req
1285                if (fault != NoFault || !inst->readPredicate() ||
1286                        !inst->isStoreConditional()) {
1287                    // If the instruction faulted, then we need to send it along
1288                    // to commit without the instruction completing.
1289                    // Send this instruction to commit, also make sure iew stage
1290                    // realizes there is activity.
1291                    inst->setExecuted();
1292                    instToCommit(inst);
1293                    activityThisCycle();
1294                }
1295
1296                // Store conditionals will mark themselves as
1297                // executed, and their writeback event will add the
1298                // instruction to the queue to commit.
1299            } else {
1300                panic("Unexpected memory type!\n");
1301            }
1302
1303        } else {
1304            // If the instruction has already faulted, then skip executing it.
1305            // Such case can happen when it faulted during ITLB translation.
1306            // If we execute the instruction (even if it's a nop) the fault
1307            // will be replaced and we will lose it.
1308            if (inst->getFault() == NoFault) {
1309                inst->execute();
1310                if (!inst->readPredicate())
1311                    inst->forwardOldRegs();
1312            }
1313
1314            inst->setExecuted();
1315
1316            instToCommit(inst);
1317        }
1318
1319        updateExeInstStats(inst);
1320
1321        // Check if branch prediction was correct, if not then we need
1322        // to tell commit to squash in flight instructions.  Only
1323        // handle this if there hasn't already been something that
1324        // redirects fetch in this group of instructions.
1325
1326        // This probably needs to prioritize the redirects if a different
1327        // scheduler is used.  Currently the scheduler schedules the oldest
1328        // instruction first, so the branch resolution order will be correct.
1329        ThreadID tid = inst->threadNumber;
1330
1331        if (!fetchRedirect[tid] ||
1332            !toCommit->squash[tid] ||
1333            toCommit->squashedSeqNum[tid] > inst->seqNum) {
1334
1335            // Prevent testing for misprediction on load instructions,
1336            // that have not been executed.
1337            bool loadNotExecuted = !inst->isExecuted() && inst->isLoad();
1338
1339            if (inst->mispredicted() && !loadNotExecuted) {
1340                fetchRedirect[tid] = true;
1341
1342                DPRINTF(IEW, "Execute: Branch mispredict detected.\n");
1343                DPRINTF(IEW, "Predicted target was PC: %s.\n",
1344                        inst->readPredTarg());
1345                DPRINTF(IEW, "Execute: Redirecting fetch to PC: %s.\n",
1346                        inst->pcState());
1347                // If incorrect, then signal the ROB that it must be squashed.
1348                squashDueToBranch(inst, tid);
1349
1350                ppMispredict->notify(inst);
1351
1352                if (inst->readPredTaken()) {
1353                    predictedTakenIncorrect++;
1354                } else {
1355                    predictedNotTakenIncorrect++;
1356                }
1357            } else if (ldstQueue.violation(tid)) {
1358                assert(inst->isMemRef());
1359                // If there was an ordering violation, then get the
1360                // DynInst that caused the violation.  Note that this
1361                // clears the violation signal.
1362                DynInstPtr violator;
1363                violator = ldstQueue.getMemDepViolator(tid);
1364
1365                DPRINTF(IEW, "LDSTQ detected a violation. Violator PC: %s "
1366                        "[sn:%lli], inst PC: %s [sn:%lli]. Addr is: %#x.\n",
1367                        violator->pcState(), violator->seqNum,
1368                        inst->pcState(), inst->seqNum, inst->physEffAddr);
1369
1370                fetchRedirect[tid] = true;
1371
1372                // Tell the instruction queue that a violation has occured.
1373                instQueue.violation(inst, violator);
1374
1375                // Squash.
1376                squashDueToMemOrder(violator, tid);
1377
1378                ++memOrderViolationEvents;
1379            } else if (ldstQueue.loadBlocked(tid) &&
1380                       !ldstQueue.isLoadBlockedHandled(tid)) {
1381                fetchRedirect[tid] = true;
1382
1383                DPRINTF(IEW, "Load operation couldn't execute because the "
1384                        "memory system is blocked.  PC: %s [sn:%lli]\n",
1385                        inst->pcState(), inst->seqNum);
1386
1387                squashDueToMemBlocked(inst, tid);
1388            }
1389        } else {
1390            // Reset any state associated with redirects that will not
1391            // be used.
1392            if (ldstQueue.violation(tid)) {
1393                assert(inst->isMemRef());
1394
1395                DynInstPtr violator = ldstQueue.getMemDepViolator(tid);
1396
1397                DPRINTF(IEW, "LDSTQ detected a violation.  Violator PC: "
1398                        "%s, inst PC: %s.  Addr is: %#x.\n",
1399                        violator->pcState(), inst->pcState(),
1400                        inst->physEffAddr);
1401                DPRINTF(IEW, "Violation will not be handled because "
1402                        "already squashing\n");
1403
1404                ++memOrderViolationEvents;
1405            }
1406            if (ldstQueue.loadBlocked(tid) &&
1407                !ldstQueue.isLoadBlockedHandled(tid)) {
1408                DPRINTF(IEW, "Load operation couldn't execute because the "
1409                        "memory system is blocked.  PC: %s [sn:%lli]\n",
1410                        inst->pcState(), inst->seqNum);
1411                DPRINTF(IEW, "Blocked load will not be handled because "
1412                        "already squashing\n");
1413
1414                ldstQueue.setLoadBlockedHandled(tid);
1415            }
1416
1417        }
1418    }
1419
1420    // Update and record activity if we processed any instructions.
1421    if (inst_num) {
1422        if (exeStatus == Idle) {
1423            exeStatus = Running;
1424        }
1425
1426        updatedQueues = true;
1427
1428        cpu->activityThisCycle();
1429    }
1430
1431    // Need to reset this in case a writeback event needs to write into the
1432    // iew queue.  That way the writeback event will write into the correct
1433    // spot in the queue.
1434    wbNumInst = 0;
1435
1436}
1437
1438template <class Impl>
1439void
1440DefaultIEW<Impl>::writebackInsts()
1441{
1442    // Loop through the head of the time buffer and wake any
1443    // dependents.  These instructions are about to write back.  Also
1444    // mark scoreboard that this instruction is finally complete.
1445    // Either have IEW have direct access to scoreboard, or have this
1446    // as part of backwards communication.
1447    for (int inst_num = 0; inst_num < wbWidth &&
1448             toCommit->insts[inst_num]; inst_num++) {
1449        DynInstPtr inst = toCommit->insts[inst_num];
1450        ThreadID tid = inst->threadNumber;
1451
1452        DPRINTF(IEW, "Sending instructions to commit, [sn:%lli] PC %s.\n",
1453                inst->seqNum, inst->pcState());
1454
1455        iewInstsToCommit[tid]++;
1456
1457        // Some instructions will be sent to commit without having
1458        // executed because they need commit to handle them.
1459        // E.g. Uncached loads have not actually executed when they
1460        // are first sent to commit.  Instead commit must tell the LSQ
1461        // when it's ready to execute the uncached load.
1462        if (!inst->isSquashed() && inst->isExecuted() && inst->getFault() == NoFault) {
1463            int dependents = instQueue.wakeDependents(inst);
1464
1465            for (int i = 0; i < inst->numDestRegs(); i++) {
1466                //mark as Ready
1467                DPRINTF(IEW,"Setting Destination Register %i\n",
1468                        inst->renamedDestRegIdx(i));
1469                scoreboard->setReg(inst->renamedDestRegIdx(i));
1470            }
1471
1472            if (dependents) {
1473                producerInst[tid]++;
1474                consumerInst[tid]+= dependents;
1475            }
1476            writebackCount[tid]++;
1477        }
1478    }
1479}
1480
1481template<class Impl>
1482void
1483DefaultIEW<Impl>::tick()
1484{
1485    wbNumInst = 0;
1486    wbCycle = 0;
1487
1488    wroteToTimeBuffer = false;
1489    updatedQueues = false;
1490
1491    sortInsts();
1492
1493    // Free function units marked as being freed this cycle.
1494    fuPool->processFreeUnits();
1495
1496    list<ThreadID>::iterator threads = activeThreads->begin();
1497    list<ThreadID>::iterator end = activeThreads->end();
1498
1499    // Check stall and squash signals, dispatch any instructions.
1500    while (threads != end) {
1501        ThreadID tid = *threads++;
1502
1503        DPRINTF(IEW,"Issue: Processing [tid:%i]\n",tid);
1504
1505        checkSignalsAndUpdate(tid);
1506        dispatch(tid);
1507    }
1508
1509    if (exeStatus != Squashing) {
1510        executeInsts();
1511
1512        writebackInsts();
1513
1514        // Have the instruction queue try to schedule any ready instructions.
1515        // (In actuality, this scheduling is for instructions that will
1516        // be executed next cycle.)
1517        instQueue.scheduleReadyInsts();
1518
1519        // Also should advance its own time buffers if the stage ran.
1520        // Not the best place for it, but this works (hopefully).
1521        issueToExecQueue.advance();
1522    }
1523
1524    bool broadcast_free_entries = false;
1525
1526    if (updatedQueues || exeStatus == Running || updateLSQNextCycle) {
1527        exeStatus = Idle;
1528        updateLSQNextCycle = false;
1529
1530        broadcast_free_entries = true;
1531    }
1532
1533    // Writeback any stores using any leftover bandwidth.
1534    ldstQueue.writebackStores();
1535
1536    // Check the committed load/store signals to see if there's a load
1537    // or store to commit.  Also check if it's being told to execute a
1538    // nonspeculative instruction.
1539    // This is pretty inefficient...
1540
1541    threads = activeThreads->begin();
1542    while (threads != end) {
1543        ThreadID tid = (*threads++);
1544
1545        DPRINTF(IEW,"Processing [tid:%i]\n",tid);
1546
1547        // Update structures based on instructions committed.
1548        if (fromCommit->commitInfo[tid].doneSeqNum != 0 &&
1549            !fromCommit->commitInfo[tid].squash &&
1550            !fromCommit->commitInfo[tid].robSquashing) {
1551
1552            ldstQueue.commitStores(fromCommit->commitInfo[tid].doneSeqNum,tid);
1553
1554            ldstQueue.commitLoads(fromCommit->commitInfo[tid].doneSeqNum,tid);
1555
1556            updateLSQNextCycle = true;
1557            instQueue.commit(fromCommit->commitInfo[tid].doneSeqNum,tid);
1558        }
1559
1560        if (fromCommit->commitInfo[tid].nonSpecSeqNum != 0) {
1561
1562            //DPRINTF(IEW,"NonspecInst from thread %i",tid);
1563            if (fromCommit->commitInfo[tid].uncached) {
1564                instQueue.replayMemInst(fromCommit->commitInfo[tid].uncachedLoad);
1565                fromCommit->commitInfo[tid].uncachedLoad->setAtCommit();
1566            } else {
1567                instQueue.scheduleNonSpec(
1568                    fromCommit->commitInfo[tid].nonSpecSeqNum);
1569            }
1570        }
1571
1572        if (broadcast_free_entries) {
1573            toFetch->iewInfo[tid].iqCount =
1574                instQueue.getCount(tid);
1575            toFetch->iewInfo[tid].ldstqCount =
1576                ldstQueue.getCount(tid);
1577
1578            toRename->iewInfo[tid].usedIQ = true;
1579            toRename->iewInfo[tid].freeIQEntries =
1580                instQueue.numFreeEntries(tid);
1581            toRename->iewInfo[tid].usedLSQ = true;
1582
1583            toRename->iewInfo[tid].freeLQEntries =
1584                ldstQueue.numFreeLoadEntries(tid);
1585            toRename->iewInfo[tid].freeSQEntries =
1586                ldstQueue.numFreeStoreEntries(tid);
1587
1588            wroteToTimeBuffer = true;
1589        }
1590
1591        DPRINTF(IEW, "[tid:%i], Dispatch dispatched %i instructions.\n",
1592                tid, toRename->iewInfo[tid].dispatched);
1593    }
1594
1595    DPRINTF(IEW, "IQ has %i free entries (Can schedule: %i).  "
1596            "LQ has %i free entries. SQ has %i free entries.\n",
1597            instQueue.numFreeEntries(), instQueue.hasReadyInsts(),
1598            ldstQueue.numFreeLoadEntries(), ldstQueue.numFreeStoreEntries());
1599
1600    updateStatus();
1601
1602    if (wroteToTimeBuffer) {
1603        DPRINTF(Activity, "Activity this cycle.\n");
1604        cpu->activityThisCycle();
1605    }
1606}
1607
1608template <class Impl>
1609void
1610DefaultIEW<Impl>::updateExeInstStats(DynInstPtr &inst)
1611{
1612    ThreadID tid = inst->threadNumber;
1613
1614    iewExecutedInsts++;
1615
1616#if TRACING_ON
1617    if (DTRACE(O3PipeView)) {
1618        inst->completeTick = curTick() - inst->fetchTick;
1619    }
1620#endif
1621
1622    //
1623    //  Control operations
1624    //
1625    if (inst->isControl())
1626        iewExecutedBranches[tid]++;
1627
1628    //
1629    //  Memory operations
1630    //
1631    if (inst->isMemRef()) {
1632        iewExecutedRefs[tid]++;
1633
1634        if (inst->isLoad()) {
1635            iewExecLoadInsts[tid]++;
1636        }
1637    }
1638}
1639
1640template <class Impl>
1641void
1642DefaultIEW<Impl>::checkMisprediction(DynInstPtr &inst)
1643{
1644    ThreadID tid = inst->threadNumber;
1645
1646    if (!fetchRedirect[tid] ||
1647        !toCommit->squash[tid] ||
1648        toCommit->squashedSeqNum[tid] > inst->seqNum) {
1649
1650        if (inst->mispredicted()) {
1651            fetchRedirect[tid] = true;
1652
1653            DPRINTF(IEW, "Execute: Branch mispredict detected.\n");
1654            DPRINTF(IEW, "Predicted target was PC:%#x, NPC:%#x.\n",
1655                    inst->predInstAddr(), inst->predNextInstAddr());
1656            DPRINTF(IEW, "Execute: Redirecting fetch to PC: %#x,"
1657                    " NPC: %#x.\n", inst->nextInstAddr(),
1658                    inst->nextInstAddr());
1659            // If incorrect, then signal the ROB that it must be squashed.
1660            squashDueToBranch(inst, tid);
1661
1662            if (inst->readPredTaken()) {
1663                predictedTakenIncorrect++;
1664            } else {
1665                predictedNotTakenIncorrect++;
1666            }
1667        }
1668    }
1669}
1670
1671#endif//__CPU_O3_IEW_IMPL_IMPL_HH__
1672