rename_impl.hh revision 2935:d1223a6c9156
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 <list>
33
34#include "config/full_system.hh"
35#include "cpu/o3/rename.hh"
36
37using namespace std;
38
39template <class Impl>
40DefaultRename<Impl>::DefaultRename(Params *params)
41    : iewToRenameDelay(params->iewToRenameDelay),
42      decodeToRenameDelay(params->decodeToRenameDelay),
43      commitToRenameDelay(params->commitToRenameDelay),
44      renameWidth(params->renameWidth),
45      commitWidth(params->commitWidth),
46      numThreads(params->numberOfThreads)
47{
48    _status = Inactive;
49
50    for (int i=0; i< numThreads; i++) {
51        renameStatus[i] = Idle;
52
53        freeEntries[i].iqEntries = 0;
54        freeEntries[i].lsqEntries = 0;
55        freeEntries[i].robEntries = 0;
56
57        stalls[i].iew = false;
58        stalls[i].commit = false;
59        serializeInst[i] = NULL;
60
61        instsInProgress[i] = 0;
62
63        emptyROB[i] = true;
64
65        serializeOnNextInst[i] = false;
66    }
67
68    // @todo: Make into a parameter.
69    skidBufferMax = (2 * (iewToRenameDelay * params->decodeWidth)) + renameWidth;
70}
71
72template <class Impl>
73std::string
74DefaultRename<Impl>::name() const
75{
76    return cpu->name() + ".rename";
77}
78
79template <class Impl>
80void
81DefaultRename<Impl>::regStats()
82{
83    renameSquashCycles
84        .name(name() + ".RENAME:SquashCycles")
85        .desc("Number of cycles rename is squashing")
86        .prereq(renameSquashCycles);
87    renameIdleCycles
88        .name(name() + ".RENAME:IdleCycles")
89        .desc("Number of cycles rename is idle")
90        .prereq(renameIdleCycles);
91    renameBlockCycles
92        .name(name() + ".RENAME:BlockCycles")
93        .desc("Number of cycles rename is blocking")
94        .prereq(renameBlockCycles);
95    renameSerializeStallCycles
96        .name(name() + ".RENAME:serializeStallCycles")
97        .desc("count of cycles rename stalled for serializing inst")
98        .flags(Stats::total);
99    renameRunCycles
100        .name(name() + ".RENAME:RunCycles")
101        .desc("Number of cycles rename is running")
102        .prereq(renameIdleCycles);
103    renameUnblockCycles
104        .name(name() + ".RENAME:UnblockCycles")
105        .desc("Number of cycles rename is unblocking")
106        .prereq(renameUnblockCycles);
107    renameRenamedInsts
108        .name(name() + ".RENAME:RenamedInsts")
109        .desc("Number of instructions processed by rename")
110        .prereq(renameRenamedInsts);
111    renameSquashedInsts
112        .name(name() + ".RENAME:SquashedInsts")
113        .desc("Number of squashed instructions processed by rename")
114        .prereq(renameSquashedInsts);
115    renameROBFullEvents
116        .name(name() + ".RENAME:ROBFullEvents")
117        .desc("Number of times rename has blocked due to ROB full")
118        .prereq(renameROBFullEvents);
119    renameIQFullEvents
120        .name(name() + ".RENAME:IQFullEvents")
121        .desc("Number of times rename has blocked due to IQ full")
122        .prereq(renameIQFullEvents);
123    renameLSQFullEvents
124        .name(name() + ".RENAME:LSQFullEvents")
125        .desc("Number of times rename has blocked due to LSQ full")
126        .prereq(renameLSQFullEvents);
127    renameFullRegistersEvents
128        .name(name() + ".RENAME:FullRegisterEvents")
129        .desc("Number of times there has been no free registers")
130        .prereq(renameFullRegistersEvents);
131    renameRenamedOperands
132        .name(name() + ".RENAME:RenamedOperands")
133        .desc("Number of destination operands rename has renamed")
134        .prereq(renameRenamedOperands);
135    renameRenameLookups
136        .name(name() + ".RENAME:RenameLookups")
137        .desc("Number of register rename lookups that rename has made")
138        .prereq(renameRenameLookups);
139    renameCommittedMaps
140        .name(name() + ".RENAME:CommittedMaps")
141        .desc("Number of HB maps that are committed")
142        .prereq(renameCommittedMaps);
143    renameUndoneMaps
144        .name(name() + ".RENAME:UndoneMaps")
145        .desc("Number of HB maps that are undone due to squashing")
146        .prereq(renameUndoneMaps);
147    renamedSerializing
148        .name(name() + ".RENAME:serializingInsts")
149        .desc("count of serializing insts renamed")
150        .flags(Stats::total)
151        ;
152    renamedTempSerializing
153        .name(name() + ".RENAME:tempSerializingInsts")
154        .desc("count of temporary serializing insts renamed")
155        .flags(Stats::total)
156        ;
157    renameSkidInsts
158        .name(name() + ".RENAME:skidInsts")
159        .desc("count of insts added to the skid buffer")
160        .flags(Stats::total)
161        ;
162}
163
164template <class Impl>
165void
166DefaultRename<Impl>::setCPU(O3CPU *cpu_ptr)
167{
168    DPRINTF(Rename, "Setting CPU pointer.\n");
169    cpu = cpu_ptr;
170}
171
172template <class Impl>
173void
174DefaultRename<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
175{
176    DPRINTF(Rename, "Setting time buffer pointer.\n");
177    timeBuffer = tb_ptr;
178
179    // Setup wire to read information from time buffer, from IEW stage.
180    fromIEW = timeBuffer->getWire(-iewToRenameDelay);
181
182    // Setup wire to read infromation from time buffer, from commit stage.
183    fromCommit = timeBuffer->getWire(-commitToRenameDelay);
184
185    // Setup wire to write information to previous stages.
186    toDecode = timeBuffer->getWire(0);
187}
188
189template <class Impl>
190void
191DefaultRename<Impl>::setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr)
192{
193    DPRINTF(Rename, "Setting rename queue pointer.\n");
194    renameQueue = rq_ptr;
195
196    // Setup wire to write information to future stages.
197    toIEW = renameQueue->getWire(0);
198}
199
200template <class Impl>
201void
202DefaultRename<Impl>::setDecodeQueue(TimeBuffer<DecodeStruct> *dq_ptr)
203{
204    DPRINTF(Rename, "Setting decode queue pointer.\n");
205    decodeQueue = dq_ptr;
206
207    // Setup wire to get information from decode.
208    fromDecode = decodeQueue->getWire(-decodeToRenameDelay);
209}
210
211template <class Impl>
212void
213DefaultRename<Impl>::initStage()
214{
215    // Grab the number of free entries directly from the stages.
216    for (int tid=0; tid < numThreads; tid++) {
217        freeEntries[tid].iqEntries = iew_ptr->instQueue.numFreeEntries(tid);
218        freeEntries[tid].lsqEntries = iew_ptr->ldstQueue.numFreeEntries(tid);
219        freeEntries[tid].robEntries = commit_ptr->numROBFreeEntries(tid);
220        emptyROB[tid] = true;
221    }
222}
223
224template<class Impl>
225void
226DefaultRename<Impl>::setActiveThreads(list<unsigned> *at_ptr)
227{
228    DPRINTF(Rename, "Setting active threads list pointer.\n");
229    activeThreads = at_ptr;
230}
231
232
233template <class Impl>
234void
235DefaultRename<Impl>::setRenameMap(RenameMap rm_ptr[])
236{
237    DPRINTF(Rename, "Setting rename map pointers.\n");
238
239    for (int i=0; i<numThreads; i++) {
240        renameMap[i] = &rm_ptr[i];
241    }
242}
243
244template <class Impl>
245void
246DefaultRename<Impl>::setFreeList(FreeList *fl_ptr)
247{
248    DPRINTF(Rename, "Setting free list pointer.\n");
249    freeList = fl_ptr;
250}
251
252template<class Impl>
253void
254DefaultRename<Impl>::setScoreboard(Scoreboard *_scoreboard)
255{
256    DPRINTF(Rename, "Setting scoreboard pointer.\n");
257    scoreboard = _scoreboard;
258}
259
260template <class Impl>
261bool
262DefaultRename<Impl>::drain()
263{
264    // Rename is ready to switch out at any time.
265    cpu->signalDrained();
266    return true;
267}
268
269template <class Impl>
270void
271DefaultRename<Impl>::switchOut()
272{
273    // Clear any state, fix up the rename map.
274    for (int i = 0; i < numThreads; i++) {
275        typename list<RenameHistory>::iterator hb_it = historyBuffer[i].begin();
276
277        while (!historyBuffer[i].empty()) {
278            assert(hb_it != historyBuffer[i].end());
279
280            DPRINTF(Rename, "[tid:%u]: Removing history entry with sequence "
281                    "number %i.\n", i, (*hb_it).instSeqNum);
282
283            // Tell the rename map to set the architected register to the
284            // previous physical register that it was renamed to.
285            renameMap[i]->setEntry(hb_it->archReg, hb_it->prevPhysReg);
286
287            // Put the renamed physical register back on the free list.
288            freeList->addReg(hb_it->newPhysReg);
289
290            historyBuffer[i].erase(hb_it++);
291        }
292        insts[i].clear();
293        skidBuffer[i].clear();
294    }
295}
296
297template <class Impl>
298void
299DefaultRename<Impl>::takeOverFrom()
300{
301    _status = Inactive;
302    initStage();
303
304    // Reset all state prior to taking over from the other CPU.
305    for (int i=0; i< numThreads; i++) {
306        renameStatus[i] = Idle;
307
308        stalls[i].iew = false;
309        stalls[i].commit = false;
310        serializeInst[i] = NULL;
311
312        instsInProgress[i] = 0;
313
314        emptyROB[i] = true;
315
316        serializeOnNextInst[i] = false;
317    }
318}
319
320template <class Impl>
321void
322DefaultRename<Impl>::squash(const InstSeqNum &squash_seq_num, unsigned tid)
323{
324    DPRINTF(Rename, "[tid:%u]: Squashing instructions.\n",tid);
325
326    // Clear the stall signal if rename was blocked or unblocking before.
327    // If it still needs to block, the blocking should happen the next
328    // cycle and there should be space to hold everything due to the squash.
329    if (renameStatus[tid] == Blocked ||
330        renameStatus[tid] == Unblocking ||
331        renameStatus[tid] == SerializeStall) {
332
333        toDecode->renameUnblock[tid] = 1;
334
335        serializeInst[tid] = NULL;
336    }
337
338    // Set the status to Squashing.
339    renameStatus[tid] = Squashing;
340
341    // Squash any instructions from decode.
342    unsigned squashCount = 0;
343
344    for (int i=0; i<fromDecode->size; i++) {
345        if (fromDecode->insts[i]->threadNumber == tid &&
346            fromDecode->insts[i]->seqNum > squash_seq_num) {
347            fromDecode->insts[i]->setSquashed();
348            wroteToTimeBuffer = true;
349            squashCount++;
350        }
351
352    }
353
354    // Clear the instruction list and skid buffer in case they have any
355    // insts in them. Since we support multiple ISAs, we cant just:
356    // "insts[tid].clear();" or "skidBuffer[tid].clear()" since there is
357    // a possible delay slot inst for different architectures
358    // insts[tid].clear();
359#if THE_ISA == ALPHA_ISA
360    insts[tid].clear();
361#else
362    DPRINTF(Rename, "[tid:%i] Squashing incoming decode instructions until "
363            "[sn:%i].\n",tid, squash_seq_num);
364    ListIt ilist_it = insts[tid].begin();
365    while (ilist_it != insts[tid].end()) {
366        if ((*ilist_it)->seqNum > squash_seq_num) {
367            (*ilist_it)->setSquashed();
368            DPRINTF(Rename, "Squashing incoming decode instruction, "
369                    "[tid:%i] [sn:%i] PC %08p.\n", tid, (*ilist_it)->seqNum, (*ilist_it)->PC);
370        }
371        ilist_it++;
372    }
373#endif
374
375    // Clear the skid buffer in case it has any data in it.
376    // See comments above.
377    //     skidBuffer[tid].clear();
378#if THE_ISA == ALPHA_ISA
379    skidBuffer[tid].clear();
380#else
381    DPRINTF(Rename, "[tid:%i] Squashing incoming skidbuffer instructions "
382            "until [sn:%i].\n", tid, squash_seq_num);
383    ListIt slist_it = skidBuffer[tid].begin();
384    while (slist_it != skidBuffer[tid].end()) {
385        if ((*slist_it)->seqNum > squash_seq_num) {
386            (*slist_it)->setSquashed();
387            DPRINTF(Rename, "Squashing skidbuffer instruction, [tid:%i] [sn:%i]"
388                    "PC %08p.\n", tid, (*slist_it)->seqNum, (*slist_it)->PC);
389        }
390        slist_it++;
391    }
392#endif
393    doSquash(squash_seq_num, tid);
394}
395
396template <class Impl>
397void
398DefaultRename<Impl>::tick()
399{
400    wroteToTimeBuffer = false;
401
402    blockThisCycle = false;
403
404    bool status_change = false;
405
406    toIEWIndex = 0;
407
408    sortInsts();
409
410    list<unsigned>::iterator threads = (*activeThreads).begin();
411
412    // Check stall and squash signals.
413    while (threads != (*activeThreads).end()) {
414        unsigned tid = *threads++;
415
416        DPRINTF(Rename, "Processing [tid:%i]\n", tid);
417
418        status_change = checkSignalsAndUpdate(tid) || status_change;
419
420        rename(status_change, tid);
421    }
422
423    if (status_change) {
424        updateStatus();
425    }
426
427    if (wroteToTimeBuffer) {
428        DPRINTF(Activity, "Activity this cycle.\n");
429        cpu->activityThisCycle();
430    }
431
432    threads = (*activeThreads).begin();
433
434    while (threads != (*activeThreads).end()) {
435        unsigned tid = *threads++;
436
437        // If we committed this cycle then doneSeqNum will be > 0
438        if (fromCommit->commitInfo[tid].doneSeqNum != 0 &&
439            !fromCommit->commitInfo[tid].squash &&
440            renameStatus[tid] != Squashing) {
441
442            removeFromHistory(fromCommit->commitInfo[tid].doneSeqNum,
443                                  tid);
444        }
445    }
446
447    // @todo: make into updateProgress function
448    for (int tid=0; tid < numThreads; tid++) {
449        instsInProgress[tid] -= fromIEW->iewInfo[tid].dispatched;
450
451        assert(instsInProgress[tid] >=0);
452    }
453
454}
455
456template<class Impl>
457void
458DefaultRename<Impl>::rename(bool &status_change, unsigned tid)
459{
460    // If status is Running or idle,
461    //     call renameInsts()
462    // If status is Unblocking,
463    //     buffer any instructions coming from decode
464    //     continue trying to empty skid buffer
465    //     check if stall conditions have passed
466
467    if (renameStatus[tid] == Blocked) {
468        ++renameBlockCycles;
469    } else if (renameStatus[tid] == Squashing) {
470        ++renameSquashCycles;
471    } else if (renameStatus[tid] == SerializeStall) {
472        ++renameSerializeStallCycles;
473    }
474
475    if (renameStatus[tid] == Running ||
476        renameStatus[tid] == Idle) {
477        DPRINTF(Rename, "[tid:%u]: Not blocked, so attempting to run "
478                "stage.\n", tid);
479
480        renameInsts(tid);
481    } else if (renameStatus[tid] == Unblocking) {
482        renameInsts(tid);
483
484        if (validInsts()) {
485            // Add the current inputs to the skid buffer so they can be
486            // reprocessed when this stage unblocks.
487            skidInsert(tid);
488        }
489
490        // If we switched over to blocking, then there's a potential for
491        // an overall status change.
492        status_change = unblock(tid) || status_change || blockThisCycle;
493    }
494}
495
496template <class Impl>
497void
498DefaultRename<Impl>::renameInsts(unsigned tid)
499{
500    // Instructions can be either in the skid buffer or the queue of
501    // instructions coming from decode, depending on the status.
502    int insts_available = renameStatus[tid] == Unblocking ?
503        skidBuffer[tid].size() : insts[tid].size();
504
505    // Check the decode queue to see if instructions are available.
506    // If there are no available instructions to rename, then do nothing.
507    if (insts_available == 0) {
508        DPRINTF(Rename, "[tid:%u]: Nothing to do, breaking out early.\n",
509                tid);
510        // Should I change status to idle?
511        ++renameIdleCycles;
512        return;
513    } else if (renameStatus[tid] == Unblocking) {
514        ++renameUnblockCycles;
515    } else if (renameStatus[tid] == Running) {
516        ++renameRunCycles;
517    }
518
519    DynInstPtr inst;
520
521    // Will have to do a different calculation for the number of free
522    // entries.
523    int free_rob_entries = calcFreeROBEntries(tid);
524    int free_iq_entries  = calcFreeIQEntries(tid);
525    int free_lsq_entries = calcFreeLSQEntries(tid);
526    int min_free_entries = free_rob_entries;
527
528    FullSource source = ROB;
529
530    if (free_iq_entries < min_free_entries) {
531        min_free_entries = free_iq_entries;
532        source = IQ;
533    }
534
535    if (free_lsq_entries < min_free_entries) {
536        min_free_entries = free_lsq_entries;
537        source = LSQ;
538    }
539
540    // Check if there's any space left.
541    if (min_free_entries <= 0) {
542        DPRINTF(Rename, "[tid:%u]: Blocking due to no free ROB/IQ/LSQ "
543                "entries.\n"
544                "ROB has %i free entries.\n"
545                "IQ has %i free entries.\n"
546                "LSQ has %i free entries.\n",
547                tid,
548                free_rob_entries,
549                free_iq_entries,
550                free_lsq_entries);
551
552        blockThisCycle = true;
553
554        block(tid);
555
556        incrFullStat(source);
557
558        return;
559    } else if (min_free_entries < insts_available) {
560        DPRINTF(Rename, "[tid:%u]: Will have to block this cycle."
561                "%i insts available, but only %i insts can be "
562                "renamed due to ROB/IQ/LSQ limits.\n",
563                tid, insts_available, min_free_entries);
564
565        insts_available = min_free_entries;
566
567        blockThisCycle = true;
568
569        incrFullStat(source);
570    }
571
572    InstQueue &insts_to_rename = renameStatus[tid] == Unblocking ?
573        skidBuffer[tid] : insts[tid];
574
575    DPRINTF(Rename, "[tid:%u]: %i available instructions to "
576            "send iew.\n", tid, insts_available);
577
578    DPRINTF(Rename, "[tid:%u]: %i insts pipelining from Rename | %i insts "
579            "dispatched to IQ last cycle.\n",
580            tid, instsInProgress[tid], fromIEW->iewInfo[tid].dispatched);
581
582    // Handle serializing the next instruction if necessary.
583    if (serializeOnNextInst[tid]) {
584        if (emptyROB[tid] && instsInProgress[tid] == 0) {
585            // ROB already empty; no need to serialize.
586            serializeOnNextInst[tid] = false;
587        } else if (!insts_to_rename.empty()) {
588            insts_to_rename.front()->setSerializeBefore();
589        }
590    }
591
592    int renamed_insts = 0;
593
594    while (insts_available > 0 &&  toIEWIndex < renameWidth) {
595        DPRINTF(Rename, "[tid:%u]: Sending instructions to IEW.\n", tid);
596
597        assert(!insts_to_rename.empty());
598
599        inst = insts_to_rename.front();
600
601        insts_to_rename.pop_front();
602
603        if (renameStatus[tid] == Unblocking) {
604            DPRINTF(Rename,"[tid:%u]: Removing [sn:%lli] PC:%#x from rename "
605                    "skidBuffer\n",
606                    tid, inst->seqNum, inst->readPC());
607        }
608
609        if (inst->isSquashed()) {
610            DPRINTF(Rename, "[tid:%u]: instruction %i with PC %#x is "
611                    "squashed, skipping.\n",
612                    tid, inst->seqNum, inst->readPC());
613
614            ++renameSquashedInsts;
615
616            // Decrement how many instructions are available.
617            --insts_available;
618
619            continue;
620        }
621
622        DPRINTF(Rename, "[tid:%u]: Processing instruction [sn:%lli] with "
623                "PC %#x.\n",
624                tid, inst->seqNum, inst->readPC());
625
626        // Handle serializeAfter/serializeBefore instructions.
627        // serializeAfter marks the next instruction as serializeBefore.
628        // serializeBefore makes the instruction wait in rename until the ROB
629        // is empty.
630
631        // In this model, IPR accesses are serialize before
632        // instructions, and store conditionals are serialize after
633        // instructions.  This is mainly due to lack of support for
634        // out-of-order operations of either of those classes of
635        // instructions.
636        if ((inst->isIprAccess() || inst->isSerializeBefore()) &&
637            !inst->isSerializeHandled()) {
638            DPRINTF(Rename, "Serialize before instruction encountered.\n");
639
640            if (!inst->isTempSerializeBefore()) {
641                renamedSerializing++;
642                inst->setSerializeHandled();
643            } else {
644                renamedTempSerializing++;
645            }
646
647            // Change status over to SerializeStall so that other stages know
648            // what this is blocked on.
649            renameStatus[tid] = SerializeStall;
650
651            serializeInst[tid] = inst;
652
653            blockThisCycle = true;
654
655            break;
656        } else if ((inst->isStoreConditional() || inst->isSerializeAfter()) &&
657                   !inst->isSerializeHandled()) {
658            DPRINTF(Rename, "Serialize after instruction encountered.\n");
659
660            renamedSerializing++;
661
662            inst->setSerializeHandled();
663
664            serializeAfter(insts_to_rename, tid);
665        }
666
667        // Check here to make sure there are enough destination registers
668        // to rename to.  Otherwise block.
669        if (renameMap[tid]->numFreeEntries() < inst->numDestRegs()) {
670            DPRINTF(Rename, "Blocking due to lack of free "
671                    "physical registers to rename to.\n");
672            blockThisCycle = true;
673
674            ++renameFullRegistersEvents;
675
676            break;
677        }
678
679        renameSrcRegs(inst, inst->threadNumber);
680
681        renameDestRegs(inst, inst->threadNumber);
682
683        ++renamed_insts;
684
685        // Put instruction in rename queue.
686        toIEW->insts[toIEWIndex] = inst;
687        ++(toIEW->size);
688
689        // Increment which instruction we're on.
690        ++toIEWIndex;
691
692        // Decrement how many instructions are available.
693        --insts_available;
694    }
695
696    instsInProgress[tid] += renamed_insts;
697    renameRenamedInsts += renamed_insts;
698
699    // If we wrote to the time buffer, record this.
700    if (toIEWIndex) {
701        wroteToTimeBuffer = true;
702    }
703
704    // Check if there's any instructions left that haven't yet been renamed.
705    // If so then block.
706    if (insts_available) {
707        blockThisCycle = true;
708    }
709
710    if (blockThisCycle) {
711        block(tid);
712        toDecode->renameUnblock[tid] = false;
713    }
714}
715
716template<class Impl>
717void
718DefaultRename<Impl>::skidInsert(unsigned tid)
719{
720    DynInstPtr inst = NULL;
721
722    while (!insts[tid].empty()) {
723        inst = insts[tid].front();
724
725        insts[tid].pop_front();
726
727        assert(tid == inst->threadNumber);
728
729        DPRINTF(Rename, "[tid:%u]: Inserting [sn:%lli] PC:%#x into Rename "
730                "skidBuffer\n", tid, inst->seqNum, inst->readPC());
731
732        ++renameSkidInsts;
733
734        skidBuffer[tid].push_back(inst);
735    }
736
737    if (skidBuffer[tid].size() > skidBufferMax)
738        panic("Skidbuffer Exceeded Max Size");
739}
740
741template <class Impl>
742void
743DefaultRename<Impl>::sortInsts()
744{
745    int insts_from_decode = fromDecode->size;
746#ifdef DEBUG
747#if THE_ISA == ALPHA_ISA
748    for (int i=0; i < numThreads; i++)
749        assert(insts[i].empty());
750#endif
751#endif
752    for (int i = 0; i < insts_from_decode; ++i) {
753        DynInstPtr inst = fromDecode->insts[i];
754        insts[inst->threadNumber].push_back(inst);
755    }
756}
757
758template<class Impl>
759bool
760DefaultRename<Impl>::skidsEmpty()
761{
762    list<unsigned>::iterator threads = (*activeThreads).begin();
763
764    while (threads != (*activeThreads).end()) {
765        if (!skidBuffer[*threads++].empty())
766            return false;
767    }
768
769    return true;
770}
771
772template<class Impl>
773void
774DefaultRename<Impl>::updateStatus()
775{
776    bool any_unblocking = false;
777
778    list<unsigned>::iterator threads = (*activeThreads).begin();
779
780    threads = (*activeThreads).begin();
781
782    while (threads != (*activeThreads).end()) {
783        unsigned tid = *threads++;
784
785        if (renameStatus[tid] == Unblocking) {
786            any_unblocking = true;
787            break;
788        }
789    }
790
791    // Rename will have activity if it's unblocking.
792    if (any_unblocking) {
793        if (_status == Inactive) {
794            _status = Active;
795
796            DPRINTF(Activity, "Activating stage.\n");
797
798            cpu->activateStage(O3CPU::RenameIdx);
799        }
800    } else {
801        // If it's not unblocking, then rename will not have any internal
802        // activity.  Switch it to inactive.
803        if (_status == Active) {
804            _status = Inactive;
805            DPRINTF(Activity, "Deactivating stage.\n");
806
807            cpu->deactivateStage(O3CPU::RenameIdx);
808        }
809    }
810}
811
812template <class Impl>
813bool
814DefaultRename<Impl>::block(unsigned tid)
815{
816    DPRINTF(Rename, "[tid:%u]: Blocking.\n", tid);
817
818    // Add the current inputs onto the skid buffer, so they can be
819    // reprocessed when this stage unblocks.
820    skidInsert(tid);
821
822    // Only signal backwards to block if the previous stages do not think
823    // rename is already blocked.
824    if (renameStatus[tid] != Blocked) {
825        if (renameStatus[tid] != Unblocking) {
826            toDecode->renameBlock[tid] = true;
827            toDecode->renameUnblock[tid] = false;
828            wroteToTimeBuffer = true;
829        }
830
831        // Rename can not go from SerializeStall to Blocked, otherwise
832        // it would not know to complete the serialize stall.
833        if (renameStatus[tid] != SerializeStall) {
834            // Set status to Blocked.
835            renameStatus[tid] = Blocked;
836            return true;
837        }
838    }
839
840    return false;
841}
842
843template <class Impl>
844bool
845DefaultRename<Impl>::unblock(unsigned tid)
846{
847    DPRINTF(Rename, "[tid:%u]: Trying to unblock.\n", tid);
848
849    // Rename is done unblocking if the skid buffer is empty.
850    if (skidBuffer[tid].empty() && renameStatus[tid] != SerializeStall) {
851
852        DPRINTF(Rename, "[tid:%u]: Done unblocking.\n", tid);
853
854        toDecode->renameUnblock[tid] = true;
855        wroteToTimeBuffer = true;
856
857        renameStatus[tid] = Running;
858        return true;
859    }
860
861    return false;
862}
863
864template <class Impl>
865void
866DefaultRename<Impl>::doSquash(const InstSeqNum &squashed_seq_num, unsigned tid)
867{
868    typename list<RenameHistory>::iterator hb_it = historyBuffer[tid].begin();
869
870    // After a syscall squashes everything, the history buffer may be empty
871    // but the ROB may still be squashing instructions.
872    if (historyBuffer[tid].empty()) {
873        return;
874    }
875
876    // Go through the most recent instructions, undoing the mappings
877    // they did and freeing up the registers.
878    while (!historyBuffer[tid].empty() &&
879           (*hb_it).instSeqNum > squashed_seq_num) {
880        assert(hb_it != historyBuffer[tid].end());
881
882        DPRINTF(Rename, "[tid:%u]: Removing history entry with sequence "
883                "number %i.\n", tid, (*hb_it).instSeqNum);
884
885        // Tell the rename map to set the architected register to the
886        // previous physical register that it was renamed to.
887        renameMap[tid]->setEntry(hb_it->archReg, hb_it->prevPhysReg);
888
889        // Put the renamed physical register back on the free list.
890        freeList->addReg(hb_it->newPhysReg);
891
892        historyBuffer[tid].erase(hb_it++);
893
894        ++renameUndoneMaps;
895    }
896}
897
898template<class Impl>
899void
900DefaultRename<Impl>::removeFromHistory(InstSeqNum inst_seq_num, unsigned tid)
901{
902    DPRINTF(Rename, "[tid:%u]: Removing a committed instruction from the "
903            "history buffer %u (size=%i), until [sn:%lli].\n",
904            tid, tid, historyBuffer[tid].size(), inst_seq_num);
905
906    typename list<RenameHistory>::iterator hb_it = historyBuffer[tid].end();
907
908    --hb_it;
909
910    if (historyBuffer[tid].empty()) {
911        DPRINTF(Rename, "[tid:%u]: History buffer is empty.\n", tid);
912        return;
913    } else if (hb_it->instSeqNum > inst_seq_num) {
914        DPRINTF(Rename, "[tid:%u]: Old sequence number encountered.  Ensure "
915                "that a syscall happened recently.\n", tid);
916        return;
917    }
918
919    // Commit all the renames up until (and including) the committed sequence
920    // number. Some or even all of the committed instructions may not have
921    // rename histories if they did not have destination registers that were
922    // renamed.
923    while (!historyBuffer[tid].empty() &&
924           hb_it != historyBuffer[tid].end() &&
925           (*hb_it).instSeqNum <= inst_seq_num) {
926
927        DPRINTF(Rename, "[tid:%u]: Freeing up older rename of reg %i, "
928                "[sn:%lli].\n",
929                tid, (*hb_it).prevPhysReg, (*hb_it).instSeqNum);
930
931        freeList->addReg((*hb_it).prevPhysReg);
932        ++renameCommittedMaps;
933
934        historyBuffer[tid].erase(hb_it--);
935    }
936}
937
938template <class Impl>
939inline void
940DefaultRename<Impl>::renameSrcRegs(DynInstPtr &inst,unsigned tid)
941{
942    assert(renameMap[tid] != 0);
943
944    unsigned num_src_regs = inst->numSrcRegs();
945
946    // Get the architectual register numbers from the source and
947    // destination operands, and redirect them to the right register.
948    // Will need to mark dependencies though.
949    for (int src_idx = 0; src_idx < num_src_regs; src_idx++) {
950        RegIndex src_reg = inst->srcRegIdx(src_idx);
951
952        // Look up the source registers to get the phys. register they've
953        // been renamed to, and set the sources to those registers.
954        PhysRegIndex renamed_reg = renameMap[tid]->lookup(src_reg);
955
956        DPRINTF(Rename, "[tid:%u]: Looking up arch reg %i, got "
957                "physical reg %i.\n", tid, (int)src_reg,
958                (int)renamed_reg);
959
960        inst->renameSrcReg(src_idx, renamed_reg);
961
962        // See if the register is ready or not.
963        if (scoreboard->getReg(renamed_reg) == true) {
964            DPRINTF(Rename, "[tid:%u]: Register is ready.\n", tid);
965
966            inst->markSrcRegReady(src_idx);
967        }
968
969        ++renameRenameLookups;
970    }
971}
972
973template <class Impl>
974inline void
975DefaultRename<Impl>::renameDestRegs(DynInstPtr &inst,unsigned tid)
976{
977    typename RenameMap::RenameInfo rename_result;
978
979    unsigned num_dest_regs = inst->numDestRegs();
980
981    // Rename the destination registers.
982    for (int dest_idx = 0; dest_idx < num_dest_regs; dest_idx++) {
983        RegIndex dest_reg = inst->destRegIdx(dest_idx);
984
985        // Get the physical register that the destination will be
986        // renamed to.
987        rename_result = renameMap[tid]->rename(dest_reg);
988
989        //Mark Scoreboard entry as not ready
990        scoreboard->unsetReg(rename_result.first);
991
992        DPRINTF(Rename, "[tid:%u]: Renaming arch reg %i to physical "
993                "reg %i.\n", tid, (int)dest_reg,
994                (int)rename_result.first);
995
996        // Record the rename information so that a history can be kept.
997        RenameHistory hb_entry(inst->seqNum, dest_reg,
998                               rename_result.first,
999                               rename_result.second);
1000
1001        historyBuffer[tid].push_front(hb_entry);
1002
1003        DPRINTF(Rename, "[tid:%u]: Adding instruction to history buffer "
1004                "(size=%i), [sn:%lli].\n",tid,
1005                historyBuffer[tid].size(),
1006                (*historyBuffer[tid].begin()).instSeqNum);
1007
1008        // Tell the instruction to rename the appropriate destination
1009        // register (dest_idx) to the new physical register
1010        // (rename_result.first), and record the previous physical
1011        // register that the same logical register was renamed to
1012        // (rename_result.second).
1013        inst->renameDestReg(dest_idx,
1014                            rename_result.first,
1015                            rename_result.second);
1016
1017        ++renameRenamedOperands;
1018    }
1019}
1020
1021template <class Impl>
1022inline int
1023DefaultRename<Impl>::calcFreeROBEntries(unsigned tid)
1024{
1025    int num_free = freeEntries[tid].robEntries -
1026                  (instsInProgress[tid] - fromIEW->iewInfo[tid].dispatched);
1027
1028    //DPRINTF(Rename,"[tid:%i]: %i rob free\n",tid,num_free);
1029
1030    return num_free;
1031}
1032
1033template <class Impl>
1034inline int
1035DefaultRename<Impl>::calcFreeIQEntries(unsigned tid)
1036{
1037    int num_free = freeEntries[tid].iqEntries -
1038                  (instsInProgress[tid] - fromIEW->iewInfo[tid].dispatched);
1039
1040    //DPRINTF(Rename,"[tid:%i]: %i iq free\n",tid,num_free);
1041
1042    return num_free;
1043}
1044
1045template <class Impl>
1046inline int
1047DefaultRename<Impl>::calcFreeLSQEntries(unsigned tid)
1048{
1049    int num_free = freeEntries[tid].lsqEntries -
1050                  (instsInProgress[tid] - fromIEW->iewInfo[tid].dispatchedToLSQ);
1051
1052    //DPRINTF(Rename,"[tid:%i]: %i lsq free\n",tid,num_free);
1053
1054    return num_free;
1055}
1056
1057template <class Impl>
1058unsigned
1059DefaultRename<Impl>::validInsts()
1060{
1061    unsigned inst_count = 0;
1062
1063    for (int i=0; i<fromDecode->size; i++) {
1064        if (!fromDecode->insts[i]->isSquashed())
1065            inst_count++;
1066    }
1067
1068    return inst_count;
1069}
1070
1071template <class Impl>
1072void
1073DefaultRename<Impl>::readStallSignals(unsigned tid)
1074{
1075    if (fromIEW->iewBlock[tid]) {
1076        stalls[tid].iew = true;
1077    }
1078
1079    if (fromIEW->iewUnblock[tid]) {
1080        assert(stalls[tid].iew);
1081        stalls[tid].iew = false;
1082    }
1083
1084    if (fromCommit->commitBlock[tid]) {
1085        stalls[tid].commit = true;
1086    }
1087
1088    if (fromCommit->commitUnblock[tid]) {
1089        assert(stalls[tid].commit);
1090        stalls[tid].commit = false;
1091    }
1092}
1093
1094template <class Impl>
1095bool
1096DefaultRename<Impl>::checkStall(unsigned tid)
1097{
1098    bool ret_val = false;
1099
1100    if (stalls[tid].iew) {
1101        DPRINTF(Rename,"[tid:%i]: Stall from IEW stage detected.\n", tid);
1102        ret_val = true;
1103    } else if (stalls[tid].commit) {
1104        DPRINTF(Rename,"[tid:%i]: Stall from Commit stage detected.\n", tid);
1105        ret_val = true;
1106    } else if (calcFreeROBEntries(tid) <= 0) {
1107        DPRINTF(Rename,"[tid:%i]: Stall: ROB has 0 free entries.\n", tid);
1108        ret_val = true;
1109    } else if (calcFreeIQEntries(tid) <= 0) {
1110        DPRINTF(Rename,"[tid:%i]: Stall: IQ has 0 free entries.\n", tid);
1111        ret_val = true;
1112    } else if (calcFreeLSQEntries(tid) <= 0) {
1113        DPRINTF(Rename,"[tid:%i]: Stall: LSQ has 0 free entries.\n", tid);
1114        ret_val = true;
1115    } else if (renameMap[tid]->numFreeEntries() <= 0) {
1116        DPRINTF(Rename,"[tid:%i]: Stall: RenameMap has 0 free entries.\n", tid);
1117        ret_val = true;
1118    } else if (renameStatus[tid] == SerializeStall &&
1119               (!emptyROB[tid] || instsInProgress[tid])) {
1120        DPRINTF(Rename,"[tid:%i]: Stall: Serialize stall and ROB is not "
1121                "empty.\n",
1122                tid);
1123        ret_val = true;
1124    }
1125
1126    return ret_val;
1127}
1128
1129template <class Impl>
1130void
1131DefaultRename<Impl>::readFreeEntries(unsigned tid)
1132{
1133    bool updated = false;
1134    if (fromIEW->iewInfo[tid].usedIQ) {
1135        freeEntries[tid].iqEntries =
1136            fromIEW->iewInfo[tid].freeIQEntries;
1137        updated = true;
1138    }
1139
1140    if (fromIEW->iewInfo[tid].usedLSQ) {
1141        freeEntries[tid].lsqEntries =
1142            fromIEW->iewInfo[tid].freeLSQEntries;
1143        updated = true;
1144    }
1145
1146    if (fromCommit->commitInfo[tid].usedROB) {
1147        freeEntries[tid].robEntries =
1148            fromCommit->commitInfo[tid].freeROBEntries;
1149        emptyROB[tid] = fromCommit->commitInfo[tid].emptyROB;
1150        updated = true;
1151    }
1152
1153    DPRINTF(Rename, "[tid:%i]: Free IQ: %i, Free ROB: %i, Free LSQ: %i\n",
1154            tid,
1155            freeEntries[tid].iqEntries,
1156            freeEntries[tid].robEntries,
1157            freeEntries[tid].lsqEntries);
1158
1159    DPRINTF(Rename, "[tid:%i]: %i instructions not yet in ROB\n",
1160            tid, instsInProgress[tid]);
1161}
1162
1163template <class Impl>
1164bool
1165DefaultRename<Impl>::checkSignalsAndUpdate(unsigned tid)
1166{
1167    // Check if there's a squash signal, squash if there is
1168    // Check stall signals, block if necessary.
1169    // If status was blocked
1170    //     check if stall conditions have passed
1171    //         if so then go to unblocking
1172    // If status was Squashing
1173    //     check if squashing is not high.  Switch to running this cycle.
1174    // If status was serialize stall
1175    //     check if ROB is empty and no insts are in flight to the ROB
1176
1177    readFreeEntries(tid);
1178    readStallSignals(tid);
1179
1180    if (fromCommit->commitInfo[tid].squash) {
1181        DPRINTF(Rename, "[tid:%u]: Squashing instructions due to squash from "
1182                "commit.\n", tid);
1183
1184#if THE_ISA == ALPHA_ISA
1185        InstSeqNum squashed_seq_num = fromCommit->commitInfo[tid].doneSeqNum;
1186#else
1187        InstSeqNum squashed_seq_num = fromCommit->commitInfo[tid].bdelayDoneSeqNum;
1188#endif
1189
1190        squash(squashed_seq_num, tid);
1191
1192        return true;
1193    }
1194
1195    if (fromCommit->commitInfo[tid].robSquashing) {
1196        DPRINTF(Rename, "[tid:%u]: ROB is still squashing.\n", tid);
1197
1198        renameStatus[tid] = Squashing;
1199
1200        return true;
1201    }
1202
1203    if (checkStall(tid)) {
1204        return block(tid);
1205    }
1206
1207    if (renameStatus[tid] == Blocked) {
1208        DPRINTF(Rename, "[tid:%u]: Done blocking, switching to unblocking.\n",
1209                tid);
1210
1211        renameStatus[tid] = Unblocking;
1212
1213        unblock(tid);
1214
1215        return true;
1216    }
1217
1218    if (renameStatus[tid] == Squashing) {
1219        // Switch status to running if rename isn't being told to block or
1220        // squash this cycle.
1221        DPRINTF(Rename, "[tid:%u]: Done squashing, switching to running.\n",
1222                tid);
1223
1224        renameStatus[tid] = Running;
1225
1226        return false;
1227    }
1228
1229    if (renameStatus[tid] == SerializeStall) {
1230        // Stall ends once the ROB is free.
1231        DPRINTF(Rename, "[tid:%u]: Done with serialize stall, switching to "
1232                "unblocking.\n", tid);
1233
1234        DynInstPtr serial_inst = serializeInst[tid];
1235
1236        renameStatus[tid] = Unblocking;
1237
1238        unblock(tid);
1239
1240        DPRINTF(Rename, "[tid:%u]: Processing instruction [%lli] with "
1241                "PC %#x.\n",
1242                tid, serial_inst->seqNum, serial_inst->readPC());
1243
1244        // Put instruction into queue here.
1245        serial_inst->clearSerializeBefore();
1246
1247        if (!skidBuffer[tid].empty()) {
1248            skidBuffer[tid].push_front(serial_inst);
1249        } else {
1250            insts[tid].push_front(serial_inst);
1251        }
1252
1253        DPRINTF(Rename, "[tid:%u]: Instruction must be processed by rename."
1254                " Adding to front of list.\n", tid);
1255
1256        serializeInst[tid] = NULL;
1257
1258        return true;
1259    }
1260
1261    // If we've reached this point, we have not gotten any signals that
1262    // cause rename to change its status.  Rename remains the same as before.
1263    return false;
1264}
1265
1266template<class Impl>
1267void
1268DefaultRename<Impl>::serializeAfter(InstQueue &inst_list,
1269                                   unsigned tid)
1270{
1271    if (inst_list.empty()) {
1272        // Mark a bit to say that I must serialize on the next instruction.
1273        serializeOnNextInst[tid] = true;
1274        return;
1275    }
1276
1277    // Set the next instruction as serializing.
1278    inst_list.front()->setSerializeBefore();
1279}
1280
1281template <class Impl>
1282inline void
1283DefaultRename<Impl>::incrFullStat(const FullSource &source)
1284{
1285    switch (source) {
1286      case ROB:
1287        ++renameROBFullEvents;
1288        break;
1289      case IQ:
1290        ++renameIQFullEvents;
1291        break;
1292      case LSQ:
1293        ++renameLSQFullEvents;
1294        break;
1295      default:
1296        panic("Rename full stall stat should be incremented for a reason!");
1297        break;
1298    }
1299}
1300
1301template <class Impl>
1302void
1303DefaultRename<Impl>::dumpHistory()
1304{
1305    typename list<RenameHistory>::iterator buf_it;
1306
1307    for (int i = 0; i < numThreads; i++) {
1308
1309        buf_it = historyBuffer[i].begin();
1310
1311        while (buf_it != historyBuffer[i].end()) {
1312            cprintf("Seq num: %i\nArch reg: %i New phys reg: %i Old phys "
1313                    "reg: %i\n", (*buf_it).instSeqNum, (int)(*buf_it).archReg,
1314                    (int)(*buf_it).newPhysReg, (int)(*buf_it).prevPhysReg);
1315
1316            buf_it++;
1317        }
1318    }
1319}
1320