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