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