inst_queue_impl.hh revision 5606:6da7a58b0bc8
1/*
2 * Copyright (c) 2004-2006 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Kevin Lim
29 *          Korey Sewell
30 */
31
32#include <limits>
33#include <vector>
34
35#include "cpu/o3/fu_pool.hh"
36#include "cpu/o3/inst_queue.hh"
37#include "enums/OpClass.hh"
38#include "sim/core.hh"
39
40#include "params/DerivO3CPU.hh"
41
42template <class Impl>
43InstructionQueue<Impl>::FUCompletion::FUCompletion(DynInstPtr &_inst,
44    int fu_idx, InstructionQueue<Impl> *iq_ptr)
45    : Event(Stat_Event_Pri), inst(_inst), fuIdx(fu_idx), iqPtr(iq_ptr),
46      freeFU(false)
47{
48    this->setFlags(Event::AutoDelete);
49}
50
51template <class Impl>
52void
53InstructionQueue<Impl>::FUCompletion::process()
54{
55    iqPtr->processFUCompletion(inst, freeFU ? fuIdx : -1);
56    inst = NULL;
57}
58
59
60template <class Impl>
61const char *
62InstructionQueue<Impl>::FUCompletion::description() const
63{
64    return "Functional unit completion";
65}
66
67template <class Impl>
68InstructionQueue<Impl>::InstructionQueue(O3CPU *cpu_ptr, IEW *iew_ptr,
69                                         DerivO3CPUParams *params)
70    : cpu(cpu_ptr),
71      iewStage(iew_ptr),
72      fuPool(params->fuPool),
73      numEntries(params->numIQEntries),
74      totalWidth(params->issueWidth),
75      numPhysIntRegs(params->numPhysIntRegs),
76      numPhysFloatRegs(params->numPhysFloatRegs),
77      commitToIEWDelay(params->commitToIEWDelay)
78{
79    assert(fuPool);
80
81    switchedOut = false;
82
83    numThreads = params->numThreads;
84
85    // Set the number of physical registers as the number of int + float
86    numPhysRegs = numPhysIntRegs + numPhysFloatRegs;
87
88    //Create an entry for each physical register within the
89    //dependency graph.
90    dependGraph.resize(numPhysRegs);
91
92    // Resize the register scoreboard.
93    regScoreboard.resize(numPhysRegs);
94
95    //Initialize Mem Dependence Units
96    for (int i = 0; i < numThreads; i++) {
97        memDepUnit[i].init(params,i);
98        memDepUnit[i].setIQ(this);
99    }
100
101    resetState();
102
103    std::string policy = params->smtIQPolicy;
104
105    //Convert string to lowercase
106    std::transform(policy.begin(), policy.end(), policy.begin(),
107                   (int(*)(int)) tolower);
108
109    //Figure out resource sharing policy
110    if (policy == "dynamic") {
111        iqPolicy = Dynamic;
112
113        //Set Max Entries to Total ROB Capacity
114        for (int i = 0; i < numThreads; i++) {
115            maxEntries[i] = numEntries;
116        }
117
118    } else if (policy == "partitioned") {
119        iqPolicy = Partitioned;
120
121        //@todo:make work if part_amt doesnt divide evenly.
122        int part_amt = numEntries / numThreads;
123
124        //Divide ROB up evenly
125        for (int i = 0; i < numThreads; i++) {
126            maxEntries[i] = part_amt;
127        }
128
129        DPRINTF(IQ, "IQ sharing policy set to Partitioned:"
130                "%i entries per thread.\n",part_amt);
131    } else if (policy == "threshold") {
132        iqPolicy = Threshold;
133
134        double threshold =  (double)params->smtIQThreshold / 100;
135
136        int thresholdIQ = (int)((double)threshold * numEntries);
137
138        //Divide up by threshold amount
139        for (int i = 0; i < numThreads; i++) {
140            maxEntries[i] = thresholdIQ;
141        }
142
143        DPRINTF(IQ, "IQ sharing policy set to Threshold:"
144                "%i entries per thread.\n",thresholdIQ);
145   } else {
146       assert(0 && "Invalid IQ Sharing Policy.Options Are:{Dynamic,"
147              "Partitioned, Threshold}");
148   }
149}
150
151template <class Impl>
152InstructionQueue<Impl>::~InstructionQueue()
153{
154    dependGraph.reset();
155#ifdef DEBUG
156    cprintf("Nodes traversed: %i, removed: %i\n",
157            dependGraph.nodesTraversed, dependGraph.nodesRemoved);
158#endif
159}
160
161template <class Impl>
162std::string
163InstructionQueue<Impl>::name() const
164{
165    return cpu->name() + ".iq";
166}
167
168template <class Impl>
169void
170InstructionQueue<Impl>::regStats()
171{
172    using namespace Stats;
173    iqInstsAdded
174        .name(name() + ".iqInstsAdded")
175        .desc("Number of instructions added to the IQ (excludes non-spec)")
176        .prereq(iqInstsAdded);
177
178    iqNonSpecInstsAdded
179        .name(name() + ".iqNonSpecInstsAdded")
180        .desc("Number of non-speculative instructions added to the IQ")
181        .prereq(iqNonSpecInstsAdded);
182
183    iqInstsIssued
184        .name(name() + ".iqInstsIssued")
185        .desc("Number of instructions issued")
186        .prereq(iqInstsIssued);
187
188    iqIntInstsIssued
189        .name(name() + ".iqIntInstsIssued")
190        .desc("Number of integer instructions issued")
191        .prereq(iqIntInstsIssued);
192
193    iqFloatInstsIssued
194        .name(name() + ".iqFloatInstsIssued")
195        .desc("Number of float instructions issued")
196        .prereq(iqFloatInstsIssued);
197
198    iqBranchInstsIssued
199        .name(name() + ".iqBranchInstsIssued")
200        .desc("Number of branch instructions issued")
201        .prereq(iqBranchInstsIssued);
202
203    iqMemInstsIssued
204        .name(name() + ".iqMemInstsIssued")
205        .desc("Number of memory instructions issued")
206        .prereq(iqMemInstsIssued);
207
208    iqMiscInstsIssued
209        .name(name() + ".iqMiscInstsIssued")
210        .desc("Number of miscellaneous instructions issued")
211        .prereq(iqMiscInstsIssued);
212
213    iqSquashedInstsIssued
214        .name(name() + ".iqSquashedInstsIssued")
215        .desc("Number of squashed instructions issued")
216        .prereq(iqSquashedInstsIssued);
217
218    iqSquashedInstsExamined
219        .name(name() + ".iqSquashedInstsExamined")
220        .desc("Number of squashed instructions iterated over during squash;"
221              " mainly for profiling")
222        .prereq(iqSquashedInstsExamined);
223
224    iqSquashedOperandsExamined
225        .name(name() + ".iqSquashedOperandsExamined")
226        .desc("Number of squashed operands that are examined and possibly "
227              "removed from graph")
228        .prereq(iqSquashedOperandsExamined);
229
230    iqSquashedNonSpecRemoved
231        .name(name() + ".iqSquashedNonSpecRemoved")
232        .desc("Number of squashed non-spec instructions that were removed")
233        .prereq(iqSquashedNonSpecRemoved);
234/*
235    queueResDist
236        .init(Num_OpClasses, 0, 99, 2)
237        .name(name() + ".IQ:residence:")
238        .desc("cycles from dispatch to issue")
239        .flags(total | pdf | cdf )
240        ;
241    for (int i = 0; i < Num_OpClasses; ++i) {
242        queueResDist.subname(i, opClassStrings[i]);
243    }
244*/
245    numIssuedDist
246        .init(0,totalWidth,1)
247        .name(name() + ".ISSUE:issued_per_cycle")
248        .desc("Number of insts issued each cycle")
249        .flags(pdf)
250        ;
251/*
252    dist_unissued
253        .init(Num_OpClasses+2)
254        .name(name() + ".ISSUE:unissued_cause")
255        .desc("Reason ready instruction not issued")
256        .flags(pdf | dist)
257        ;
258    for (int i=0; i < (Num_OpClasses + 2); ++i) {
259        dist_unissued.subname(i, unissued_names[i]);
260    }
261*/
262    statIssuedInstType
263        .init(numThreads,Enums::Num_OpClass)
264        .name(name() + ".ISSUE:FU_type")
265        .desc("Type of FU issued")
266        .flags(total | pdf | dist)
267        ;
268    statIssuedInstType.ysubnames(Enums::OpClassStrings);
269
270    //
271    //  How long did instructions for a particular FU type wait prior to issue
272    //
273/*
274    issueDelayDist
275        .init(Num_OpClasses,0,99,2)
276        .name(name() + ".ISSUE:")
277        .desc("cycles from operands ready to issue")
278        .flags(pdf | cdf)
279        ;
280
281    for (int i=0; i<Num_OpClasses; ++i) {
282        std::stringstream subname;
283        subname << opClassStrings[i] << "_delay";
284        issueDelayDist.subname(i, subname.str());
285    }
286*/
287    issueRate
288        .name(name() + ".ISSUE:rate")
289        .desc("Inst issue rate")
290        .flags(total)
291        ;
292    issueRate = iqInstsIssued / cpu->numCycles;
293
294    statFuBusy
295        .init(Num_OpClasses)
296        .name(name() + ".ISSUE:fu_full")
297        .desc("attempts to use FU when none available")
298        .flags(pdf | dist)
299        ;
300    for (int i=0; i < Num_OpClasses; ++i) {
301        statFuBusy.subname(i, Enums::OpClassStrings[i]);
302    }
303
304    fuBusy
305        .init(numThreads)
306        .name(name() + ".ISSUE:fu_busy_cnt")
307        .desc("FU busy when requested")
308        .flags(total)
309        ;
310
311    fuBusyRate
312        .name(name() + ".ISSUE:fu_busy_rate")
313        .desc("FU busy rate (busy events/executed inst)")
314        .flags(total)
315        ;
316    fuBusyRate = fuBusy / iqInstsIssued;
317
318    for ( int i=0; i < numThreads; i++) {
319        // Tell mem dependence unit to reg stats as well.
320        memDepUnit[i].regStats();
321    }
322}
323
324template <class Impl>
325void
326InstructionQueue<Impl>::resetState()
327{
328    //Initialize thread IQ counts
329    for (int i = 0; i <numThreads; i++) {
330        count[i] = 0;
331        instList[i].clear();
332    }
333
334    // Initialize the number of free IQ entries.
335    freeEntries = numEntries;
336
337    // Note that in actuality, the registers corresponding to the logical
338    // registers start off as ready.  However this doesn't matter for the
339    // IQ as the instruction should have been correctly told if those
340    // registers are ready in rename.  Thus it can all be initialized as
341    // unready.
342    for (int i = 0; i < numPhysRegs; ++i) {
343        regScoreboard[i] = false;
344    }
345
346    for (int i = 0; i < numThreads; ++i) {
347        squashedSeqNum[i] = 0;
348    }
349
350    for (int i = 0; i < Num_OpClasses; ++i) {
351        while (!readyInsts[i].empty())
352            readyInsts[i].pop();
353        queueOnList[i] = false;
354        readyIt[i] = listOrder.end();
355    }
356    nonSpecInsts.clear();
357    listOrder.clear();
358}
359
360template <class Impl>
361void
362InstructionQueue<Impl>::setActiveThreads(std::list<unsigned> *at_ptr)
363{
364    activeThreads = at_ptr;
365}
366
367template <class Impl>
368void
369InstructionQueue<Impl>::setIssueToExecuteQueue(TimeBuffer<IssueStruct> *i2e_ptr)
370{
371      issueToExecuteQueue = i2e_ptr;
372}
373
374template <class Impl>
375void
376InstructionQueue<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
377{
378    timeBuffer = tb_ptr;
379
380    fromCommit = timeBuffer->getWire(-commitToIEWDelay);
381}
382
383template <class Impl>
384void
385InstructionQueue<Impl>::switchOut()
386{
387/*
388    if (!instList[0].empty() || (numEntries != freeEntries) ||
389        !readyInsts[0].empty() || !nonSpecInsts.empty() || !listOrder.empty()) {
390        dumpInsts();
391//        assert(0);
392    }
393*/
394    resetState();
395    dependGraph.reset();
396    instsToExecute.clear();
397    switchedOut = true;
398    for (int i = 0; i < numThreads; ++i) {
399        memDepUnit[i].switchOut();
400    }
401}
402
403template <class Impl>
404void
405InstructionQueue<Impl>::takeOverFrom()
406{
407    switchedOut = false;
408}
409
410template <class Impl>
411int
412InstructionQueue<Impl>::entryAmount(int num_threads)
413{
414    if (iqPolicy == Partitioned) {
415        return numEntries / num_threads;
416    } else {
417        return 0;
418    }
419}
420
421
422template <class Impl>
423void
424InstructionQueue<Impl>::resetEntries()
425{
426    if (iqPolicy != Dynamic || numThreads > 1) {
427        int active_threads = activeThreads->size();
428
429        std::list<unsigned>::iterator threads = activeThreads->begin();
430        std::list<unsigned>::iterator end = activeThreads->end();
431
432        while (threads != end) {
433            unsigned tid = *threads++;
434
435            if (iqPolicy == Partitioned) {
436                maxEntries[tid] = numEntries / active_threads;
437            } else if(iqPolicy == Threshold && active_threads == 1) {
438                maxEntries[tid] = numEntries;
439            }
440        }
441    }
442}
443
444template <class Impl>
445unsigned
446InstructionQueue<Impl>::numFreeEntries()
447{
448    return freeEntries;
449}
450
451template <class Impl>
452unsigned
453InstructionQueue<Impl>::numFreeEntries(unsigned tid)
454{
455    return maxEntries[tid] - count[tid];
456}
457
458// Might want to do something more complex if it knows how many instructions
459// will be issued this cycle.
460template <class Impl>
461bool
462InstructionQueue<Impl>::isFull()
463{
464    if (freeEntries == 0) {
465        return(true);
466    } else {
467        return(false);
468    }
469}
470
471template <class Impl>
472bool
473InstructionQueue<Impl>::isFull(unsigned tid)
474{
475    if (numFreeEntries(tid) == 0) {
476        return(true);
477    } else {
478        return(false);
479    }
480}
481
482template <class Impl>
483bool
484InstructionQueue<Impl>::hasReadyInsts()
485{
486    if (!listOrder.empty()) {
487        return true;
488    }
489
490    for (int i = 0; i < Num_OpClasses; ++i) {
491        if (!readyInsts[i].empty()) {
492            return true;
493        }
494    }
495
496    return false;
497}
498
499template <class Impl>
500void
501InstructionQueue<Impl>::insert(DynInstPtr &new_inst)
502{
503    // Make sure the instruction is valid
504    assert(new_inst);
505
506    DPRINTF(IQ, "Adding instruction [sn:%lli] PC %#x to the IQ.\n",
507            new_inst->seqNum, new_inst->readPC());
508
509    assert(freeEntries != 0);
510
511    instList[new_inst->threadNumber].push_back(new_inst);
512
513    --freeEntries;
514
515    new_inst->setInIQ();
516
517    // Look through its source registers (physical regs), and mark any
518    // dependencies.
519    addToDependents(new_inst);
520
521    // Have this instruction set itself as the producer of its destination
522    // register(s).
523    addToProducers(new_inst);
524
525    if (new_inst->isMemRef()) {
526        memDepUnit[new_inst->threadNumber].insert(new_inst);
527    } else {
528        addIfReady(new_inst);
529    }
530
531    ++iqInstsAdded;
532
533    count[new_inst->threadNumber]++;
534
535    assert(freeEntries == (numEntries - countInsts()));
536}
537
538template <class Impl>
539void
540InstructionQueue<Impl>::insertNonSpec(DynInstPtr &new_inst)
541{
542    // @todo: Clean up this code; can do it by setting inst as unable
543    // to issue, then calling normal insert on the inst.
544
545    assert(new_inst);
546
547    nonSpecInsts[new_inst->seqNum] = new_inst;
548
549    DPRINTF(IQ, "Adding non-speculative instruction [sn:%lli] PC %#x "
550            "to the IQ.\n",
551            new_inst->seqNum, new_inst->readPC());
552
553    assert(freeEntries != 0);
554
555    instList[new_inst->threadNumber].push_back(new_inst);
556
557    --freeEntries;
558
559    new_inst->setInIQ();
560
561    // Have this instruction set itself as the producer of its destination
562    // register(s).
563    addToProducers(new_inst);
564
565    // If it's a memory instruction, add it to the memory dependency
566    // unit.
567    if (new_inst->isMemRef()) {
568        memDepUnit[new_inst->threadNumber].insertNonSpec(new_inst);
569    }
570
571    ++iqNonSpecInstsAdded;
572
573    count[new_inst->threadNumber]++;
574
575    assert(freeEntries == (numEntries - countInsts()));
576}
577
578template <class Impl>
579void
580InstructionQueue<Impl>::insertBarrier(DynInstPtr &barr_inst)
581{
582    memDepUnit[barr_inst->threadNumber].insertBarrier(barr_inst);
583
584    insertNonSpec(barr_inst);
585}
586
587template <class Impl>
588typename Impl::DynInstPtr
589InstructionQueue<Impl>::getInstToExecute()
590{
591    assert(!instsToExecute.empty());
592    DynInstPtr inst = instsToExecute.front();
593    instsToExecute.pop_front();
594    return inst;
595}
596
597template <class Impl>
598void
599InstructionQueue<Impl>::addToOrderList(OpClass op_class)
600{
601    assert(!readyInsts[op_class].empty());
602
603    ListOrderEntry queue_entry;
604
605    queue_entry.queueType = op_class;
606
607    queue_entry.oldestInst = readyInsts[op_class].top()->seqNum;
608
609    ListOrderIt list_it = listOrder.begin();
610    ListOrderIt list_end_it = listOrder.end();
611
612    while (list_it != list_end_it) {
613        if ((*list_it).oldestInst > queue_entry.oldestInst) {
614            break;
615        }
616
617        list_it++;
618    }
619
620    readyIt[op_class] = listOrder.insert(list_it, queue_entry);
621    queueOnList[op_class] = true;
622}
623
624template <class Impl>
625void
626InstructionQueue<Impl>::moveToYoungerInst(ListOrderIt list_order_it)
627{
628    // Get iterator of next item on the list
629    // Delete the original iterator
630    // Determine if the next item is either the end of the list or younger
631    // than the new instruction.  If so, then add in a new iterator right here.
632    // If not, then move along.
633    ListOrderEntry queue_entry;
634    OpClass op_class = (*list_order_it).queueType;
635    ListOrderIt next_it = list_order_it;
636
637    ++next_it;
638
639    queue_entry.queueType = op_class;
640    queue_entry.oldestInst = readyInsts[op_class].top()->seqNum;
641
642    while (next_it != listOrder.end() &&
643           (*next_it).oldestInst < queue_entry.oldestInst) {
644        ++next_it;
645    }
646
647    readyIt[op_class] = listOrder.insert(next_it, queue_entry);
648}
649
650template <class Impl>
651void
652InstructionQueue<Impl>::processFUCompletion(DynInstPtr &inst, int fu_idx)
653{
654    DPRINTF(IQ, "Processing FU completion [sn:%lli]\n", inst->seqNum);
655    // The CPU could have been sleeping until this op completed (*extremely*
656    // long latency op).  Wake it if it was.  This may be overkill.
657    if (isSwitchedOut()) {
658        DPRINTF(IQ, "FU completion not processed, IQ is switched out [sn:%lli]\n",
659                inst->seqNum);
660        return;
661    }
662
663    iewStage->wakeCPU();
664
665    if (fu_idx > -1)
666        fuPool->freeUnitNextCycle(fu_idx);
667
668    // @todo: Ensure that these FU Completions happen at the beginning
669    // of a cycle, otherwise they could add too many instructions to
670    // the queue.
671    issueToExecuteQueue->access(-1)->size++;
672    instsToExecute.push_back(inst);
673}
674
675// @todo: Figure out a better way to remove the squashed items from the
676// lists.  Checking the top item of each list to see if it's squashed
677// wastes time and forces jumps.
678template <class Impl>
679void
680InstructionQueue<Impl>::scheduleReadyInsts()
681{
682    DPRINTF(IQ, "Attempting to schedule ready instructions from "
683            "the IQ.\n");
684
685    IssueStruct *i2e_info = issueToExecuteQueue->access(0);
686
687    // Have iterator to head of the list
688    // While I haven't exceeded bandwidth or reached the end of the list,
689    // Try to get a FU that can do what this op needs.
690    // If successful, change the oldestInst to the new top of the list, put
691    // the queue in the proper place in the list.
692    // Increment the iterator.
693    // This will avoid trying to schedule a certain op class if there are no
694    // FUs that handle it.
695    ListOrderIt order_it = listOrder.begin();
696    ListOrderIt order_end_it = listOrder.end();
697    int total_issued = 0;
698
699    while (total_issued < totalWidth &&
700           iewStage->canIssue() &&
701           order_it != order_end_it) {
702        OpClass op_class = (*order_it).queueType;
703
704        assert(!readyInsts[op_class].empty());
705
706        DynInstPtr issuing_inst = readyInsts[op_class].top();
707
708        assert(issuing_inst->seqNum == (*order_it).oldestInst);
709
710        if (issuing_inst->isSquashed()) {
711            readyInsts[op_class].pop();
712
713            if (!readyInsts[op_class].empty()) {
714                moveToYoungerInst(order_it);
715            } else {
716                readyIt[op_class] = listOrder.end();
717                queueOnList[op_class] = false;
718            }
719
720            listOrder.erase(order_it++);
721
722            ++iqSquashedInstsIssued;
723
724            continue;
725        }
726
727        int idx = -2;
728        int op_latency = 1;
729        int tid = issuing_inst->threadNumber;
730
731        if (op_class != No_OpClass) {
732            idx = fuPool->getUnit(op_class);
733
734            if (idx > -1) {
735                op_latency = fuPool->getOpLatency(op_class);
736            }
737        }
738
739        // If we have an instruction that doesn't require a FU, or a
740        // valid FU, then schedule for execution.
741        if (idx == -2 || idx != -1) {
742            if (op_latency == 1) {
743                i2e_info->size++;
744                instsToExecute.push_back(issuing_inst);
745
746                // Add the FU onto the list of FU's to be freed next
747                // cycle if we used one.
748                if (idx >= 0)
749                    fuPool->freeUnitNextCycle(idx);
750            } else {
751                int issue_latency = fuPool->getIssueLatency(op_class);
752                // Generate completion event for the FU
753                FUCompletion *execution = new FUCompletion(issuing_inst,
754                                                           idx, this);
755
756                cpu->schedule(execution, curTick + cpu->ticks(op_latency - 1));
757
758                // @todo: Enforce that issue_latency == 1 or op_latency
759                if (issue_latency > 1) {
760                    // If FU isn't pipelined, then it must be freed
761                    // upon the execution completing.
762                    execution->setFreeFU();
763                } else {
764                    // Add the FU onto the list of FU's to be freed next cycle.
765                    fuPool->freeUnitNextCycle(idx);
766                }
767            }
768
769            DPRINTF(IQ, "Thread %i: Issuing instruction PC %#x "
770                    "[sn:%lli]\n",
771                    tid, issuing_inst->readPC(),
772                    issuing_inst->seqNum);
773
774            readyInsts[op_class].pop();
775
776            if (!readyInsts[op_class].empty()) {
777                moveToYoungerInst(order_it);
778            } else {
779                readyIt[op_class] = listOrder.end();
780                queueOnList[op_class] = false;
781            }
782
783            issuing_inst->setIssued();
784            ++total_issued;
785
786            if (!issuing_inst->isMemRef()) {
787                // Memory instructions can not be freed from the IQ until they
788                // complete.
789                ++freeEntries;
790                count[tid]--;
791                issuing_inst->clearInIQ();
792            } else {
793                memDepUnit[tid].issue(issuing_inst);
794            }
795
796            listOrder.erase(order_it++);
797            statIssuedInstType[tid][op_class]++;
798            iewStage->incrWb(issuing_inst->seqNum);
799        } else {
800            statFuBusy[op_class]++;
801            fuBusy[tid]++;
802            ++order_it;
803        }
804    }
805
806    numIssuedDist.sample(total_issued);
807    iqInstsIssued+= total_issued;
808
809    // If we issued any instructions, tell the CPU we had activity.
810    if (total_issued) {
811        cpu->activityThisCycle();
812    } else {
813        DPRINTF(IQ, "Not able to schedule any instructions.\n");
814    }
815}
816
817template <class Impl>
818void
819InstructionQueue<Impl>::scheduleNonSpec(const InstSeqNum &inst)
820{
821    DPRINTF(IQ, "Marking nonspeculative instruction [sn:%lli] as ready "
822            "to execute.\n", inst);
823
824    NonSpecMapIt inst_it = nonSpecInsts.find(inst);
825
826    assert(inst_it != nonSpecInsts.end());
827
828    unsigned tid = (*inst_it).second->threadNumber;
829
830    (*inst_it).second->setAtCommit();
831
832    (*inst_it).second->setCanIssue();
833
834    if (!(*inst_it).second->isMemRef()) {
835        addIfReady((*inst_it).second);
836    } else {
837        memDepUnit[tid].nonSpecInstReady((*inst_it).second);
838    }
839
840    (*inst_it).second = NULL;
841
842    nonSpecInsts.erase(inst_it);
843}
844
845template <class Impl>
846void
847InstructionQueue<Impl>::commit(const InstSeqNum &inst, unsigned tid)
848{
849    DPRINTF(IQ, "[tid:%i]: Committing instructions older than [sn:%i]\n",
850            tid,inst);
851
852    ListIt iq_it = instList[tid].begin();
853
854    while (iq_it != instList[tid].end() &&
855           (*iq_it)->seqNum <= inst) {
856        ++iq_it;
857        instList[tid].pop_front();
858    }
859
860    assert(freeEntries == (numEntries - countInsts()));
861}
862
863template <class Impl>
864int
865InstructionQueue<Impl>::wakeDependents(DynInstPtr &completed_inst)
866{
867    int dependents = 0;
868
869    DPRINTF(IQ, "Waking dependents of completed instruction.\n");
870
871    assert(!completed_inst->isSquashed());
872
873    // Tell the memory dependence unit to wake any dependents on this
874    // instruction if it is a memory instruction.  Also complete the memory
875    // instruction at this point since we know it executed without issues.
876    // @todo: Might want to rename "completeMemInst" to something that
877    // indicates that it won't need to be replayed, and call this
878    // earlier.  Might not be a big deal.
879    if (completed_inst->isMemRef()) {
880        memDepUnit[completed_inst->threadNumber].wakeDependents(completed_inst);
881        completeMemInst(completed_inst);
882    } else if (completed_inst->isMemBarrier() ||
883               completed_inst->isWriteBarrier()) {
884        memDepUnit[completed_inst->threadNumber].completeBarrier(completed_inst);
885    }
886
887    for (int dest_reg_idx = 0;
888         dest_reg_idx < completed_inst->numDestRegs();
889         dest_reg_idx++)
890    {
891        PhysRegIndex dest_reg =
892            completed_inst->renamedDestRegIdx(dest_reg_idx);
893
894        // Special case of uniq or control registers.  They are not
895        // handled by the IQ and thus have no dependency graph entry.
896        // @todo Figure out a cleaner way to handle this.
897        if (dest_reg >= numPhysRegs) {
898            continue;
899        }
900
901        DPRINTF(IQ, "Waking any dependents on register %i.\n",
902                (int) dest_reg);
903
904        //Go through the dependency chain, marking the registers as
905        //ready within the waiting instructions.
906        DynInstPtr dep_inst = dependGraph.pop(dest_reg);
907
908        while (dep_inst) {
909            DPRINTF(IQ, "Waking up a dependent instruction, PC%#x.\n",
910                    dep_inst->readPC());
911
912            // Might want to give more information to the instruction
913            // so that it knows which of its source registers is
914            // ready.  However that would mean that the dependency
915            // graph entries would need to hold the src_reg_idx.
916            dep_inst->markSrcRegReady();
917
918            addIfReady(dep_inst);
919
920            dep_inst = dependGraph.pop(dest_reg);
921
922            ++dependents;
923        }
924
925        // Reset the head node now that all of its dependents have
926        // been woken up.
927        assert(dependGraph.empty(dest_reg));
928        dependGraph.clearInst(dest_reg);
929
930        // Mark the scoreboard as having that register ready.
931        regScoreboard[dest_reg] = true;
932    }
933    return dependents;
934}
935
936template <class Impl>
937void
938InstructionQueue<Impl>::addReadyMemInst(DynInstPtr &ready_inst)
939{
940    OpClass op_class = ready_inst->opClass();
941
942    readyInsts[op_class].push(ready_inst);
943
944    // Will need to reorder the list if either a queue is not on the list,
945    // or it has an older instruction than last time.
946    if (!queueOnList[op_class]) {
947        addToOrderList(op_class);
948    } else if (readyInsts[op_class].top()->seqNum  <
949               (*readyIt[op_class]).oldestInst) {
950        listOrder.erase(readyIt[op_class]);
951        addToOrderList(op_class);
952    }
953
954    DPRINTF(IQ, "Instruction is ready to issue, putting it onto "
955            "the ready list, PC %#x opclass:%i [sn:%lli].\n",
956            ready_inst->readPC(), op_class, ready_inst->seqNum);
957}
958
959template <class Impl>
960void
961InstructionQueue<Impl>::rescheduleMemInst(DynInstPtr &resched_inst)
962{
963    DPRINTF(IQ, "Rescheduling mem inst [sn:%lli]\n", resched_inst->seqNum);
964    resched_inst->clearCanIssue();
965    memDepUnit[resched_inst->threadNumber].reschedule(resched_inst);
966}
967
968template <class Impl>
969void
970InstructionQueue<Impl>::replayMemInst(DynInstPtr &replay_inst)
971{
972    memDepUnit[replay_inst->threadNumber].replay(replay_inst);
973}
974
975template <class Impl>
976void
977InstructionQueue<Impl>::completeMemInst(DynInstPtr &completed_inst)
978{
979    int tid = completed_inst->threadNumber;
980
981    DPRINTF(IQ, "Completing mem instruction PC:%#x [sn:%lli]\n",
982            completed_inst->readPC(), completed_inst->seqNum);
983
984    ++freeEntries;
985
986    completed_inst->memOpDone = true;
987
988    memDepUnit[tid].completed(completed_inst);
989    count[tid]--;
990}
991
992template <class Impl>
993void
994InstructionQueue<Impl>::violation(DynInstPtr &store,
995                                  DynInstPtr &faulting_load)
996{
997    memDepUnit[store->threadNumber].violation(store, faulting_load);
998}
999
1000template <class Impl>
1001void
1002InstructionQueue<Impl>::squash(unsigned tid)
1003{
1004    DPRINTF(IQ, "[tid:%i]: Starting to squash instructions in "
1005            "the IQ.\n", tid);
1006
1007    // Read instruction sequence number of last instruction out of the
1008    // time buffer.
1009    squashedSeqNum[tid] = fromCommit->commitInfo[tid].doneSeqNum;
1010
1011    // Call doSquash if there are insts in the IQ
1012    if (count[tid] > 0) {
1013        doSquash(tid);
1014    }
1015
1016    // Also tell the memory dependence unit to squash.
1017    memDepUnit[tid].squash(squashedSeqNum[tid], tid);
1018}
1019
1020template <class Impl>
1021void
1022InstructionQueue<Impl>::doSquash(unsigned tid)
1023{
1024    // Start at the tail.
1025    ListIt squash_it = instList[tid].end();
1026    --squash_it;
1027
1028    DPRINTF(IQ, "[tid:%i]: Squashing until sequence number %i!\n",
1029            tid, squashedSeqNum[tid]);
1030
1031    // Squash any instructions younger than the squashed sequence number
1032    // given.
1033    while (squash_it != instList[tid].end() &&
1034           (*squash_it)->seqNum > squashedSeqNum[tid]) {
1035
1036        DynInstPtr squashed_inst = (*squash_it);
1037
1038        // Only handle the instruction if it actually is in the IQ and
1039        // hasn't already been squashed in the IQ.
1040        if (squashed_inst->threadNumber != tid ||
1041            squashed_inst->isSquashedInIQ()) {
1042            --squash_it;
1043            continue;
1044        }
1045
1046        if (!squashed_inst->isIssued() ||
1047            (squashed_inst->isMemRef() &&
1048             !squashed_inst->memOpDone)) {
1049
1050            DPRINTF(IQ, "[tid:%i]: Instruction [sn:%lli] PC %#x "
1051                    "squashed.\n",
1052                    tid, squashed_inst->seqNum, squashed_inst->readPC());
1053
1054            // Remove the instruction from the dependency list.
1055            if (!squashed_inst->isNonSpeculative() &&
1056                !squashed_inst->isStoreConditional() &&
1057                !squashed_inst->isMemBarrier() &&
1058                !squashed_inst->isWriteBarrier()) {
1059
1060                for (int src_reg_idx = 0;
1061                     src_reg_idx < squashed_inst->numSrcRegs();
1062                     src_reg_idx++)
1063                {
1064                    PhysRegIndex src_reg =
1065                        squashed_inst->renamedSrcRegIdx(src_reg_idx);
1066
1067                    // Only remove it from the dependency graph if it
1068                    // was placed there in the first place.
1069
1070                    // Instead of doing a linked list traversal, we
1071                    // can just remove these squashed instructions
1072                    // either at issue time, or when the register is
1073                    // overwritten.  The only downside to this is it
1074                    // leaves more room for error.
1075
1076                    if (!squashed_inst->isReadySrcRegIdx(src_reg_idx) &&
1077                        src_reg < numPhysRegs) {
1078                        dependGraph.remove(src_reg, squashed_inst);
1079                    }
1080
1081
1082                    ++iqSquashedOperandsExamined;
1083                }
1084            } else if (!squashed_inst->isStoreConditional() ||
1085                       !squashed_inst->isCompleted()) {
1086                NonSpecMapIt ns_inst_it =
1087                    nonSpecInsts.find(squashed_inst->seqNum);
1088                assert(ns_inst_it != nonSpecInsts.end());
1089                if (ns_inst_it == nonSpecInsts.end()) {
1090                    assert(squashed_inst->getFault() != NoFault);
1091                } else {
1092
1093                    (*ns_inst_it).second = NULL;
1094
1095                    nonSpecInsts.erase(ns_inst_it);
1096
1097                    ++iqSquashedNonSpecRemoved;
1098                }
1099            }
1100
1101            // Might want to also clear out the head of the dependency graph.
1102
1103            // Mark it as squashed within the IQ.
1104            squashed_inst->setSquashedInIQ();
1105
1106            // @todo: Remove this hack where several statuses are set so the
1107            // inst will flow through the rest of the pipeline.
1108            squashed_inst->setIssued();
1109            squashed_inst->setCanCommit();
1110            squashed_inst->clearInIQ();
1111
1112            //Update Thread IQ Count
1113            count[squashed_inst->threadNumber]--;
1114
1115            ++freeEntries;
1116        }
1117
1118        instList[tid].erase(squash_it--);
1119        ++iqSquashedInstsExamined;
1120    }
1121}
1122
1123template <class Impl>
1124bool
1125InstructionQueue<Impl>::addToDependents(DynInstPtr &new_inst)
1126{
1127    // Loop through the instruction's source registers, adding
1128    // them to the dependency list if they are not ready.
1129    int8_t total_src_regs = new_inst->numSrcRegs();
1130    bool return_val = false;
1131
1132    for (int src_reg_idx = 0;
1133         src_reg_idx < total_src_regs;
1134         src_reg_idx++)
1135    {
1136        // Only add it to the dependency graph if it's not ready.
1137        if (!new_inst->isReadySrcRegIdx(src_reg_idx)) {
1138            PhysRegIndex src_reg = new_inst->renamedSrcRegIdx(src_reg_idx);
1139
1140            // Check the IQ's scoreboard to make sure the register
1141            // hasn't become ready while the instruction was in flight
1142            // between stages.  Only if it really isn't ready should
1143            // it be added to the dependency graph.
1144            if (src_reg >= numPhysRegs) {
1145                continue;
1146            } else if (regScoreboard[src_reg] == false) {
1147                DPRINTF(IQ, "Instruction PC %#x has src reg %i that "
1148                        "is being added to the dependency chain.\n",
1149                        new_inst->readPC(), src_reg);
1150
1151                dependGraph.insert(src_reg, new_inst);
1152
1153                // Change the return value to indicate that something
1154                // was added to the dependency graph.
1155                return_val = true;
1156            } else {
1157                DPRINTF(IQ, "Instruction PC %#x has src reg %i that "
1158                        "became ready before it reached the IQ.\n",
1159                        new_inst->readPC(), src_reg);
1160                // Mark a register ready within the instruction.
1161                new_inst->markSrcRegReady(src_reg_idx);
1162            }
1163        }
1164    }
1165
1166    return return_val;
1167}
1168
1169template <class Impl>
1170void
1171InstructionQueue<Impl>::addToProducers(DynInstPtr &new_inst)
1172{
1173    // Nothing really needs to be marked when an instruction becomes
1174    // the producer of a register's value, but for convenience a ptr
1175    // to the producing instruction will be placed in the head node of
1176    // the dependency links.
1177    int8_t total_dest_regs = new_inst->numDestRegs();
1178
1179    for (int dest_reg_idx = 0;
1180         dest_reg_idx < total_dest_regs;
1181         dest_reg_idx++)
1182    {
1183        PhysRegIndex dest_reg = new_inst->renamedDestRegIdx(dest_reg_idx);
1184
1185        // Instructions that use the misc regs will have a reg number
1186        // higher than the normal physical registers.  In this case these
1187        // registers are not renamed, and there is no need to track
1188        // dependencies as these instructions must be executed at commit.
1189        if (dest_reg >= numPhysRegs) {
1190            continue;
1191        }
1192
1193        if (!dependGraph.empty(dest_reg)) {
1194            dependGraph.dump();
1195            panic("Dependency graph %i not empty!", dest_reg);
1196        }
1197
1198        dependGraph.setInst(dest_reg, new_inst);
1199
1200        // Mark the scoreboard to say it's not yet ready.
1201        regScoreboard[dest_reg] = false;
1202    }
1203}
1204
1205template <class Impl>
1206void
1207InstructionQueue<Impl>::addIfReady(DynInstPtr &inst)
1208{
1209    // If the instruction now has all of its source registers
1210    // available, then add it to the list of ready instructions.
1211    if (inst->readyToIssue()) {
1212
1213        //Add the instruction to the proper ready list.
1214        if (inst->isMemRef()) {
1215
1216            DPRINTF(IQ, "Checking if memory instruction can issue.\n");
1217
1218            // Message to the mem dependence unit that this instruction has
1219            // its registers ready.
1220            memDepUnit[inst->threadNumber].regsReady(inst);
1221
1222            return;
1223        }
1224
1225        OpClass op_class = inst->opClass();
1226
1227        DPRINTF(IQ, "Instruction is ready to issue, putting it onto "
1228                "the ready list, PC %#x opclass:%i [sn:%lli].\n",
1229                inst->readPC(), op_class, inst->seqNum);
1230
1231        readyInsts[op_class].push(inst);
1232
1233        // Will need to reorder the list if either a queue is not on the list,
1234        // or it has an older instruction than last time.
1235        if (!queueOnList[op_class]) {
1236            addToOrderList(op_class);
1237        } else if (readyInsts[op_class].top()->seqNum  <
1238                   (*readyIt[op_class]).oldestInst) {
1239            listOrder.erase(readyIt[op_class]);
1240            addToOrderList(op_class);
1241        }
1242    }
1243}
1244
1245template <class Impl>
1246int
1247InstructionQueue<Impl>::countInsts()
1248{
1249#if 0
1250    //ksewell:This works but definitely could use a cleaner write
1251    //with a more intuitive way of counting. Right now it's
1252    //just brute force ....
1253    // Change the #if if you want to use this method.
1254    int total_insts = 0;
1255
1256    for (int i = 0; i < numThreads; ++i) {
1257        ListIt count_it = instList[i].begin();
1258
1259        while (count_it != instList[i].end()) {
1260            if (!(*count_it)->isSquashed() && !(*count_it)->isSquashedInIQ()) {
1261                if (!(*count_it)->isIssued()) {
1262                    ++total_insts;
1263                } else if ((*count_it)->isMemRef() &&
1264                           !(*count_it)->memOpDone) {
1265                    // Loads that have not been marked as executed still count
1266                    // towards the total instructions.
1267                    ++total_insts;
1268                }
1269            }
1270
1271            ++count_it;
1272        }
1273    }
1274
1275    return total_insts;
1276#else
1277    return numEntries - freeEntries;
1278#endif
1279}
1280
1281template <class Impl>
1282void
1283InstructionQueue<Impl>::dumpLists()
1284{
1285    for (int i = 0; i < Num_OpClasses; ++i) {
1286        cprintf("Ready list %i size: %i\n", i, readyInsts[i].size());
1287
1288        cprintf("\n");
1289    }
1290
1291    cprintf("Non speculative list size: %i\n", nonSpecInsts.size());
1292
1293    NonSpecMapIt non_spec_it = nonSpecInsts.begin();
1294    NonSpecMapIt non_spec_end_it = nonSpecInsts.end();
1295
1296    cprintf("Non speculative list: ");
1297
1298    while (non_spec_it != non_spec_end_it) {
1299        cprintf("%#x [sn:%lli]", (*non_spec_it).second->readPC(),
1300                (*non_spec_it).second->seqNum);
1301        ++non_spec_it;
1302    }
1303
1304    cprintf("\n");
1305
1306    ListOrderIt list_order_it = listOrder.begin();
1307    ListOrderIt list_order_end_it = listOrder.end();
1308    int i = 1;
1309
1310    cprintf("List order: ");
1311
1312    while (list_order_it != list_order_end_it) {
1313        cprintf("%i OpClass:%i [sn:%lli] ", i, (*list_order_it).queueType,
1314                (*list_order_it).oldestInst);
1315
1316        ++list_order_it;
1317        ++i;
1318    }
1319
1320    cprintf("\n");
1321}
1322
1323
1324template <class Impl>
1325void
1326InstructionQueue<Impl>::dumpInsts()
1327{
1328    for (int i = 0; i < numThreads; ++i) {
1329        int num = 0;
1330        int valid_num = 0;
1331        ListIt inst_list_it = instList[i].begin();
1332
1333        while (inst_list_it != instList[i].end())
1334        {
1335            cprintf("Instruction:%i\n",
1336                    num);
1337            if (!(*inst_list_it)->isSquashed()) {
1338                if (!(*inst_list_it)->isIssued()) {
1339                    ++valid_num;
1340                    cprintf("Count:%i\n", valid_num);
1341                } else if ((*inst_list_it)->isMemRef() &&
1342                           !(*inst_list_it)->memOpDone) {
1343                    // Loads that have not been marked as executed
1344                    // still count towards the total instructions.
1345                    ++valid_num;
1346                    cprintf("Count:%i\n", valid_num);
1347                }
1348            }
1349
1350            cprintf("PC:%#x\n[sn:%lli]\n[tid:%i]\n"
1351                    "Issued:%i\nSquashed:%i\n",
1352                    (*inst_list_it)->readPC(),
1353                    (*inst_list_it)->seqNum,
1354                    (*inst_list_it)->threadNumber,
1355                    (*inst_list_it)->isIssued(),
1356                    (*inst_list_it)->isSquashed());
1357
1358            if ((*inst_list_it)->isMemRef()) {
1359                cprintf("MemOpDone:%i\n", (*inst_list_it)->memOpDone);
1360            }
1361
1362            cprintf("\n");
1363
1364            inst_list_it++;
1365            ++num;
1366        }
1367    }
1368
1369    cprintf("Insts to Execute list:\n");
1370
1371    int num = 0;
1372    int valid_num = 0;
1373    ListIt inst_list_it = instsToExecute.begin();
1374
1375    while (inst_list_it != instsToExecute.end())
1376    {
1377        cprintf("Instruction:%i\n",
1378                num);
1379        if (!(*inst_list_it)->isSquashed()) {
1380            if (!(*inst_list_it)->isIssued()) {
1381                ++valid_num;
1382                cprintf("Count:%i\n", valid_num);
1383            } else if ((*inst_list_it)->isMemRef() &&
1384                       !(*inst_list_it)->memOpDone) {
1385                // Loads that have not been marked as executed
1386                // still count towards the total instructions.
1387                ++valid_num;
1388                cprintf("Count:%i\n", valid_num);
1389            }
1390        }
1391
1392        cprintf("PC:%#x\n[sn:%lli]\n[tid:%i]\n"
1393                "Issued:%i\nSquashed:%i\n",
1394                (*inst_list_it)->readPC(),
1395                (*inst_list_it)->seqNum,
1396                (*inst_list_it)->threadNumber,
1397                (*inst_list_it)->isIssued(),
1398                (*inst_list_it)->isSquashed());
1399
1400        if ((*inst_list_it)->isMemRef()) {
1401            cprintf("MemOpDone:%i\n", (*inst_list_it)->memOpDone);
1402        }
1403
1404        cprintf("\n");
1405
1406        inst_list_it++;
1407        ++num;
1408    }
1409}
1410