inst_queue_impl.hh revision 8275:8c88a94c2f4f
12292SN/A/*
22727Sktlim@umich.edu * Copyright (c) 2011 ARM Limited
32292SN/A * All rights reserved.
42292SN/A *
52292SN/A * The license below extends only to copyright in the software and shall
62292SN/A * not be construed as granting a license to any other intellectual
72292SN/A * property including but not limited to intellectual property relating
82292SN/A * to a hardware implementation of the functionality of the software
92292SN/A * licensed hereunder.  You may use the software subject to the license
102292SN/A * terms below provided that you ensure that this notice is replicated
112292SN/A * unmodified and in its entirety in all distributions of the software,
122292SN/A * modified or unmodified, in source code or in binary form.
132292SN/A *
142292SN/A * Copyright (c) 2004-2006 The Regents of The University of Michigan
152292SN/A * All rights reserved.
162292SN/A *
172292SN/A * Redistribution and use in source and binary forms, with or without
182292SN/A * modification, are permitted provided that the following conditions are
192292SN/A * met: redistributions of source code must retain the above copyright
202292SN/A * notice, this list of conditions and the following disclaimer;
212292SN/A * redistributions in binary form must reproduce the above copyright
222292SN/A * notice, this list of conditions and the following disclaimer in the
232292SN/A * documentation and/or other materials provided with the distribution;
242292SN/A * neither the name of the copyright holders nor the names of its
252292SN/A * contributors may be used to endorse or promote products derived from
262292SN/A * this software without specific prior written permission.
272689Sktlim@umich.edu *
282689Sktlim@umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
292292SN/A * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
302292SN/A * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
312329SN/A * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
322980Sgblack@eecs.umich.edu * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
332329SN/A * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
342329SN/A * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
352292SN/A * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
362292SN/A * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
375529Snate@binkert.org * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
385529Snate@binkert.org * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
394192Sktlim@umich.edu *
404192Sktlim@umich.edu * Authors: Kevin Lim
414192Sktlim@umich.edu *          Korey Sewell
424192Sktlim@umich.edu */
434192Sktlim@umich.edu
444192Sktlim@umich.edu#include <limits>
454192Sktlim@umich.edu#include <vector>
464192Sktlim@umich.edu
474192Sktlim@umich.edu#include "cpu/o3/fu_pool.hh"
484192Sktlim@umich.edu#include "cpu/o3/inst_queue.hh"
494192Sktlim@umich.edu#include "debug/IQ.hh"
504192Sktlim@umich.edu#include "enums/OpClass.hh"
514192Sktlim@umich.edu#include "params/DerivO3CPU.hh"
522292SN/A#include "sim/core.hh"
532907Sktlim@umich.edu
542907Sktlim@umich.eduusing namespace std;
552907Sktlim@umich.edu
562907Sktlim@umich.edutemplate <class Impl>
572907Sktlim@umich.eduInstructionQueue<Impl>::FUCompletion::FUCompletion(DynInstPtr &_inst,
582907Sktlim@umich.edu    int fu_idx, InstructionQueue<Impl> *iq_ptr)
592907Sktlim@umich.edu    : Event(Stat_Event_Pri), inst(_inst), fuIdx(fu_idx), iqPtr(iq_ptr),
602907Sktlim@umich.edu      freeFU(false)
612907Sktlim@umich.edu{
622907Sktlim@umich.edu    this->setFlags(Event::AutoDelete);
632907Sktlim@umich.edu}
643639Sktlim@umich.edu
652907Sktlim@umich.edutemplate <class Impl>
662907Sktlim@umich.eduvoid
672907Sktlim@umich.eduInstructionQueue<Impl>::FUCompletion::process()
682907Sktlim@umich.edu{
692907Sktlim@umich.edu    iqPtr->processFUCompletion(inst, freeFU ? fuIdx : -1);
702907Sktlim@umich.edu    inst = NULL;
713647Srdreslin@umich.edu}
723647Srdreslin@umich.edu
733647Srdreslin@umich.edu
743647Srdreslin@umich.edutemplate <class Impl>
753647Srdreslin@umich.educonst char *
762907Sktlim@umich.eduInstructionQueue<Impl>::FUCompletion::description() const
773647Srdreslin@umich.edu{
782907Sktlim@umich.edu    return "Functional unit completion";
792907Sktlim@umich.edu}
802907Sktlim@umich.edu
812907Sktlim@umich.edutemplate <class Impl>
822907Sktlim@umich.eduInstructionQueue<Impl>::InstructionQueue(O3CPU *cpu_ptr, IEW *iew_ptr,
832907Sktlim@umich.edu                                         DerivO3CPUParams *params)
842907Sktlim@umich.edu    : cpu(cpu_ptr),
854986Ssaidi@eecs.umich.edu      iewStage(iew_ptr),
864986Ssaidi@eecs.umich.edu      fuPool(params->fuPool),
873310Srdreslin@umich.edu      numEntries(params->numIQEntries),
883310Srdreslin@umich.edu      totalWidth(params->issueWidth),
893310Srdreslin@umich.edu      numPhysIntRegs(params->numPhysIntRegs),
903310Srdreslin@umich.edu      numPhysFloatRegs(params->numPhysFloatRegs),
914895Sstever@eecs.umich.edu      commitToIEWDelay(params->commitToIEWDelay)
924895Sstever@eecs.umich.edu{
934895Sstever@eecs.umich.edu    assert(fuPool);
944895Sstever@eecs.umich.edu
953310Srdreslin@umich.edu    switchedOut = false;
962907Sktlim@umich.edu
972907Sktlim@umich.edu    numThreads = params->numThreads;
982907Sktlim@umich.edu
992907Sktlim@umich.edu    // Set the number of physical registers as the number of int + float
1002907Sktlim@umich.edu    numPhysRegs = numPhysIntRegs + numPhysFloatRegs;
1012907Sktlim@umich.edu
1022907Sktlim@umich.edu    //Create an entry for each physical register within the
1033014Srdreslin@umich.edu    //dependency graph.
1043014Srdreslin@umich.edu    dependGraph.resize(numPhysRegs);
1053014Srdreslin@umich.edu
1063014Srdreslin@umich.edu    // Resize the register scoreboard.
1073014Srdreslin@umich.edu    regScoreboard.resize(numPhysRegs);
1084985Sktlim@umich.edu
1092907Sktlim@umich.edu    //Initialize Mem Dependence Units
1102907Sktlim@umich.edu    for (ThreadID tid = 0; tid < numThreads; tid++) {
1112907Sktlim@umich.edu        memDepUnit[tid].init(params, tid);
1124985Sktlim@umich.edu        memDepUnit[tid].setIQ(this);
1132907Sktlim@umich.edu    }
1142907Sktlim@umich.edu
1152907Sktlim@umich.edu    resetState();
1165529Snate@binkert.org
1175494Sstever@gmail.com    std::string policy = params->smtIQPolicy;
1184329Sktlim@umich.edu
1194329Sktlim@umich.edu    //Convert string to lowercase
1205529Snate@binkert.org    std::transform(policy.begin(), policy.end(), policy.begin(),
1212907Sktlim@umich.edu                   (int(*)(int)) tolower);
1222292SN/A
1233647Srdreslin@umich.edu    //Figure out resource sharing policy
1243647Srdreslin@umich.edu    if (policy == "dynamic") {
1252292SN/A        iqPolicy = Dynamic;
1262292SN/A
1272292SN/A        //Set Max Entries to Total ROB Capacity
1282980Sgblack@eecs.umich.edu        for (ThreadID tid = 0; tid < numThreads; tid++) {
1292292SN/A            maxEntries[tid] = numEntries;
1302292SN/A        }
1312292SN/A
1322292SN/A    } else if (policy == "partitioned") {
1332292SN/A        iqPolicy = Partitioned;
1342292SN/A
1352292SN/A        //@todo:make work if part_amt doesnt divide evenly.
1362292SN/A        int part_amt = numEntries / numThreads;
1372292SN/A
1382292SN/A        //Divide ROB up evenly
1392292SN/A        for (ThreadID tid = 0; tid < numThreads; tid++) {
1404329Sktlim@umich.edu            maxEntries[tid] = part_amt;
1412292SN/A        }
1422292SN/A
1432292SN/A        DPRINTF(IQ, "IQ sharing policy set to Partitioned:"
1442292SN/A                "%i entries per thread.\n",part_amt);
1452292SN/A    } else if (policy == "threshold") {
1462292SN/A        iqPolicy = Threshold;
1472292SN/A
1484329Sktlim@umich.edu        double threshold =  (double)params->smtIQThreshold / 100;
1492292SN/A
1502292SN/A        int thresholdIQ = (int)((double)threshold * numEntries);
1512292SN/A
1522292SN/A        //Divide up by threshold amount
1532292SN/A        for (ThreadID tid = 0; tid < numThreads; tid++) {
1542292SN/A            maxEntries[tid] = thresholdIQ;
1552292SN/A        }
1562292SN/A
1572292SN/A        DPRINTF(IQ, "IQ sharing policy set to Threshold:"
1582292SN/A                "%i entries per thread.\n",thresholdIQ);
1592292SN/A   } else {
1602292SN/A       assert(0 && "Invalid IQ Sharing Policy.Options Are:{Dynamic,"
1612292SN/A              "Partitioned, Threshold}");
1622292SN/A   }
1634329Sktlim@umich.edu}
1642292SN/A
1652292SN/Atemplate <class Impl>
1662292SN/AInstructionQueue<Impl>::~InstructionQueue()
1672292SN/A{
1682292SN/A    dependGraph.reset();
1692292SN/A#ifdef DEBUG
1702292SN/A    cprintf("Nodes traversed: %i, removed: %i\n",
1712292SN/A            dependGraph.nodesTraversed, dependGraph.nodesRemoved);
1722292SN/A#endif
1732292SN/A}
1744329Sktlim@umich.edu
1754329Sktlim@umich.edutemplate <class Impl>
1762907Sktlim@umich.edustd::string
1772292SN/AInstructionQueue<Impl>::name() const
1782292SN/A{
1792292SN/A    return cpu->name() + ".iq";
1802292SN/A}
1812292SN/A
1822292SN/Atemplate <class Impl>
1832292SN/Avoid
1842292SN/AInstructionQueue<Impl>::regStats()
1852292SN/A{
1862292SN/A    using namespace Stats;
1872292SN/A    iqInstsAdded
1882292SN/A        .name(name() + ".iqInstsAdded")
1892292SN/A        .desc("Number of instructions added to the IQ (excludes non-spec)")
1902727Sktlim@umich.edu        .prereq(iqInstsAdded);
1912727Sktlim@umich.edu
1922727Sktlim@umich.edu    iqNonSpecInstsAdded
1932727Sktlim@umich.edu        .name(name() + ".iqNonSpecInstsAdded")
1942727Sktlim@umich.edu        .desc("Number of non-speculative instructions added to the IQ")
1952727Sktlim@umich.edu        .prereq(iqNonSpecInstsAdded);
1962727Sktlim@umich.edu
1972727Sktlim@umich.edu    iqInstsIssued
1982727Sktlim@umich.edu        .name(name() + ".iqInstsIssued")
1992727Sktlim@umich.edu        .desc("Number of instructions issued")
2002980Sgblack@eecs.umich.edu        .prereq(iqInstsIssued);
2012292SN/A
2022292SN/A    iqIntInstsIssued
2032292SN/A        .name(name() + ".iqIntInstsIssued")
2042292SN/A        .desc("Number of integer instructions issued")
2052292SN/A        .prereq(iqIntInstsIssued);
2062292SN/A
2072307SN/A    iqFloatInstsIssued
2082307SN/A        .name(name() + ".iqFloatInstsIssued")
2092307SN/A        .desc("Number of float instructions issued")
2102307SN/A        .prereq(iqFloatInstsIssued);
2112307SN/A
2122307SN/A    iqBranchInstsIssued
2132307SN/A        .name(name() + ".iqBranchInstsIssued")
2142307SN/A        .desc("Number of branch instructions issued")
2152307SN/A        .prereq(iqBranchInstsIssued);
2162307SN/A
2172307SN/A    iqMemInstsIssued
2182307SN/A        .name(name() + ".iqMemInstsIssued")
2192307SN/A        .desc("Number of memory instructions issued")
2202307SN/A        .prereq(iqMemInstsIssued);
2212307SN/A
2222307SN/A    iqMiscInstsIssued
2232307SN/A        .name(name() + ".iqMiscInstsIssued")
2242307SN/A        .desc("Number of miscellaneous instructions issued")
2252292SN/A        .prereq(iqMiscInstsIssued);
2262292SN/A
2272292SN/A    iqSquashedInstsIssued
2282292SN/A        .name(name() + ".iqSquashedInstsIssued")
2292292SN/A        .desc("Number of squashed instructions issued")
2302292SN/A        .prereq(iqSquashedInstsIssued);
2312292SN/A
2322292SN/A    iqSquashedInstsExamined
2332292SN/A        .name(name() + ".iqSquashedInstsExamined")
2342292SN/A        .desc("Number of squashed instructions iterated over during squash;"
2352292SN/A              " mainly for profiling")
2362292SN/A        .prereq(iqSquashedInstsExamined);
2372292SN/A
2382292SN/A    iqSquashedOperandsExamined
2392292SN/A        .name(name() + ".iqSquashedOperandsExamined")
2403867Sbinkertn@umich.edu        .desc("Number of squashed operands that are examined and possibly "
2412292SN/A              "removed from graph")
2422292SN/A        .prereq(iqSquashedOperandsExamined);
2432292SN/A
2442292SN/A    iqSquashedNonSpecRemoved
2452292SN/A        .name(name() + ".iqSquashedNonSpecRemoved")
2462292SN/A        .desc("Number of squashed non-spec instructions that were removed")
2472292SN/A        .prereq(iqSquashedNonSpecRemoved);
2482292SN/A/*
2492292SN/A    queueResDist
2502292SN/A        .init(Num_OpClasses, 0, 99, 2)
2512292SN/A        .name(name() + ".IQ:residence:")
2523867Sbinkertn@umich.edu        .desc("cycles from dispatch to issue")
2533867Sbinkertn@umich.edu        .flags(total | pdf | cdf )
2543867Sbinkertn@umich.edu        ;
2553867Sbinkertn@umich.edu    for (int i = 0; i < Num_OpClasses; ++i) {
2563867Sbinkertn@umich.edu        queueResDist.subname(i, opClassStrings[i]);
2573867Sbinkertn@umich.edu    }
2583867Sbinkertn@umich.edu*/
2592292SN/A    numIssuedDist
2602292SN/A        .init(0,totalWidth,1)
2612292SN/A        .name(name() + ".issued_per_cycle")
2622292SN/A        .desc("Number of insts issued each cycle")
2632292SN/A        .flags(pdf)
2642292SN/A        ;
2652292SN/A/*
2662292SN/A    dist_unissued
2672292SN/A        .init(Num_OpClasses+2)
2682292SN/A        .name(name() + ".unissued_cause")
2692292SN/A        .desc("Reason ready instruction not issued")
2702292SN/A        .flags(pdf | dist)
2712292SN/A        ;
2722292SN/A    for (int i=0; i < (Num_OpClasses + 2); ++i) {
2732292SN/A        dist_unissued.subname(i, unissued_names[i]);
2742292SN/A    }
2752292SN/A*/
2762292SN/A    statIssuedInstType
2772292SN/A        .init(numThreads,Enums::Num_OpClass)
2782292SN/A        .name(name() + ".FU_type")
2792292SN/A        .desc("Type of FU issued")
2802292SN/A        .flags(total | pdf | dist)
2812292SN/A        ;
2822292SN/A    statIssuedInstType.ysubnames(Enums::OpClassStrings);
2833867Sbinkertn@umich.edu
2843867Sbinkertn@umich.edu    //
2852292SN/A    //  How long did instructions for a particular FU type wait prior to issue
2863867Sbinkertn@umich.edu    //
2873867Sbinkertn@umich.edu/*
2882292SN/A    issueDelayDist
2892292SN/A        .init(Num_OpClasses,0,99,2)
2902292SN/A        .name(name() + ".")
2912292SN/A        .desc("cycles from operands ready to issue")
2922292SN/A        .flags(pdf | cdf)
2932292SN/A        ;
2942292SN/A
2952292SN/A    for (int i=0; i<Num_OpClasses; ++i) {
2962292SN/A        std::stringstream subname;
2972292SN/A        subname << opClassStrings[i] << "_delay";
2982292SN/A        issueDelayDist.subname(i, subname.str());
2992292SN/A    }
3002292SN/A*/
3012292SN/A    issueRate
3022292SN/A        .name(name() + ".rate")
3032292SN/A        .desc("Inst issue rate")
3042292SN/A        .flags(total)
3052292SN/A        ;
3062292SN/A    issueRate = iqInstsIssued / cpu->numCycles;
3072292SN/A
3082292SN/A    statFuBusy
3092292SN/A        .init(Num_OpClasses)
3102292SN/A        .name(name() + ".fu_full")
3112292SN/A        .desc("attempts to use FU when none available")
3122292SN/A        .flags(pdf | dist)
3132292SN/A        ;
3142292SN/A    for (int i=0; i < Num_OpClasses; ++i) {
3152292SN/A        statFuBusy.subname(i, Enums::OpClassStrings[i]);
3162292SN/A    }
3172292SN/A
3182292SN/A    fuBusy
3192292SN/A        .init(numThreads)
3202292SN/A        .name(name() + ".fu_busy_cnt")
3212292SN/A        .desc("FU busy when requested")
3222292SN/A        .flags(total)
3232292SN/A        ;
3242292SN/A
3252292SN/A    fuBusyRate
3262292SN/A        .name(name() + ".fu_busy_rate")
3272292SN/A        .desc("FU busy rate (busy events/executed inst)")
3282292SN/A        .flags(total)
3292292SN/A        ;
3302292SN/A    fuBusyRate = fuBusy / iqInstsIssued;
3312292SN/A
3322292SN/A    for (ThreadID tid = 0; tid < numThreads; tid++) {
3333867Sbinkertn@umich.edu        // Tell mem dependence unit to reg stats as well.
3343867Sbinkertn@umich.edu        memDepUnit[tid].regStats();
3352292SN/A    }
3363867Sbinkertn@umich.edu
3373867Sbinkertn@umich.edu    intInstQueueReads
3382292SN/A        .name(name() + ".int_inst_queue_reads")
3392292SN/A        .desc("Number of integer instruction queue reads")
3402329SN/A        .flags(total);
3412329SN/A
3422292SN/A    intInstQueueWrites
3432292SN/A        .name(name() + ".int_inst_queue_writes")
3442292SN/A        .desc("Number of integer instruction queue writes")
3452292SN/A        .flags(total);
3462292SN/A
3472292SN/A    intInstQueueWakeupAccesses
3482292SN/A        .name(name() + ".int_inst_queue_wakeup_accesses")
3492292SN/A        .desc("Number of integer instruction queue wakeup accesses")
3502292SN/A        .flags(total);
3512292SN/A
3522292SN/A    fpInstQueueReads
3533867Sbinkertn@umich.edu        .name(name() + ".fp_inst_queue_reads")
3543867Sbinkertn@umich.edu        .desc("Number of floating instruction queue reads")
3552292SN/A        .flags(total);
3563867Sbinkertn@umich.edu
3573867Sbinkertn@umich.edu    fpInstQueueWrites
3583867Sbinkertn@umich.edu        .name(name() + ".fp_inst_queue_writes")
3592292SN/A        .desc("Number of floating instruction queue writes")
3602292SN/A        .flags(total);
3612292SN/A
3622292SN/A    fpInstQueueWakeupQccesses
3632292SN/A        .name(name() + ".fp_inst_queue_wakeup_accesses")
3642292SN/A        .desc("Number of floating instruction queue wakeup accesses")
3652292SN/A        .flags(total);
3662292SN/A
3672292SN/A    intAluAccesses
3682292SN/A        .name(name() + ".int_alu_accesses")
3692292SN/A        .desc("Number of integer alu accesses")
3702292SN/A        .flags(total);
3712292SN/A
3723867Sbinkertn@umich.edu    fpAluAccesses
3733867Sbinkertn@umich.edu        .name(name() + ".fp_alu_accesses")
3742292SN/A        .desc("Number of floating point alu accesses")
3753867Sbinkertn@umich.edu        .flags(total);
3763867Sbinkertn@umich.edu
3773867Sbinkertn@umich.edu}
3782292SN/A
3792292SN/Atemplate <class Impl>
3802292SN/Avoid
3812292SN/AInstructionQueue<Impl>::resetState()
3822292SN/A{
3832292SN/A    //Initialize thread IQ counts
3842292SN/A    for (ThreadID tid = 0; tid <numThreads; tid++) {
3852292SN/A        count[tid] = 0;
3862292SN/A        instList[tid].clear();
3872292SN/A    }
3882292SN/A
3892292SN/A    // Initialize the number of free IQ entries.
3903867Sbinkertn@umich.edu    freeEntries = numEntries;
3913867Sbinkertn@umich.edu
3922292SN/A    // Note that in actuality, the registers corresponding to the logical
3933867Sbinkertn@umich.edu    // registers start off as ready.  However this doesn't matter for the
3943867Sbinkertn@umich.edu    // IQ as the instruction should have been correctly told if those
3953867Sbinkertn@umich.edu    // registers are ready in rename.  Thus it can all be initialized as
3962292SN/A    // unready.
3972292SN/A    for (int i = 0; i < numPhysRegs; ++i) {
3982292SN/A        regScoreboard[i] = false;
3992292SN/A    }
4002292SN/A
4012292SN/A    for (ThreadID tid = 0; tid < numThreads; ++tid) {
4022292SN/A        squashedSeqNum[tid] = 0;
4032292SN/A    }
4042292SN/A
4052292SN/A    for (int i = 0; i < Num_OpClasses; ++i) {
4062292SN/A        while (!readyInsts[i].empty())
4072292SN/A            readyInsts[i].pop();
4083867Sbinkertn@umich.edu        queueOnList[i] = false;
4093867Sbinkertn@umich.edu        readyIt[i] = listOrder.end();
4102292SN/A    }
4113867Sbinkertn@umich.edu    nonSpecInsts.clear();
4123867Sbinkertn@umich.edu    listOrder.clear();
4133867Sbinkertn@umich.edu    deferredMemInsts.clear();
4142292SN/A}
4152292SN/A
4162292SN/Atemplate <class Impl>
4172292SN/Avoid
4182292SN/AInstructionQueue<Impl>::setActiveThreads(list<ThreadID> *at_ptr)
4192292SN/A{
4202292SN/A    activeThreads = at_ptr;
4212292SN/A}
4222292SN/A
4232292SN/Atemplate <class Impl>
4242292SN/Avoid
4252292SN/AInstructionQueue<Impl>::setIssueToExecuteQueue(TimeBuffer<IssueStruct> *i2e_ptr)
4263867Sbinkertn@umich.edu{
4273867Sbinkertn@umich.edu      issueToExecuteQueue = i2e_ptr;
4282292SN/A}
4293867Sbinkertn@umich.edu
4303867Sbinkertn@umich.edutemplate <class Impl>
4313867Sbinkertn@umich.eduvoid
4322292SN/AInstructionQueue<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
4332292SN/A{
4342292SN/A    timeBuffer = tb_ptr;
4352292SN/A
4362292SN/A    fromCommit = timeBuffer->getWire(-commitToIEWDelay);
4372292SN/A}
4382292SN/A
4392292SN/Atemplate <class Impl>
4402292SN/Avoid
4412292SN/AInstructionQueue<Impl>::switchOut()
4422292SN/A{
4432292SN/A/*
4443867Sbinkertn@umich.edu    if (!instList[0].empty() || (numEntries != freeEntries) ||
4453867Sbinkertn@umich.edu        !readyInsts[0].empty() || !nonSpecInsts.empty() || !listOrder.empty()) {
4462292SN/A        dumpInsts();
4473867Sbinkertn@umich.edu//        assert(0);
4483867Sbinkertn@umich.edu    }
4493867Sbinkertn@umich.edu*/
4502292SN/A    resetState();
4512292SN/A    dependGraph.reset();
4522292SN/A    instsToExecute.clear();
4532292SN/A    switchedOut = true;
4542292SN/A    for (ThreadID tid = 0; tid < numThreads; ++tid) {
4552292SN/A        memDepUnit[tid].switchOut();
4562292SN/A    }
4572292SN/A}
4582292SN/A
4592292SN/Atemplate <class Impl>
4603870Sbinkertn@umich.eduvoid
4612292SN/AInstructionQueue<Impl>::takeOverFrom()
4622292SN/A{
4632292SN/A    switchedOut = false;
4642292SN/A}
4652292SN/A
4662292SN/Atemplate <class Impl>
4672292SN/Aint
4682292SN/AInstructionQueue<Impl>::entryAmount(ThreadID num_threads)
4692292SN/A{
4703867Sbinkertn@umich.edu    if (iqPolicy == Partitioned) {
4713867Sbinkertn@umich.edu        return numEntries / num_threads;
4722292SN/A    } else {
4733867Sbinkertn@umich.edu        return 0;
4743867Sbinkertn@umich.edu    }
4753867Sbinkertn@umich.edu}
4763867Sbinkertn@umich.edu
4772292SN/A
4782292SN/Atemplate <class Impl>
4792292SN/Avoid
4802292SN/AInstructionQueue<Impl>::resetEntries()
4812292SN/A{
4822292SN/A    if (iqPolicy != Dynamic || numThreads > 1) {
4832292SN/A        int active_threads = activeThreads->size();
4842292SN/A
4852292SN/A        list<ThreadID>::iterator threads = activeThreads->begin();
4862292SN/A        list<ThreadID>::iterator end = activeThreads->end();
4872292SN/A
4882292SN/A        while (threads != end) {
4893867Sbinkertn@umich.edu            ThreadID tid = *threads++;
4902292SN/A
4912292SN/A            if (iqPolicy == Partitioned) {
4922292SN/A                maxEntries[tid] = numEntries / active_threads;
4932292SN/A            } else if(iqPolicy == Threshold && active_threads == 1) {
4942292SN/A                maxEntries[tid] = numEntries;
4952292SN/A            }
4962292SN/A        }
4972292SN/A    }
4982292SN/A}
4993867Sbinkertn@umich.edu
5003867Sbinkertn@umich.edutemplate <class Impl>
5012292SN/Aunsigned
5023867Sbinkertn@umich.eduInstructionQueue<Impl>::numFreeEntries()
5033867Sbinkertn@umich.edu{
5043867Sbinkertn@umich.edu    return freeEntries;
5052292SN/A}
5062292SN/A
5072292SN/Atemplate <class Impl>
5082292SN/Aunsigned
5092292SN/AInstructionQueue<Impl>::numFreeEntries(ThreadID tid)
5102292SN/A{
5112292SN/A    return maxEntries[tid] - count[tid];
5122292SN/A}
5132292SN/A
5142292SN/A// Might want to do something more complex if it knows how many instructions
5152292SN/A// will be issued this cycle.
5162292SN/Atemplate <class Impl>
5172292SN/Abool
5183870Sbinkertn@umich.eduInstructionQueue<Impl>::isFull()
5192292SN/A{
5202292SN/A    if (freeEntries == 0) {
5212292SN/A        return(true);
5222292SN/A    } else {
5232292SN/A        return(false);
5242292SN/A    }
5252292SN/A}
5262292SN/A
5272292SN/Atemplate <class Impl>
5283867Sbinkertn@umich.edubool
5293867Sbinkertn@umich.eduInstructionQueue<Impl>::isFull(ThreadID tid)
5302292SN/A{
5313867Sbinkertn@umich.edu    if (numFreeEntries(tid) == 0) {
5323867Sbinkertn@umich.edu        return(true);
5333867Sbinkertn@umich.edu    } else {
5342292SN/A        return(false);
5352292SN/A    }
5362292SN/A}
5372292SN/A
5382292SN/Atemplate <class Impl>
5392292SN/Abool
5402292SN/AInstructionQueue<Impl>::hasReadyInsts()
5412292SN/A{
5422292SN/A    if (!listOrder.empty()) {
5432292SN/A        return true;
5442292SN/A    }
5452292SN/A
5462292SN/A    for (int i = 0; i < Num_OpClasses; ++i) {
5473870Sbinkertn@umich.edu        if (!readyInsts[i].empty()) {
5482292SN/A            return true;
5492292SN/A        }
5502292SN/A    }
5512292SN/A
5522292SN/A    return false;
5532292SN/A}
5542292SN/A
5552292SN/Atemplate <class Impl>
5562292SN/Avoid
5573867Sbinkertn@umich.eduInstructionQueue<Impl>::insert(DynInstPtr &new_inst)
5583867Sbinkertn@umich.edu{
5592292SN/A    new_inst->isFloating() ? fpInstQueueWrites++ : intInstQueueWrites++;
5603867Sbinkertn@umich.edu    // Make sure the instruction is valid
5613867Sbinkertn@umich.edu    assert(new_inst);
5623867Sbinkertn@umich.edu
5632292SN/A    DPRINTF(IQ, "Adding instruction [sn:%lli] PC %s to the IQ.\n",
5642292SN/A            new_inst->seqNum, new_inst->pcState());
5652292SN/A
5662292SN/A    assert(freeEntries != 0);
5672292SN/A
5682292SN/A    instList[new_inst->threadNumber].push_back(new_inst);
5692292SN/A
5702292SN/A    --freeEntries;
5712292SN/A
5722292SN/A    new_inst->setInIQ();
5732292SN/A
5743870Sbinkertn@umich.edu    // Look through its source registers (physical regs), and mark any
5752292SN/A    // dependencies.
5762292SN/A    addToDependents(new_inst);
5772292SN/A
5782292SN/A    // Have this instruction set itself as the producer of its destination
5792292SN/A    // register(s).
5802292SN/A    addToProducers(new_inst);
5812292SN/A
5822292SN/A    if (new_inst->isMemRef()) {
5832292SN/A        memDepUnit[new_inst->threadNumber].insert(new_inst);
5843867Sbinkertn@umich.edu    } else {
5853867Sbinkertn@umich.edu        addIfReady(new_inst);
5862292SN/A    }
5873867Sbinkertn@umich.edu
5882864Sktlim@umich.edu    ++iqInstsAdded;
5892864Sktlim@umich.edu
5903867Sbinkertn@umich.edu    count[new_inst->threadNumber]++;
5913867Sbinkertn@umich.edu
5923867Sbinkertn@umich.edu    assert(freeEntries == (numEntries - countInsts()));
5932292SN/A}
5942292SN/A
5952292SN/Atemplate <class Impl>
5962292SN/Avoid
5972292SN/AInstructionQueue<Impl>::insertNonSpec(DynInstPtr &new_inst)
5982292SN/A{
5992292SN/A    // @todo: Clean up this code; can do it by setting inst as unable
6002292SN/A    // to issue, then calling normal insert on the inst.
6012292SN/A    new_inst->isFloating() ? fpInstQueueWrites++ : intInstQueueWrites++;
6022292SN/A
6032292SN/A    assert(new_inst);
6043867Sbinkertn@umich.edu
6053867Sbinkertn@umich.edu    nonSpecInsts[new_inst->seqNum] = new_inst;
6062292SN/A
6073867Sbinkertn@umich.edu    DPRINTF(IQ, "Adding non-speculative instruction [sn:%lli] PC %s "
6083867Sbinkertn@umich.edu            "to the IQ.\n",
6093867Sbinkertn@umich.edu            new_inst->seqNum, new_inst->pcState());
6102292SN/A
6112292SN/A    assert(freeEntries != 0);
6122292SN/A
6132292SN/A    instList[new_inst->threadNumber].push_back(new_inst);
6142292SN/A
6152292SN/A    --freeEntries;
6162292SN/A
6172292SN/A    new_inst->setInIQ();
6182292SN/A
6192292SN/A    // Have this instruction set itself as the producer of its destination
6202292SN/A    // register(s).
6213867Sbinkertn@umich.edu    addToProducers(new_inst);
6223867Sbinkertn@umich.edu
6232292SN/A    // If it's a memory instruction, add it to the memory dependency
6243867Sbinkertn@umich.edu    // unit.
6253867Sbinkertn@umich.edu    if (new_inst->isMemRef()) {
6263867Sbinkertn@umich.edu        memDepUnit[new_inst->threadNumber].insertNonSpec(new_inst);
6272292SN/A    }
6282292SN/A
6292292SN/A    ++iqNonSpecInstsAdded;
630
631    count[new_inst->threadNumber]++;
632
633    assert(freeEntries == (numEntries - countInsts()));
634}
635
636template <class Impl>
637void
638InstructionQueue<Impl>::insertBarrier(DynInstPtr &barr_inst)
639{
640    memDepUnit[barr_inst->threadNumber].insertBarrier(barr_inst);
641
642    insertNonSpec(barr_inst);
643}
644
645template <class Impl>
646typename Impl::DynInstPtr
647InstructionQueue<Impl>::getInstToExecute()
648{
649    assert(!instsToExecute.empty());
650    DynInstPtr inst = instsToExecute.front();
651    instsToExecute.pop_front();
652    if (inst->isFloating()){
653        fpInstQueueReads++;
654    } else {
655        intInstQueueReads++;
656    }
657    return inst;
658}
659
660template <class Impl>
661void
662InstructionQueue<Impl>::addToOrderList(OpClass op_class)
663{
664    assert(!readyInsts[op_class].empty());
665
666    ListOrderEntry queue_entry;
667
668    queue_entry.queueType = op_class;
669
670    queue_entry.oldestInst = readyInsts[op_class].top()->seqNum;
671
672    ListOrderIt list_it = listOrder.begin();
673    ListOrderIt list_end_it = listOrder.end();
674
675    while (list_it != list_end_it) {
676        if ((*list_it).oldestInst > queue_entry.oldestInst) {
677            break;
678        }
679
680        list_it++;
681    }
682
683    readyIt[op_class] = listOrder.insert(list_it, queue_entry);
684    queueOnList[op_class] = true;
685}
686
687template <class Impl>
688void
689InstructionQueue<Impl>::moveToYoungerInst(ListOrderIt list_order_it)
690{
691    // Get iterator of next item on the list
692    // Delete the original iterator
693    // Determine if the next item is either the end of the list or younger
694    // than the new instruction.  If so, then add in a new iterator right here.
695    // If not, then move along.
696    ListOrderEntry queue_entry;
697    OpClass op_class = (*list_order_it).queueType;
698    ListOrderIt next_it = list_order_it;
699
700    ++next_it;
701
702    queue_entry.queueType = op_class;
703    queue_entry.oldestInst = readyInsts[op_class].top()->seqNum;
704
705    while (next_it != listOrder.end() &&
706           (*next_it).oldestInst < queue_entry.oldestInst) {
707        ++next_it;
708    }
709
710    readyIt[op_class] = listOrder.insert(next_it, queue_entry);
711}
712
713template <class Impl>
714void
715InstructionQueue<Impl>::processFUCompletion(DynInstPtr &inst, int fu_idx)
716{
717    DPRINTF(IQ, "Processing FU completion [sn:%lli]\n", inst->seqNum);
718    // The CPU could have been sleeping until this op completed (*extremely*
719    // long latency op).  Wake it if it was.  This may be overkill.
720    if (isSwitchedOut()) {
721        DPRINTF(IQ, "FU completion not processed, IQ is switched out [sn:%lli]\n",
722                inst->seqNum);
723        return;
724    }
725
726    iewStage->wakeCPU();
727
728    if (fu_idx > -1)
729        fuPool->freeUnitNextCycle(fu_idx);
730
731    // @todo: Ensure that these FU Completions happen at the beginning
732    // of a cycle, otherwise they could add too many instructions to
733    // the queue.
734    issueToExecuteQueue->access(-1)->size++;
735    instsToExecute.push_back(inst);
736}
737
738// @todo: Figure out a better way to remove the squashed items from the
739// lists.  Checking the top item of each list to see if it's squashed
740// wastes time and forces jumps.
741template <class Impl>
742void
743InstructionQueue<Impl>::scheduleReadyInsts()
744{
745    DPRINTF(IQ, "Attempting to schedule ready instructions from "
746            "the IQ.\n");
747
748    IssueStruct *i2e_info = issueToExecuteQueue->access(0);
749
750    DynInstPtr deferred_mem_inst;
751    int total_deferred_mem_issued = 0;
752    while (total_deferred_mem_issued < totalWidth &&
753           (deferred_mem_inst = getDeferredMemInstToExecute()) != 0) {
754        issueToExecuteQueue->access(0)->size++;
755        instsToExecute.push_back(deferred_mem_inst);
756        total_deferred_mem_issued++;
757    }
758
759    // Have iterator to head of the list
760    // While I haven't exceeded bandwidth or reached the end of the list,
761    // Try to get a FU that can do what this op needs.
762    // If successful, change the oldestInst to the new top of the list, put
763    // the queue in the proper place in the list.
764    // Increment the iterator.
765    // This will avoid trying to schedule a certain op class if there are no
766    // FUs that handle it.
767    ListOrderIt order_it = listOrder.begin();
768    ListOrderIt order_end_it = listOrder.end();
769    int total_issued = 0;
770
771    while (total_issued < (totalWidth - total_deferred_mem_issued) &&
772           iewStage->canIssue() &&
773           order_it != order_end_it) {
774        OpClass op_class = (*order_it).queueType;
775
776        assert(!readyInsts[op_class].empty());
777
778        DynInstPtr issuing_inst = readyInsts[op_class].top();
779
780        issuing_inst->isFloating() ? fpInstQueueReads++ : intInstQueueReads++;
781
782        assert(issuing_inst->seqNum == (*order_it).oldestInst);
783
784        if (issuing_inst->isSquashed()) {
785            readyInsts[op_class].pop();
786
787            if (!readyInsts[op_class].empty()) {
788                moveToYoungerInst(order_it);
789            } else {
790                readyIt[op_class] = listOrder.end();
791                queueOnList[op_class] = false;
792            }
793
794            listOrder.erase(order_it++);
795
796            ++iqSquashedInstsIssued;
797
798            continue;
799        }
800
801        int idx = -2;
802        int op_latency = 1;
803        ThreadID tid = issuing_inst->threadNumber;
804
805        if (op_class != No_OpClass) {
806            idx = fuPool->getUnit(op_class);
807            issuing_inst->isFloating() ? fpAluAccesses++ : intAluAccesses++;
808            if (idx > -1) {
809                op_latency = fuPool->getOpLatency(op_class);
810            }
811        }
812
813        // If we have an instruction that doesn't require a FU, or a
814        // valid FU, then schedule for execution.
815        if (idx == -2 || idx != -1) {
816            if (op_latency == 1) {
817                i2e_info->size++;
818                instsToExecute.push_back(issuing_inst);
819
820                // Add the FU onto the list of FU's to be freed next
821                // cycle if we used one.
822                if (idx >= 0)
823                    fuPool->freeUnitNextCycle(idx);
824            } else {
825                int issue_latency = fuPool->getIssueLatency(op_class);
826                // Generate completion event for the FU
827                FUCompletion *execution = new FUCompletion(issuing_inst,
828                                                           idx, this);
829
830                cpu->schedule(execution, curTick() + cpu->ticks(op_latency - 1));
831
832                // @todo: Enforce that issue_latency == 1 or op_latency
833                if (issue_latency > 1) {
834                    // If FU isn't pipelined, then it must be freed
835                    // upon the execution completing.
836                    execution->setFreeFU();
837                } else {
838                    // Add the FU onto the list of FU's to be freed next cycle.
839                    fuPool->freeUnitNextCycle(idx);
840                }
841            }
842
843            DPRINTF(IQ, "Thread %i: Issuing instruction PC %s "
844                    "[sn:%lli]\n",
845                    tid, issuing_inst->pcState(),
846                    issuing_inst->seqNum);
847
848            readyInsts[op_class].pop();
849
850            if (!readyInsts[op_class].empty()) {
851                moveToYoungerInst(order_it);
852            } else {
853                readyIt[op_class] = listOrder.end();
854                queueOnList[op_class] = false;
855            }
856
857            issuing_inst->setIssued();
858            ++total_issued;
859
860            if (!issuing_inst->isMemRef()) {
861                // Memory instructions can not be freed from the IQ until they
862                // complete.
863                ++freeEntries;
864                count[tid]--;
865                issuing_inst->clearInIQ();
866            } else {
867                memDepUnit[tid].issue(issuing_inst);
868            }
869
870            listOrder.erase(order_it++);
871            statIssuedInstType[tid][op_class]++;
872            iewStage->incrWb(issuing_inst->seqNum);
873        } else {
874            statFuBusy[op_class]++;
875            fuBusy[tid]++;
876            ++order_it;
877        }
878    }
879
880    numIssuedDist.sample(total_issued);
881    iqInstsIssued+= total_issued;
882
883    // If we issued any instructions, tell the CPU we had activity.
884    // @todo If the way deferred memory instructions are handeled due to
885    // translation changes then the deferredMemInsts condition should be removed
886    // from the code below.
887    if (total_issued || total_deferred_mem_issued || deferredMemInsts.size()) {
888        cpu->activityThisCycle();
889    } else {
890        DPRINTF(IQ, "Not able to schedule any instructions.\n");
891    }
892}
893
894template <class Impl>
895void
896InstructionQueue<Impl>::scheduleNonSpec(const InstSeqNum &inst)
897{
898    DPRINTF(IQ, "Marking nonspeculative instruction [sn:%lli] as ready "
899            "to execute.\n", inst);
900
901    NonSpecMapIt inst_it = nonSpecInsts.find(inst);
902
903    assert(inst_it != nonSpecInsts.end());
904
905    ThreadID tid = (*inst_it).second->threadNumber;
906
907    (*inst_it).second->setAtCommit();
908
909    (*inst_it).second->setCanIssue();
910
911    if (!(*inst_it).second->isMemRef()) {
912        addIfReady((*inst_it).second);
913    } else {
914        memDepUnit[tid].nonSpecInstReady((*inst_it).second);
915    }
916
917    (*inst_it).second = NULL;
918
919    nonSpecInsts.erase(inst_it);
920}
921
922template <class Impl>
923void
924InstructionQueue<Impl>::commit(const InstSeqNum &inst, ThreadID tid)
925{
926    DPRINTF(IQ, "[tid:%i]: Committing instructions older than [sn:%i]\n",
927            tid,inst);
928
929    ListIt iq_it = instList[tid].begin();
930
931    while (iq_it != instList[tid].end() &&
932           (*iq_it)->seqNum <= inst) {
933        ++iq_it;
934        instList[tid].pop_front();
935    }
936
937    assert(freeEntries == (numEntries - countInsts()));
938}
939
940template <class Impl>
941int
942InstructionQueue<Impl>::wakeDependents(DynInstPtr &completed_inst)
943{
944    int dependents = 0;
945
946    // The instruction queue here takes care of both floating and int ops
947    if (completed_inst->isFloating()) {
948        fpInstQueueWakeupQccesses++;
949    } else {
950        intInstQueueWakeupAccesses++;
951    }
952
953    DPRINTF(IQ, "Waking dependents of completed instruction.\n");
954
955    assert(!completed_inst->isSquashed());
956
957    // Tell the memory dependence unit to wake any dependents on this
958    // instruction if it is a memory instruction.  Also complete the memory
959    // instruction at this point since we know it executed without issues.
960    // @todo: Might want to rename "completeMemInst" to something that
961    // indicates that it won't need to be replayed, and call this
962    // earlier.  Might not be a big deal.
963    if (completed_inst->isMemRef()) {
964        memDepUnit[completed_inst->threadNumber].wakeDependents(completed_inst);
965        completeMemInst(completed_inst);
966    } else if (completed_inst->isMemBarrier() ||
967               completed_inst->isWriteBarrier()) {
968        memDepUnit[completed_inst->threadNumber].completeBarrier(completed_inst);
969    }
970
971    for (int dest_reg_idx = 0;
972         dest_reg_idx < completed_inst->numDestRegs();
973         dest_reg_idx++)
974    {
975        PhysRegIndex dest_reg =
976            completed_inst->renamedDestRegIdx(dest_reg_idx);
977
978        // Special case of uniq or control registers.  They are not
979        // handled by the IQ and thus have no dependency graph entry.
980        // @todo Figure out a cleaner way to handle this.
981        if (dest_reg >= numPhysRegs) {
982            DPRINTF(IQ, "dest_reg :%d, numPhysRegs: %d\n", dest_reg,
983                    numPhysRegs);
984            continue;
985        }
986
987        DPRINTF(IQ, "Waking any dependents on register %i.\n",
988                (int) dest_reg);
989
990        //Go through the dependency chain, marking the registers as
991        //ready within the waiting instructions.
992        DynInstPtr dep_inst = dependGraph.pop(dest_reg);
993
994        while (dep_inst) {
995            DPRINTF(IQ, "Waking up a dependent instruction, [sn:%lli] "
996                    "PC %s.\n", dep_inst->seqNum, dep_inst->pcState());
997
998            // Might want to give more information to the instruction
999            // so that it knows which of its source registers is
1000            // ready.  However that would mean that the dependency
1001            // graph entries would need to hold the src_reg_idx.
1002            dep_inst->markSrcRegReady();
1003
1004            addIfReady(dep_inst);
1005
1006            dep_inst = dependGraph.pop(dest_reg);
1007
1008            ++dependents;
1009        }
1010
1011        // Reset the head node now that all of its dependents have
1012        // been woken up.
1013        assert(dependGraph.empty(dest_reg));
1014        dependGraph.clearInst(dest_reg);
1015
1016        // Mark the scoreboard as having that register ready.
1017        regScoreboard[dest_reg] = true;
1018    }
1019    return dependents;
1020}
1021
1022template <class Impl>
1023void
1024InstructionQueue<Impl>::addReadyMemInst(DynInstPtr &ready_inst)
1025{
1026    OpClass op_class = ready_inst->opClass();
1027
1028    readyInsts[op_class].push(ready_inst);
1029
1030    // Will need to reorder the list if either a queue is not on the list,
1031    // or it has an older instruction than last time.
1032    if (!queueOnList[op_class]) {
1033        addToOrderList(op_class);
1034    } else if (readyInsts[op_class].top()->seqNum  <
1035               (*readyIt[op_class]).oldestInst) {
1036        listOrder.erase(readyIt[op_class]);
1037        addToOrderList(op_class);
1038    }
1039
1040    DPRINTF(IQ, "Instruction is ready to issue, putting it onto "
1041            "the ready list, PC %s opclass:%i [sn:%lli].\n",
1042            ready_inst->pcState(), op_class, ready_inst->seqNum);
1043}
1044
1045template <class Impl>
1046void
1047InstructionQueue<Impl>::rescheduleMemInst(DynInstPtr &resched_inst)
1048{
1049    DPRINTF(IQ, "Rescheduling mem inst [sn:%lli]\n", resched_inst->seqNum);
1050
1051    // Reset DTB translation state
1052    resched_inst->translationStarted = false;
1053    resched_inst->translationCompleted = false;
1054
1055    resched_inst->clearCanIssue();
1056    memDepUnit[resched_inst->threadNumber].reschedule(resched_inst);
1057}
1058
1059template <class Impl>
1060void
1061InstructionQueue<Impl>::replayMemInst(DynInstPtr &replay_inst)
1062{
1063    memDepUnit[replay_inst->threadNumber].replay(replay_inst);
1064}
1065
1066template <class Impl>
1067void
1068InstructionQueue<Impl>::completeMemInst(DynInstPtr &completed_inst)
1069{
1070    ThreadID tid = completed_inst->threadNumber;
1071
1072    DPRINTF(IQ, "Completing mem instruction PC: %s [sn:%lli]\n",
1073            completed_inst->pcState(), completed_inst->seqNum);
1074
1075    ++freeEntries;
1076
1077    completed_inst->memOpDone = true;
1078
1079    memDepUnit[tid].completed(completed_inst);
1080    count[tid]--;
1081}
1082
1083template <class Impl>
1084void
1085InstructionQueue<Impl>::deferMemInst(DynInstPtr &deferred_inst)
1086{
1087    deferredMemInsts.push_back(deferred_inst);
1088}
1089
1090template <class Impl>
1091typename Impl::DynInstPtr
1092InstructionQueue<Impl>::getDeferredMemInstToExecute()
1093{
1094    for (ListIt it = deferredMemInsts.begin(); it != deferredMemInsts.end();
1095         ++it) {
1096        if ((*it)->translationCompleted) {
1097            DynInstPtr ret = *it;
1098            deferredMemInsts.erase(it);
1099            return ret;
1100        }
1101    }
1102    return NULL;
1103}
1104
1105template <class Impl>
1106void
1107InstructionQueue<Impl>::violation(DynInstPtr &store,
1108                                  DynInstPtr &faulting_load)
1109{
1110    intInstQueueWrites++;
1111    memDepUnit[store->threadNumber].violation(store, faulting_load);
1112}
1113
1114template <class Impl>
1115void
1116InstructionQueue<Impl>::squash(ThreadID tid)
1117{
1118    DPRINTF(IQ, "[tid:%i]: Starting to squash instructions in "
1119            "the IQ.\n", tid);
1120
1121    // Read instruction sequence number of last instruction out of the
1122    // time buffer.
1123    squashedSeqNum[tid] = fromCommit->commitInfo[tid].doneSeqNum;
1124
1125    // Call doSquash if there are insts in the IQ
1126    if (count[tid] > 0) {
1127        doSquash(tid);
1128    }
1129
1130    // Also tell the memory dependence unit to squash.
1131    memDepUnit[tid].squash(squashedSeqNum[tid], tid);
1132}
1133
1134template <class Impl>
1135void
1136InstructionQueue<Impl>::doSquash(ThreadID tid)
1137{
1138    // Start at the tail.
1139    ListIt squash_it = instList[tid].end();
1140    --squash_it;
1141
1142    DPRINTF(IQ, "[tid:%i]: Squashing until sequence number %i!\n",
1143            tid, squashedSeqNum[tid]);
1144
1145    // Squash any instructions younger than the squashed sequence number
1146    // given.
1147    while (squash_it != instList[tid].end() &&
1148           (*squash_it)->seqNum > squashedSeqNum[tid]) {
1149
1150        DynInstPtr squashed_inst = (*squash_it);
1151        squashed_inst->isFloating() ? fpInstQueueWrites++ : intInstQueueWrites++;
1152
1153        // Only handle the instruction if it actually is in the IQ and
1154        // hasn't already been squashed in the IQ.
1155        if (squashed_inst->threadNumber != tid ||
1156            squashed_inst->isSquashedInIQ()) {
1157            --squash_it;
1158            continue;
1159        }
1160
1161        if (!squashed_inst->isIssued() ||
1162            (squashed_inst->isMemRef() &&
1163             !squashed_inst->memOpDone)) {
1164
1165            DPRINTF(IQ, "[tid:%i]: Instruction [sn:%lli] PC %s squashed.\n",
1166                    tid, squashed_inst->seqNum, squashed_inst->pcState());
1167
1168            // Remove the instruction from the dependency list.
1169            if (!squashed_inst->isNonSpeculative() &&
1170                !squashed_inst->isStoreConditional() &&
1171                !squashed_inst->isMemBarrier() &&
1172                !squashed_inst->isWriteBarrier()) {
1173
1174                for (int src_reg_idx = 0;
1175                     src_reg_idx < squashed_inst->numSrcRegs();
1176                     src_reg_idx++)
1177                {
1178                    PhysRegIndex src_reg =
1179                        squashed_inst->renamedSrcRegIdx(src_reg_idx);
1180
1181                    // Only remove it from the dependency graph if it
1182                    // was placed there in the first place.
1183
1184                    // Instead of doing a linked list traversal, we
1185                    // can just remove these squashed instructions
1186                    // either at issue time, or when the register is
1187                    // overwritten.  The only downside to this is it
1188                    // leaves more room for error.
1189
1190                    if (!squashed_inst->isReadySrcRegIdx(src_reg_idx) &&
1191                        src_reg < numPhysRegs) {
1192                        dependGraph.remove(src_reg, squashed_inst);
1193                    }
1194
1195
1196                    ++iqSquashedOperandsExamined;
1197                }
1198            } else if (!squashed_inst->isStoreConditional() ||
1199                       !squashed_inst->isCompleted()) {
1200                NonSpecMapIt ns_inst_it =
1201                    nonSpecInsts.find(squashed_inst->seqNum);
1202
1203                if (ns_inst_it == nonSpecInsts.end()) {
1204                    assert(squashed_inst->getFault() != NoFault);
1205                } else {
1206
1207                    (*ns_inst_it).second = NULL;
1208
1209                    nonSpecInsts.erase(ns_inst_it);
1210
1211                    ++iqSquashedNonSpecRemoved;
1212                }
1213            }
1214
1215            // Might want to also clear out the head of the dependency graph.
1216
1217            // Mark it as squashed within the IQ.
1218            squashed_inst->setSquashedInIQ();
1219
1220            // @todo: Remove this hack where several statuses are set so the
1221            // inst will flow through the rest of the pipeline.
1222            squashed_inst->setIssued();
1223            squashed_inst->setCanCommit();
1224            squashed_inst->clearInIQ();
1225
1226            //Update Thread IQ Count
1227            count[squashed_inst->threadNumber]--;
1228
1229            ++freeEntries;
1230        }
1231
1232        instList[tid].erase(squash_it--);
1233        ++iqSquashedInstsExamined;
1234    }
1235}
1236
1237template <class Impl>
1238bool
1239InstructionQueue<Impl>::addToDependents(DynInstPtr &new_inst)
1240{
1241    // Loop through the instruction's source registers, adding
1242    // them to the dependency list if they are not ready.
1243    int8_t total_src_regs = new_inst->numSrcRegs();
1244    bool return_val = false;
1245
1246    for (int src_reg_idx = 0;
1247         src_reg_idx < total_src_regs;
1248         src_reg_idx++)
1249    {
1250        // Only add it to the dependency graph if it's not ready.
1251        if (!new_inst->isReadySrcRegIdx(src_reg_idx)) {
1252            PhysRegIndex src_reg = new_inst->renamedSrcRegIdx(src_reg_idx);
1253
1254            // Check the IQ's scoreboard to make sure the register
1255            // hasn't become ready while the instruction was in flight
1256            // between stages.  Only if it really isn't ready should
1257            // it be added to the dependency graph.
1258            if (src_reg >= numPhysRegs) {
1259                continue;
1260            } else if (regScoreboard[src_reg] == false) {
1261                DPRINTF(IQ, "Instruction PC %s has src reg %i that "
1262                        "is being added to the dependency chain.\n",
1263                        new_inst->pcState(), src_reg);
1264
1265                dependGraph.insert(src_reg, new_inst);
1266
1267                // Change the return value to indicate that something
1268                // was added to the dependency graph.
1269                return_val = true;
1270            } else {
1271                DPRINTF(IQ, "Instruction PC %s has src reg %i that "
1272                        "became ready before it reached the IQ.\n",
1273                        new_inst->pcState(), src_reg);
1274                // Mark a register ready within the instruction.
1275                new_inst->markSrcRegReady(src_reg_idx);
1276            }
1277        }
1278    }
1279
1280    return return_val;
1281}
1282
1283template <class Impl>
1284void
1285InstructionQueue<Impl>::addToProducers(DynInstPtr &new_inst)
1286{
1287    // Nothing really needs to be marked when an instruction becomes
1288    // the producer of a register's value, but for convenience a ptr
1289    // to the producing instruction will be placed in the head node of
1290    // the dependency links.
1291    int8_t total_dest_regs = new_inst->numDestRegs();
1292
1293    for (int dest_reg_idx = 0;
1294         dest_reg_idx < total_dest_regs;
1295         dest_reg_idx++)
1296    {
1297        PhysRegIndex dest_reg = new_inst->renamedDestRegIdx(dest_reg_idx);
1298
1299        // Instructions that use the misc regs will have a reg number
1300        // higher than the normal physical registers.  In this case these
1301        // registers are not renamed, and there is no need to track
1302        // dependencies as these instructions must be executed at commit.
1303        if (dest_reg >= numPhysRegs) {
1304            continue;
1305        }
1306
1307        if (!dependGraph.empty(dest_reg)) {
1308            dependGraph.dump();
1309            panic("Dependency graph %i not empty!", dest_reg);
1310        }
1311
1312        dependGraph.setInst(dest_reg, new_inst);
1313
1314        // Mark the scoreboard to say it's not yet ready.
1315        regScoreboard[dest_reg] = false;
1316    }
1317}
1318
1319template <class Impl>
1320void
1321InstructionQueue<Impl>::addIfReady(DynInstPtr &inst)
1322{
1323    // If the instruction now has all of its source registers
1324    // available, then add it to the list of ready instructions.
1325    if (inst->readyToIssue()) {
1326
1327        //Add the instruction to the proper ready list.
1328        if (inst->isMemRef()) {
1329
1330            DPRINTF(IQ, "Checking if memory instruction can issue.\n");
1331
1332            // Message to the mem dependence unit that this instruction has
1333            // its registers ready.
1334            memDepUnit[inst->threadNumber].regsReady(inst);
1335
1336            return;
1337        }
1338
1339        OpClass op_class = inst->opClass();
1340
1341        DPRINTF(IQ, "Instruction is ready to issue, putting it onto "
1342                "the ready list, PC %s opclass:%i [sn:%lli].\n",
1343                inst->pcState(), op_class, inst->seqNum);
1344
1345        readyInsts[op_class].push(inst);
1346
1347        // Will need to reorder the list if either a queue is not on the list,
1348        // or it has an older instruction than last time.
1349        if (!queueOnList[op_class]) {
1350            addToOrderList(op_class);
1351        } else if (readyInsts[op_class].top()->seqNum  <
1352                   (*readyIt[op_class]).oldestInst) {
1353            listOrder.erase(readyIt[op_class]);
1354            addToOrderList(op_class);
1355        }
1356    }
1357}
1358
1359template <class Impl>
1360int
1361InstructionQueue<Impl>::countInsts()
1362{
1363#if 0
1364    //ksewell:This works but definitely could use a cleaner write
1365    //with a more intuitive way of counting. Right now it's
1366    //just brute force ....
1367    // Change the #if if you want to use this method.
1368    int total_insts = 0;
1369
1370    for (ThreadID tid = 0; tid < numThreads; ++tid) {
1371        ListIt count_it = instList[tid].begin();
1372
1373        while (count_it != instList[tid].end()) {
1374            if (!(*count_it)->isSquashed() && !(*count_it)->isSquashedInIQ()) {
1375                if (!(*count_it)->isIssued()) {
1376                    ++total_insts;
1377                } else if ((*count_it)->isMemRef() &&
1378                           !(*count_it)->memOpDone) {
1379                    // Loads that have not been marked as executed still count
1380                    // towards the total instructions.
1381                    ++total_insts;
1382                }
1383            }
1384
1385            ++count_it;
1386        }
1387    }
1388
1389    return total_insts;
1390#else
1391    return numEntries - freeEntries;
1392#endif
1393}
1394
1395template <class Impl>
1396void
1397InstructionQueue<Impl>::dumpLists()
1398{
1399    for (int i = 0; i < Num_OpClasses; ++i) {
1400        cprintf("Ready list %i size: %i\n", i, readyInsts[i].size());
1401
1402        cprintf("\n");
1403    }
1404
1405    cprintf("Non speculative list size: %i\n", nonSpecInsts.size());
1406
1407    NonSpecMapIt non_spec_it = nonSpecInsts.begin();
1408    NonSpecMapIt non_spec_end_it = nonSpecInsts.end();
1409
1410    cprintf("Non speculative list: ");
1411
1412    while (non_spec_it != non_spec_end_it) {
1413        cprintf("%s [sn:%lli]", (*non_spec_it).second->pcState(),
1414                (*non_spec_it).second->seqNum);
1415        ++non_spec_it;
1416    }
1417
1418    cprintf("\n");
1419
1420    ListOrderIt list_order_it = listOrder.begin();
1421    ListOrderIt list_order_end_it = listOrder.end();
1422    int i = 1;
1423
1424    cprintf("List order: ");
1425
1426    while (list_order_it != list_order_end_it) {
1427        cprintf("%i OpClass:%i [sn:%lli] ", i, (*list_order_it).queueType,
1428                (*list_order_it).oldestInst);
1429
1430        ++list_order_it;
1431        ++i;
1432    }
1433
1434    cprintf("\n");
1435}
1436
1437
1438template <class Impl>
1439void
1440InstructionQueue<Impl>::dumpInsts()
1441{
1442    for (ThreadID tid = 0; tid < numThreads; ++tid) {
1443        int num = 0;
1444        int valid_num = 0;
1445        ListIt inst_list_it = instList[tid].begin();
1446
1447        while (inst_list_it != instList[tid].end()) {
1448            cprintf("Instruction:%i\n", num);
1449            if (!(*inst_list_it)->isSquashed()) {
1450                if (!(*inst_list_it)->isIssued()) {
1451                    ++valid_num;
1452                    cprintf("Count:%i\n", valid_num);
1453                } else if ((*inst_list_it)->isMemRef() &&
1454                           !(*inst_list_it)->memOpDone) {
1455                    // Loads that have not been marked as executed
1456                    // still count towards the total instructions.
1457                    ++valid_num;
1458                    cprintf("Count:%i\n", valid_num);
1459                }
1460            }
1461
1462            cprintf("PC: %s\n[sn:%lli]\n[tid:%i]\n"
1463                    "Issued:%i\nSquashed:%i\n",
1464                    (*inst_list_it)->pcState(),
1465                    (*inst_list_it)->seqNum,
1466                    (*inst_list_it)->threadNumber,
1467                    (*inst_list_it)->isIssued(),
1468                    (*inst_list_it)->isSquashed());
1469
1470            if ((*inst_list_it)->isMemRef()) {
1471                cprintf("MemOpDone:%i\n", (*inst_list_it)->memOpDone);
1472            }
1473
1474            cprintf("\n");
1475
1476            inst_list_it++;
1477            ++num;
1478        }
1479    }
1480
1481    cprintf("Insts to Execute list:\n");
1482
1483    int num = 0;
1484    int valid_num = 0;
1485    ListIt inst_list_it = instsToExecute.begin();
1486
1487    while (inst_list_it != instsToExecute.end())
1488    {
1489        cprintf("Instruction:%i\n",
1490                num);
1491        if (!(*inst_list_it)->isSquashed()) {
1492            if (!(*inst_list_it)->isIssued()) {
1493                ++valid_num;
1494                cprintf("Count:%i\n", valid_num);
1495            } else if ((*inst_list_it)->isMemRef() &&
1496                       !(*inst_list_it)->memOpDone) {
1497                // Loads that have not been marked as executed
1498                // still count towards the total instructions.
1499                ++valid_num;
1500                cprintf("Count:%i\n", valid_num);
1501            }
1502        }
1503
1504        cprintf("PC: %s\n[sn:%lli]\n[tid:%i]\n"
1505                "Issued:%i\nSquashed:%i\n",
1506                (*inst_list_it)->pcState(),
1507                (*inst_list_it)->seqNum,
1508                (*inst_list_it)->threadNumber,
1509                (*inst_list_it)->isIssued(),
1510                (*inst_list_it)->isSquashed());
1511
1512        if ((*inst_list_it)->isMemRef()) {
1513            cprintf("MemOpDone:%i\n", (*inst_list_it)->memOpDone);
1514        }
1515
1516        cprintf("\n");
1517
1518        inst_list_it++;
1519        ++num;
1520    }
1521}
1522