cpu.cc revision 12109:f29e9c5418aa
1/*
2 * Copyright (c) 2011-2012, 2014, 2016 ARM Limited
3 * Copyright (c) 2013 Advanced Micro Devices, Inc.
4 * All rights reserved
5 *
6 * The license below extends only to copyright in the software and shall
7 * not be construed as granting a license to any other intellectual
8 * property including but not limited to intellectual property relating
9 * to a hardware implementation of the functionality of the software
10 * licensed hereunder.  You may use the software subject to the license
11 * terms below provided that you ensure that this notice is replicated
12 * unmodified and in its entirety in all distributions of the software,
13 * modified or unmodified, in source code or in binary form.
14 *
15 * Copyright (c) 2004-2006 The Regents of The University of Michigan
16 * Copyright (c) 2011 Regents of the University of California
17 * All rights reserved.
18 *
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions are
21 * met: redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimer;
23 * redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution;
26 * neither the name of the copyright holders nor the names of its
27 * contributors may be used to endorse or promote products derived from
28 * this software without specific prior written permission.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
31 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
32 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
33 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
34 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
36 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
40 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 *
42 * Authors: Kevin Lim
43 *          Korey Sewell
44 *          Rick Strong
45 */
46
47#include "cpu/o3/cpu.hh"
48
49#include "arch/generic/traits.hh"
50#include "arch/kernel_stats.hh"
51#include "config/the_isa.hh"
52#include "cpu/activity.hh"
53#include "cpu/checker/cpu.hh"
54#include "cpu/checker/thread_context.hh"
55#include "cpu/o3/isa_specific.hh"
56#include "cpu/o3/thread_context.hh"
57#include "cpu/quiesce_event.hh"
58#include "cpu/simple_thread.hh"
59#include "cpu/thread_context.hh"
60#include "debug/Activity.hh"
61#include "debug/Drain.hh"
62#include "debug/O3CPU.hh"
63#include "debug/Quiesce.hh"
64#include "enums/MemoryMode.hh"
65#include "sim/core.hh"
66#include "sim/full_system.hh"
67#include "sim/process.hh"
68#include "sim/stat_control.hh"
69#include "sim/system.hh"
70
71#if THE_ISA == ALPHA_ISA
72#include "arch/alpha/osfpal.hh"
73#include "debug/Activity.hh"
74
75#endif
76
77struct BaseCPUParams;
78
79using namespace TheISA;
80using namespace std;
81
82BaseO3CPU::BaseO3CPU(BaseCPUParams *params)
83    : BaseCPU(params)
84{
85}
86
87void
88BaseO3CPU::regStats()
89{
90    BaseCPU::regStats();
91}
92
93template<class Impl>
94bool
95FullO3CPU<Impl>::IcachePort::recvTimingResp(PacketPtr pkt)
96{
97    DPRINTF(O3CPU, "Fetch unit received timing\n");
98    // We shouldn't ever get a cacheable block in Modified state
99    assert(pkt->req->isUncacheable() ||
100           !(pkt->cacheResponding() && !pkt->hasSharers()));
101    fetch->processCacheCompletion(pkt);
102
103    return true;
104}
105
106template<class Impl>
107void
108FullO3CPU<Impl>::IcachePort::recvReqRetry()
109{
110    fetch->recvReqRetry();
111}
112
113template <class Impl>
114bool
115FullO3CPU<Impl>::DcachePort::recvTimingResp(PacketPtr pkt)
116{
117    return lsq->recvTimingResp(pkt);
118}
119
120template <class Impl>
121void
122FullO3CPU<Impl>::DcachePort::recvTimingSnoopReq(PacketPtr pkt)
123{
124    for (ThreadID tid = 0; tid < cpu->numThreads; tid++) {
125        if (cpu->getCpuAddrMonitor(tid)->doMonitor(pkt)) {
126            cpu->wakeup(tid);
127        }
128    }
129    lsq->recvTimingSnoopReq(pkt);
130}
131
132template <class Impl>
133void
134FullO3CPU<Impl>::DcachePort::recvReqRetry()
135{
136    lsq->recvReqRetry();
137}
138
139template <class Impl>
140FullO3CPU<Impl>::TickEvent::TickEvent(FullO3CPU<Impl> *c)
141    : Event(CPU_Tick_Pri), cpu(c)
142{
143}
144
145template <class Impl>
146void
147FullO3CPU<Impl>::TickEvent::process()
148{
149    cpu->tick();
150}
151
152template <class Impl>
153const char *
154FullO3CPU<Impl>::TickEvent::description() const
155{
156    return "FullO3CPU tick";
157}
158
159template <class Impl>
160FullO3CPU<Impl>::FullO3CPU(DerivO3CPUParams *params)
161    : BaseO3CPU(params),
162      itb(params->itb),
163      dtb(params->dtb),
164      tickEvent(this),
165#ifndef NDEBUG
166      instcount(0),
167#endif
168      removeInstsThisCycle(false),
169      fetch(this, params),
170      decode(this, params),
171      rename(this, params),
172      iew(this, params),
173      commit(this, params),
174
175      /* It is mandatory that all SMT threads use the same renaming mode as
176       * they are sharing registers and rename */
177      vecMode(initRenameMode<TheISA::ISA>::mode(params->isa[0])),
178      regFile(params->numPhysIntRegs,
179              params->numPhysFloatRegs,
180              params->numPhysVecRegs,
181              params->numPhysCCRegs,
182              vecMode),
183
184      freeList(name() + ".freelist", &regFile),
185
186      rob(this, params),
187
188      scoreboard(name() + ".scoreboard",
189                 regFile.totalNumPhysRegs()),
190
191      isa(numThreads, NULL),
192
193      icachePort(&fetch, this),
194      dcachePort(&iew.ldstQueue, this),
195
196      timeBuffer(params->backComSize, params->forwardComSize),
197      fetchQueue(params->backComSize, params->forwardComSize),
198      decodeQueue(params->backComSize, params->forwardComSize),
199      renameQueue(params->backComSize, params->forwardComSize),
200      iewQueue(params->backComSize, params->forwardComSize),
201      activityRec(name(), NumStages,
202                  params->backComSize + params->forwardComSize,
203                  params->activity),
204
205      globalSeqNum(1),
206      system(params->system),
207      lastRunningCycle(curCycle())
208{
209    if (!params->switched_out) {
210        _status = Running;
211    } else {
212        _status = SwitchedOut;
213    }
214
215    if (params->checker) {
216        BaseCPU *temp_checker = params->checker;
217        checker = dynamic_cast<Checker<Impl> *>(temp_checker);
218        checker->setIcachePort(&icachePort);
219        checker->setSystem(params->system);
220    } else {
221        checker = NULL;
222    }
223
224    if (!FullSystem) {
225        thread.resize(numThreads);
226        tids.resize(numThreads);
227    }
228
229    // The stages also need their CPU pointer setup.  However this
230    // must be done at the upper level CPU because they have pointers
231    // to the upper level CPU, and not this FullO3CPU.
232
233    // Set up Pointers to the activeThreads list for each stage
234    fetch.setActiveThreads(&activeThreads);
235    decode.setActiveThreads(&activeThreads);
236    rename.setActiveThreads(&activeThreads);
237    iew.setActiveThreads(&activeThreads);
238    commit.setActiveThreads(&activeThreads);
239
240    // Give each of the stages the time buffer they will use.
241    fetch.setTimeBuffer(&timeBuffer);
242    decode.setTimeBuffer(&timeBuffer);
243    rename.setTimeBuffer(&timeBuffer);
244    iew.setTimeBuffer(&timeBuffer);
245    commit.setTimeBuffer(&timeBuffer);
246
247    // Also setup each of the stages' queues.
248    fetch.setFetchQueue(&fetchQueue);
249    decode.setFetchQueue(&fetchQueue);
250    commit.setFetchQueue(&fetchQueue);
251    decode.setDecodeQueue(&decodeQueue);
252    rename.setDecodeQueue(&decodeQueue);
253    rename.setRenameQueue(&renameQueue);
254    iew.setRenameQueue(&renameQueue);
255    iew.setIEWQueue(&iewQueue);
256    commit.setIEWQueue(&iewQueue);
257    commit.setRenameQueue(&renameQueue);
258
259    commit.setIEWStage(&iew);
260    rename.setIEWStage(&iew);
261    rename.setCommitStage(&commit);
262
263    ThreadID active_threads;
264    if (FullSystem) {
265        active_threads = 1;
266    } else {
267        active_threads = params->workload.size();
268
269        if (active_threads > Impl::MaxThreads) {
270            panic("Workload Size too large. Increase the 'MaxThreads' "
271                  "constant in your O3CPU impl. file (e.g. o3/alpha/impl.hh) "
272                  "or edit your workload size.");
273        }
274    }
275
276    //Make Sure That this a Valid Architeture
277    assert(params->numPhysIntRegs   >= numThreads * TheISA::NumIntRegs);
278    assert(params->numPhysFloatRegs >= numThreads * TheISA::NumFloatRegs);
279    assert(params->numPhysVecRegs >= numThreads * TheISA::NumVecRegs);
280    assert(params->numPhysCCRegs >= numThreads * TheISA::NumCCRegs);
281
282    rename.setScoreboard(&scoreboard);
283    iew.setScoreboard(&scoreboard);
284
285    // Setup the rename map for whichever stages need it.
286    for (ThreadID tid = 0; tid < numThreads; tid++) {
287        isa[tid] = params->isa[tid];
288        assert(initRenameMode<TheISA::ISA>::equals(isa[tid], isa[0]));
289
290        // Only Alpha has an FP zero register, so for other ISAs we
291        // use an invalid FP register index to avoid special treatment
292        // of any valid FP reg.
293        RegIndex invalidFPReg = TheISA::NumFloatRegs + 1;
294        RegIndex fpZeroReg =
295            (THE_ISA == ALPHA_ISA) ? TheISA::ZeroReg : invalidFPReg;
296
297        commitRenameMap[tid].init(&regFile, TheISA::ZeroReg, fpZeroReg,
298                                  &freeList,
299                                  vecMode);
300
301        renameMap[tid].init(&regFile, TheISA::ZeroReg, fpZeroReg,
302                            &freeList, vecMode);
303    }
304
305    // Initialize rename map to assign physical registers to the
306    // architectural registers for active threads only.
307    for (ThreadID tid = 0; tid < active_threads; tid++) {
308        for (RegIndex ridx = 0; ridx < TheISA::NumIntRegs; ++ridx) {
309            // Note that we can't use the rename() method because we don't
310            // want special treatment for the zero register at this point
311            PhysRegIdPtr phys_reg = freeList.getIntReg();
312            renameMap[tid].setEntry(RegId(IntRegClass, ridx), phys_reg);
313            commitRenameMap[tid].setEntry(RegId(IntRegClass, ridx), phys_reg);
314        }
315
316        for (RegIndex ridx = 0; ridx < TheISA::NumFloatRegs; ++ridx) {
317            PhysRegIdPtr phys_reg = freeList.getFloatReg();
318            renameMap[tid].setEntry(RegId(FloatRegClass, ridx), phys_reg);
319            commitRenameMap[tid].setEntry(
320                    RegId(FloatRegClass, ridx), phys_reg);
321        }
322
323        /* Here we need two 'interfaces' the 'whole register' and the
324         * 'register element'. At any point only one of them will be
325         * active. */
326        if (vecMode == Enums::Full) {
327            /* Initialize the full-vector interface */
328            for (RegIndex ridx = 0; ridx < TheISA::NumVecRegs; ++ridx) {
329                RegId rid = RegId(VecRegClass, ridx);
330                PhysRegIdPtr phys_reg = freeList.getVecReg();
331                renameMap[tid].setEntry(rid, phys_reg);
332                commitRenameMap[tid].setEntry(rid, phys_reg);
333            }
334        } else {
335            /* Initialize the vector-element interface */
336            for (RegIndex ridx = 0; ridx < TheISA::NumVecRegs; ++ridx) {
337                for (ElemIndex ldx = 0; ldx < TheISA::NumVecElemPerVecReg;
338                        ++ldx) {
339                    RegId lrid = RegId(VecElemClass, ridx, ldx);
340                    PhysRegIdPtr phys_elem = freeList.getVecElem();
341                    renameMap[tid].setEntry(lrid, phys_elem);
342                    commitRenameMap[tid].setEntry(lrid, phys_elem);
343                }
344            }
345        }
346
347        for (RegIndex ridx = 0; ridx < TheISA::NumCCRegs; ++ridx) {
348            PhysRegIdPtr phys_reg = freeList.getCCReg();
349            renameMap[tid].setEntry(RegId(CCRegClass, ridx), phys_reg);
350            commitRenameMap[tid].setEntry(RegId(CCRegClass, ridx), phys_reg);
351        }
352    }
353
354    rename.setRenameMap(renameMap);
355    commit.setRenameMap(commitRenameMap);
356    rename.setFreeList(&freeList);
357
358    // Setup the ROB for whichever stages need it.
359    commit.setROB(&rob);
360
361    lastActivatedCycle = 0;
362#if 0
363    // Give renameMap & rename stage access to the freeList;
364    for (ThreadID tid = 0; tid < numThreads; tid++)
365        globalSeqNum[tid] = 1;
366#endif
367
368    DPRINTF(O3CPU, "Creating O3CPU object.\n");
369
370    // Setup any thread state.
371    this->thread.resize(this->numThreads);
372
373    for (ThreadID tid = 0; tid < this->numThreads; ++tid) {
374        if (FullSystem) {
375            // SMT is not supported in FS mode yet.
376            assert(this->numThreads == 1);
377            this->thread[tid] = new Thread(this, 0, NULL);
378        } else {
379            if (tid < params->workload.size()) {
380                DPRINTF(O3CPU, "Workload[%i] process is %#x",
381                        tid, this->thread[tid]);
382                this->thread[tid] = new typename FullO3CPU<Impl>::Thread(
383                        (typename Impl::O3CPU *)(this),
384                        tid, params->workload[tid]);
385
386                //usedTids[tid] = true;
387                //threadMap[tid] = tid;
388            } else {
389                //Allocate Empty thread so M5 can use later
390                //when scheduling threads to CPU
391                Process* dummy_proc = NULL;
392
393                this->thread[tid] = new typename FullO3CPU<Impl>::Thread(
394                        (typename Impl::O3CPU *)(this),
395                        tid, dummy_proc);
396                //usedTids[tid] = false;
397            }
398        }
399
400        ThreadContext *tc;
401
402        // Setup the TC that will serve as the interface to the threads/CPU.
403        O3ThreadContext<Impl> *o3_tc = new O3ThreadContext<Impl>;
404
405        tc = o3_tc;
406
407        // If we're using a checker, then the TC should be the
408        // CheckerThreadContext.
409        if (params->checker) {
410            tc = new CheckerThreadContext<O3ThreadContext<Impl> >(
411                o3_tc, this->checker);
412        }
413
414        o3_tc->cpu = (typename Impl::O3CPU *)(this);
415        assert(o3_tc->cpu);
416        o3_tc->thread = this->thread[tid];
417
418        // Setup quiesce event.
419        this->thread[tid]->quiesceEvent = new EndQuiesceEvent(tc);
420
421        // Give the thread the TC.
422        this->thread[tid]->tc = tc;
423
424        // Add the TC to the CPU's list of TC's.
425        this->threadContexts.push_back(tc);
426    }
427
428    // FullO3CPU always requires an interrupt controller.
429    if (!params->switched_out && interrupts.empty()) {
430        fatal("FullO3CPU %s has no interrupt controller.\n"
431              "Ensure createInterruptController() is called.\n", name());
432    }
433
434    for (ThreadID tid = 0; tid < this->numThreads; tid++)
435        this->thread[tid]->setFuncExeInst(0);
436}
437
438template <class Impl>
439FullO3CPU<Impl>::~FullO3CPU()
440{
441}
442
443template <class Impl>
444void
445FullO3CPU<Impl>::regProbePoints()
446{
447    BaseCPU::regProbePoints();
448
449    ppInstAccessComplete = new ProbePointArg<PacketPtr>(getProbeManager(), "InstAccessComplete");
450    ppDataAccessComplete = new ProbePointArg<std::pair<DynInstPtr, PacketPtr> >(getProbeManager(), "DataAccessComplete");
451
452    fetch.regProbePoints();
453    rename.regProbePoints();
454    iew.regProbePoints();
455    commit.regProbePoints();
456}
457
458template <class Impl>
459void
460FullO3CPU<Impl>::regStats()
461{
462    BaseO3CPU::regStats();
463
464    // Register any of the O3CPU's stats here.
465    timesIdled
466        .name(name() + ".timesIdled")
467        .desc("Number of times that the entire CPU went into an idle state and"
468              " unscheduled itself")
469        .prereq(timesIdled);
470
471    idleCycles
472        .name(name() + ".idleCycles")
473        .desc("Total number of cycles that the CPU has spent unscheduled due "
474              "to idling")
475        .prereq(idleCycles);
476
477    quiesceCycles
478        .name(name() + ".quiesceCycles")
479        .desc("Total number of cycles that CPU has spent quiesced or waiting "
480              "for an interrupt")
481        .prereq(quiesceCycles);
482
483    // Number of Instructions simulated
484    // --------------------------------
485    // Should probably be in Base CPU but need templated
486    // MaxThreads so put in here instead
487    committedInsts
488        .init(numThreads)
489        .name(name() + ".committedInsts")
490        .desc("Number of Instructions Simulated")
491        .flags(Stats::total);
492
493    committedOps
494        .init(numThreads)
495        .name(name() + ".committedOps")
496        .desc("Number of Ops (including micro ops) Simulated")
497        .flags(Stats::total);
498
499    cpi
500        .name(name() + ".cpi")
501        .desc("CPI: Cycles Per Instruction")
502        .precision(6);
503    cpi = numCycles / committedInsts;
504
505    totalCpi
506        .name(name() + ".cpi_total")
507        .desc("CPI: Total CPI of All Threads")
508        .precision(6);
509    totalCpi = numCycles / sum(committedInsts);
510
511    ipc
512        .name(name() + ".ipc")
513        .desc("IPC: Instructions Per Cycle")
514        .precision(6);
515    ipc =  committedInsts / numCycles;
516
517    totalIpc
518        .name(name() + ".ipc_total")
519        .desc("IPC: Total IPC of All Threads")
520        .precision(6);
521    totalIpc =  sum(committedInsts) / numCycles;
522
523    this->fetch.regStats();
524    this->decode.regStats();
525    this->rename.regStats();
526    this->iew.regStats();
527    this->commit.regStats();
528    this->rob.regStats();
529
530    intRegfileReads
531        .name(name() + ".int_regfile_reads")
532        .desc("number of integer regfile reads")
533        .prereq(intRegfileReads);
534
535    intRegfileWrites
536        .name(name() + ".int_regfile_writes")
537        .desc("number of integer regfile writes")
538        .prereq(intRegfileWrites);
539
540    fpRegfileReads
541        .name(name() + ".fp_regfile_reads")
542        .desc("number of floating regfile reads")
543        .prereq(fpRegfileReads);
544
545    fpRegfileWrites
546        .name(name() + ".fp_regfile_writes")
547        .desc("number of floating regfile writes")
548        .prereq(fpRegfileWrites);
549
550    vecRegfileReads
551        .name(name() + ".vec_regfile_reads")
552        .desc("number of vector regfile reads")
553        .prereq(vecRegfileReads);
554
555    vecRegfileWrites
556        .name(name() + ".vec_regfile_writes")
557        .desc("number of vector regfile writes")
558        .prereq(vecRegfileWrites);
559
560    ccRegfileReads
561        .name(name() + ".cc_regfile_reads")
562        .desc("number of cc regfile reads")
563        .prereq(ccRegfileReads);
564
565    ccRegfileWrites
566        .name(name() + ".cc_regfile_writes")
567        .desc("number of cc regfile writes")
568        .prereq(ccRegfileWrites);
569
570    miscRegfileReads
571        .name(name() + ".misc_regfile_reads")
572        .desc("number of misc regfile reads")
573        .prereq(miscRegfileReads);
574
575    miscRegfileWrites
576        .name(name() + ".misc_regfile_writes")
577        .desc("number of misc regfile writes")
578        .prereq(miscRegfileWrites);
579}
580
581template <class Impl>
582void
583FullO3CPU<Impl>::tick()
584{
585    DPRINTF(O3CPU, "\n\nFullO3CPU: Ticking main, FullO3CPU.\n");
586    assert(!switchedOut());
587    assert(drainState() != DrainState::Drained);
588
589    ++numCycles;
590    ppCycles->notify(1);
591
592//    activity = false;
593
594    //Tick each of the stages
595    fetch.tick();
596
597    decode.tick();
598
599    rename.tick();
600
601    iew.tick();
602
603    commit.tick();
604
605    // Now advance the time buffers
606    timeBuffer.advance();
607
608    fetchQueue.advance();
609    decodeQueue.advance();
610    renameQueue.advance();
611    iewQueue.advance();
612
613    activityRec.advance();
614
615    if (removeInstsThisCycle) {
616        cleanUpRemovedInsts();
617    }
618
619    if (!tickEvent.scheduled()) {
620        if (_status == SwitchedOut) {
621            DPRINTF(O3CPU, "Switched out!\n");
622            // increment stat
623            lastRunningCycle = curCycle();
624        } else if (!activityRec.active() || _status == Idle) {
625            DPRINTF(O3CPU, "Idle!\n");
626            lastRunningCycle = curCycle();
627            timesIdled++;
628        } else {
629            schedule(tickEvent, clockEdge(Cycles(1)));
630            DPRINTF(O3CPU, "Scheduling next tick!\n");
631        }
632    }
633
634    if (!FullSystem)
635        updateThreadPriority();
636
637    tryDrain();
638}
639
640template <class Impl>
641void
642FullO3CPU<Impl>::init()
643{
644    BaseCPU::init();
645
646    for (ThreadID tid = 0; tid < numThreads; ++tid) {
647        // Set noSquashFromTC so that the CPU doesn't squash when initially
648        // setting up registers.
649        thread[tid]->noSquashFromTC = true;
650        // Initialise the ThreadContext's memory proxies
651        thread[tid]->initMemProxies(thread[tid]->getTC());
652    }
653
654    if (FullSystem && !params()->switched_out) {
655        for (ThreadID tid = 0; tid < numThreads; tid++) {
656            ThreadContext *src_tc = threadContexts[tid];
657            TheISA::initCPU(src_tc, src_tc->contextId());
658        }
659    }
660
661    // Clear noSquashFromTC.
662    for (int tid = 0; tid < numThreads; ++tid)
663        thread[tid]->noSquashFromTC = false;
664
665    commit.setThreads(thread);
666}
667
668template <class Impl>
669void
670FullO3CPU<Impl>::startup()
671{
672    BaseCPU::startup();
673    for (int tid = 0; tid < numThreads; ++tid)
674        isa[tid]->startup(threadContexts[tid]);
675
676    fetch.startupStage();
677    decode.startupStage();
678    iew.startupStage();
679    rename.startupStage();
680    commit.startupStage();
681}
682
683template <class Impl>
684void
685FullO3CPU<Impl>::activateThread(ThreadID tid)
686{
687    list<ThreadID>::iterator isActive =
688        std::find(activeThreads.begin(), activeThreads.end(), tid);
689
690    DPRINTF(O3CPU, "[tid:%i]: Calling activate thread.\n", tid);
691    assert(!switchedOut());
692
693    if (isActive == activeThreads.end()) {
694        DPRINTF(O3CPU, "[tid:%i]: Adding to active threads list\n",
695                tid);
696
697        activeThreads.push_back(tid);
698    }
699}
700
701template <class Impl>
702void
703FullO3CPU<Impl>::deactivateThread(ThreadID tid)
704{
705    //Remove From Active List, if Active
706    list<ThreadID>::iterator thread_it =
707        std::find(activeThreads.begin(), activeThreads.end(), tid);
708
709    DPRINTF(O3CPU, "[tid:%i]: Calling deactivate thread.\n", tid);
710    assert(!switchedOut());
711
712    if (thread_it != activeThreads.end()) {
713        DPRINTF(O3CPU,"[tid:%i]: Removing from active threads list\n",
714                tid);
715        activeThreads.erase(thread_it);
716    }
717
718    fetch.deactivateThread(tid);
719    commit.deactivateThread(tid);
720}
721
722template <class Impl>
723Counter
724FullO3CPU<Impl>::totalInsts() const
725{
726    Counter total(0);
727
728    ThreadID size = thread.size();
729    for (ThreadID i = 0; i < size; i++)
730        total += thread[i]->numInst;
731
732    return total;
733}
734
735template <class Impl>
736Counter
737FullO3CPU<Impl>::totalOps() const
738{
739    Counter total(0);
740
741    ThreadID size = thread.size();
742    for (ThreadID i = 0; i < size; i++)
743        total += thread[i]->numOp;
744
745    return total;
746}
747
748template <class Impl>
749void
750FullO3CPU<Impl>::activateContext(ThreadID tid)
751{
752    assert(!switchedOut());
753
754    // Needs to set each stage to running as well.
755    activateThread(tid);
756
757    // We don't want to wake the CPU if it is drained. In that case,
758    // we just want to flag the thread as active and schedule the tick
759    // event from drainResume() instead.
760    if (drainState() == DrainState::Drained)
761        return;
762
763    // If we are time 0 or if the last activation time is in the past,
764    // schedule the next tick and wake up the fetch unit
765    if (lastActivatedCycle == 0 || lastActivatedCycle < curTick()) {
766        scheduleTickEvent(Cycles(0));
767
768        // Be sure to signal that there's some activity so the CPU doesn't
769        // deschedule itself.
770        activityRec.activity();
771        fetch.wakeFromQuiesce();
772
773        Cycles cycles(curCycle() - lastRunningCycle);
774        // @todo: This is an oddity that is only here to match the stats
775        if (cycles != 0)
776            --cycles;
777        quiesceCycles += cycles;
778
779        lastActivatedCycle = curTick();
780
781        _status = Running;
782
783        BaseCPU::activateContext(tid);
784    }
785}
786
787template <class Impl>
788void
789FullO3CPU<Impl>::suspendContext(ThreadID tid)
790{
791    DPRINTF(O3CPU,"[tid: %i]: Suspending Thread Context.\n", tid);
792    assert(!switchedOut());
793
794    deactivateThread(tid);
795
796    // If this was the last thread then unschedule the tick event.
797    if (activeThreads.size() == 0) {
798        unscheduleTickEvent();
799        lastRunningCycle = curCycle();
800        _status = Idle;
801    }
802
803    DPRINTF(Quiesce, "Suspending Context\n");
804
805    BaseCPU::suspendContext(tid);
806}
807
808template <class Impl>
809void
810FullO3CPU<Impl>::haltContext(ThreadID tid)
811{
812    //For now, this is the same as deallocate
813    DPRINTF(O3CPU,"[tid:%i]: Halt Context called. Deallocating", tid);
814    assert(!switchedOut());
815
816    deactivateThread(tid);
817    removeThread(tid);
818}
819
820template <class Impl>
821void
822FullO3CPU<Impl>::insertThread(ThreadID tid)
823{
824    DPRINTF(O3CPU,"[tid:%i] Initializing thread into CPU");
825    // Will change now that the PC and thread state is internal to the CPU
826    // and not in the ThreadContext.
827    ThreadContext *src_tc;
828    if (FullSystem)
829        src_tc = system->threadContexts[tid];
830    else
831        src_tc = tcBase(tid);
832
833    //Bind Int Regs to Rename Map
834
835    for (RegId reg_id(IntRegClass, 0); reg_id.index() < TheISA::NumIntRegs;
836         reg_id.index()++) {
837        PhysRegIdPtr phys_reg = freeList.getIntReg();
838        renameMap[tid].setEntry(reg_id, phys_reg);
839        scoreboard.setReg(phys_reg);
840    }
841
842    //Bind Float Regs to Rename Map
843    for (RegId reg_id(FloatRegClass, 0); reg_id.index() < TheISA::NumFloatRegs;
844         reg_id.index()++) {
845        PhysRegIdPtr phys_reg = freeList.getFloatReg();
846        renameMap[tid].setEntry(reg_id, phys_reg);
847        scoreboard.setReg(phys_reg);
848    }
849
850    //Bind condition-code Regs to Rename Map
851    for (RegId reg_id(CCRegClass, 0); reg_id.index() < TheISA::NumCCRegs;
852         reg_id.index()++) {
853        PhysRegIdPtr phys_reg = freeList.getCCReg();
854        renameMap[tid].setEntry(reg_id, phys_reg);
855        scoreboard.setReg(phys_reg);
856    }
857
858    //Copy Thread Data Into RegFile
859    //this->copyFromTC(tid);
860
861    //Set PC/NPC/NNPC
862    pcState(src_tc->pcState(), tid);
863
864    src_tc->setStatus(ThreadContext::Active);
865
866    activateContext(tid);
867
868    //Reset ROB/IQ/LSQ Entries
869    commit.rob->resetEntries();
870    iew.resetEntries();
871}
872
873template <class Impl>
874void
875FullO3CPU<Impl>::removeThread(ThreadID tid)
876{
877    DPRINTF(O3CPU,"[tid:%i] Removing thread context from CPU.\n", tid);
878
879    // Copy Thread Data From RegFile
880    // If thread is suspended, it might be re-allocated
881    // this->copyToTC(tid);
882
883
884    // @todo: 2-27-2008: Fix how we free up rename mappings
885    // here to alleviate the case for double-freeing registers
886    // in SMT workloads.
887
888    // Unbind Int Regs from Rename Map
889    for (RegId reg_id(IntRegClass, 0); reg_id.index() < TheISA::NumIntRegs;
890         reg_id.index()++) {
891        PhysRegIdPtr phys_reg = renameMap[tid].lookup(reg_id);
892        scoreboard.unsetReg(phys_reg);
893        freeList.addReg(phys_reg);
894    }
895
896    // Unbind Float Regs from Rename Map
897    for (RegId reg_id(FloatRegClass, 0); reg_id.index() < TheISA::NumFloatRegs;
898         reg_id.index()++) {
899        PhysRegIdPtr phys_reg = renameMap[tid].lookup(reg_id);
900        scoreboard.unsetReg(phys_reg);
901        freeList.addReg(phys_reg);
902    }
903
904    // Unbind condition-code Regs from Rename Map
905    for (RegId reg_id(CCRegClass, 0); reg_id.index() < TheISA::NumCCRegs;
906         reg_id.index()++) {
907        PhysRegIdPtr phys_reg = renameMap[tid].lookup(reg_id);
908        scoreboard.unsetReg(phys_reg);
909        freeList.addReg(phys_reg);
910    }
911
912    // Squash Throughout Pipeline
913    DynInstPtr inst = commit.rob->readHeadInst(tid);
914    InstSeqNum squash_seq_num = inst->seqNum;
915    fetch.squash(0, squash_seq_num, inst, tid);
916    decode.squash(tid);
917    rename.squash(squash_seq_num, tid);
918    iew.squash(tid);
919    iew.ldstQueue.squash(squash_seq_num, tid);
920    commit.rob->squash(squash_seq_num, tid);
921
922
923    assert(iew.instQueue.getCount(tid) == 0);
924    assert(iew.ldstQueue.getCount(tid) == 0);
925
926    // Reset ROB/IQ/LSQ Entries
927
928    // Commented out for now.  This should be possible to do by
929    // telling all the pipeline stages to drain first, and then
930    // checking until the drain completes.  Once the pipeline is
931    // drained, call resetEntries(). - 10-09-06 ktlim
932/*
933    if (activeThreads.size() >= 1) {
934        commit.rob->resetEntries();
935        iew.resetEntries();
936    }
937*/
938}
939
940template <class Impl>
941Fault
942FullO3CPU<Impl>::hwrei(ThreadID tid)
943{
944#if THE_ISA == ALPHA_ISA
945    // Need to clear the lock flag upon returning from an interrupt.
946    this->setMiscRegNoEffect(AlphaISA::MISCREG_LOCKFLAG, false, tid);
947
948    this->thread[tid]->kernelStats->hwrei();
949
950    // FIXME: XXX check for interrupts? XXX
951#endif
952    return NoFault;
953}
954
955template <class Impl>
956bool
957FullO3CPU<Impl>::simPalCheck(int palFunc, ThreadID tid)
958{
959#if THE_ISA == ALPHA_ISA
960    if (this->thread[tid]->kernelStats)
961        this->thread[tid]->kernelStats->callpal(palFunc,
962                                                this->threadContexts[tid]);
963
964    switch (palFunc) {
965      case PAL::halt:
966        halt();
967        if (--System::numSystemsRunning == 0)
968            exitSimLoop("all cpus halted");
969        break;
970
971      case PAL::bpt:
972      case PAL::bugchk:
973        if (this->system->breakpoint())
974            return false;
975        break;
976    }
977#endif
978    return true;
979}
980
981template <class Impl>
982Fault
983FullO3CPU<Impl>::getInterrupts()
984{
985    // Check if there are any outstanding interrupts
986    return this->interrupts[0]->getInterrupt(this->threadContexts[0]);
987}
988
989template <class Impl>
990void
991FullO3CPU<Impl>::processInterrupts(const Fault &interrupt)
992{
993    // Check for interrupts here.  For now can copy the code that
994    // exists within isa_fullsys_traits.hh.  Also assume that thread 0
995    // is the one that handles the interrupts.
996    // @todo: Possibly consolidate the interrupt checking code.
997    // @todo: Allow other threads to handle interrupts.
998
999    assert(interrupt != NoFault);
1000    this->interrupts[0]->updateIntrInfo(this->threadContexts[0]);
1001
1002    DPRINTF(O3CPU, "Interrupt %s being handled\n", interrupt->name());
1003    this->trap(interrupt, 0, nullptr);
1004}
1005
1006template <class Impl>
1007void
1008FullO3CPU<Impl>::trap(const Fault &fault, ThreadID tid,
1009                      const StaticInstPtr &inst)
1010{
1011    // Pass the thread's TC into the invoke method.
1012    fault->invoke(this->threadContexts[tid], inst);
1013}
1014
1015template <class Impl>
1016void
1017FullO3CPU<Impl>::syscall(int64_t callnum, ThreadID tid, Fault *fault)
1018{
1019    DPRINTF(O3CPU, "[tid:%i] Executing syscall().\n\n", tid);
1020
1021    DPRINTF(Activity,"Activity: syscall() called.\n");
1022
1023    // Temporarily increase this by one to account for the syscall
1024    // instruction.
1025    ++(this->thread[tid]->funcExeInst);
1026
1027    // Execute the actual syscall.
1028    this->thread[tid]->syscall(callnum, fault);
1029
1030    // Decrease funcExeInst by one as the normal commit will handle
1031    // incrementing it.
1032    --(this->thread[tid]->funcExeInst);
1033}
1034
1035template <class Impl>
1036void
1037FullO3CPU<Impl>::serializeThread(CheckpointOut &cp, ThreadID tid) const
1038{
1039    thread[tid]->serialize(cp);
1040}
1041
1042template <class Impl>
1043void
1044FullO3CPU<Impl>::unserializeThread(CheckpointIn &cp, ThreadID tid)
1045{
1046    thread[tid]->unserialize(cp);
1047}
1048
1049template <class Impl>
1050DrainState
1051FullO3CPU<Impl>::drain()
1052{
1053    // If the CPU isn't doing anything, then return immediately.
1054    if (switchedOut())
1055        return DrainState::Drained;
1056
1057    DPRINTF(Drain, "Draining...\n");
1058
1059    // We only need to signal a drain to the commit stage as this
1060    // initiates squashing controls the draining. Once the commit
1061    // stage commits an instruction where it is safe to stop, it'll
1062    // squash the rest of the instructions in the pipeline and force
1063    // the fetch stage to stall. The pipeline will be drained once all
1064    // in-flight instructions have retired.
1065    commit.drain();
1066
1067    // Wake the CPU and record activity so everything can drain out if
1068    // the CPU was not able to immediately drain.
1069    if (!isDrained())  {
1070        wakeCPU();
1071        activityRec.activity();
1072
1073        DPRINTF(Drain, "CPU not drained\n");
1074
1075        return DrainState::Draining;
1076    } else {
1077        DPRINTF(Drain, "CPU is already drained\n");
1078        if (tickEvent.scheduled())
1079            deschedule(tickEvent);
1080
1081        // Flush out any old data from the time buffers.  In
1082        // particular, there might be some data in flight from the
1083        // fetch stage that isn't visible in any of the CPU buffers we
1084        // test in isDrained().
1085        for (int i = 0; i < timeBuffer.getSize(); ++i) {
1086            timeBuffer.advance();
1087            fetchQueue.advance();
1088            decodeQueue.advance();
1089            renameQueue.advance();
1090            iewQueue.advance();
1091        }
1092
1093        drainSanityCheck();
1094        return DrainState::Drained;
1095    }
1096}
1097
1098template <class Impl>
1099bool
1100FullO3CPU<Impl>::tryDrain()
1101{
1102    if (drainState() != DrainState::Draining || !isDrained())
1103        return false;
1104
1105    if (tickEvent.scheduled())
1106        deschedule(tickEvent);
1107
1108    DPRINTF(Drain, "CPU done draining, processing drain event\n");
1109    signalDrainDone();
1110
1111    return true;
1112}
1113
1114template <class Impl>
1115void
1116FullO3CPU<Impl>::drainSanityCheck() const
1117{
1118    assert(isDrained());
1119    fetch.drainSanityCheck();
1120    decode.drainSanityCheck();
1121    rename.drainSanityCheck();
1122    iew.drainSanityCheck();
1123    commit.drainSanityCheck();
1124}
1125
1126template <class Impl>
1127bool
1128FullO3CPU<Impl>::isDrained() const
1129{
1130    bool drained(true);
1131
1132    if (!instList.empty() || !removeList.empty()) {
1133        DPRINTF(Drain, "Main CPU structures not drained.\n");
1134        drained = false;
1135    }
1136
1137    if (!fetch.isDrained()) {
1138        DPRINTF(Drain, "Fetch not drained.\n");
1139        drained = false;
1140    }
1141
1142    if (!decode.isDrained()) {
1143        DPRINTF(Drain, "Decode not drained.\n");
1144        drained = false;
1145    }
1146
1147    if (!rename.isDrained()) {
1148        DPRINTF(Drain, "Rename not drained.\n");
1149        drained = false;
1150    }
1151
1152    if (!iew.isDrained()) {
1153        DPRINTF(Drain, "IEW not drained.\n");
1154        drained = false;
1155    }
1156
1157    if (!commit.isDrained()) {
1158        DPRINTF(Drain, "Commit not drained.\n");
1159        drained = false;
1160    }
1161
1162    return drained;
1163}
1164
1165template <class Impl>
1166void
1167FullO3CPU<Impl>::commitDrained(ThreadID tid)
1168{
1169    fetch.drainStall(tid);
1170}
1171
1172template <class Impl>
1173void
1174FullO3CPU<Impl>::drainResume()
1175{
1176    if (switchedOut())
1177        return;
1178
1179    DPRINTF(Drain, "Resuming...\n");
1180    verifyMemoryMode();
1181
1182    fetch.drainResume();
1183    commit.drainResume();
1184
1185    _status = Idle;
1186    for (ThreadID i = 0; i < thread.size(); i++) {
1187        if (thread[i]->status() == ThreadContext::Active) {
1188            DPRINTF(Drain, "Activating thread: %i\n", i);
1189            activateThread(i);
1190            _status = Running;
1191        }
1192    }
1193
1194    assert(!tickEvent.scheduled());
1195    if (_status == Running)
1196        schedule(tickEvent, nextCycle());
1197}
1198
1199template <class Impl>
1200void
1201FullO3CPU<Impl>::switchOut()
1202{
1203    DPRINTF(O3CPU, "Switching out\n");
1204    BaseCPU::switchOut();
1205
1206    activityRec.reset();
1207
1208    _status = SwitchedOut;
1209
1210    if (checker)
1211        checker->switchOut();
1212}
1213
1214template <class Impl>
1215void
1216FullO3CPU<Impl>::takeOverFrom(BaseCPU *oldCPU)
1217{
1218    BaseCPU::takeOverFrom(oldCPU);
1219
1220    fetch.takeOverFrom();
1221    decode.takeOverFrom();
1222    rename.takeOverFrom();
1223    iew.takeOverFrom();
1224    commit.takeOverFrom();
1225
1226    assert(!tickEvent.scheduled());
1227
1228    FullO3CPU<Impl> *oldO3CPU = dynamic_cast<FullO3CPU<Impl>*>(oldCPU);
1229    if (oldO3CPU)
1230        globalSeqNum = oldO3CPU->globalSeqNum;
1231
1232    lastRunningCycle = curCycle();
1233    _status = Idle;
1234}
1235
1236template <class Impl>
1237void
1238FullO3CPU<Impl>::verifyMemoryMode() const
1239{
1240    if (!system->isTimingMode()) {
1241        fatal("The O3 CPU requires the memory system to be in "
1242              "'timing' mode.\n");
1243    }
1244}
1245
1246template <class Impl>
1247TheISA::MiscReg
1248FullO3CPU<Impl>::readMiscRegNoEffect(int misc_reg, ThreadID tid) const
1249{
1250    return this->isa[tid]->readMiscRegNoEffect(misc_reg);
1251}
1252
1253template <class Impl>
1254TheISA::MiscReg
1255FullO3CPU<Impl>::readMiscReg(int misc_reg, ThreadID tid)
1256{
1257    miscRegfileReads++;
1258    return this->isa[tid]->readMiscReg(misc_reg, tcBase(tid));
1259}
1260
1261template <class Impl>
1262void
1263FullO3CPU<Impl>::setMiscRegNoEffect(int misc_reg,
1264        const TheISA::MiscReg &val, ThreadID tid)
1265{
1266    this->isa[tid]->setMiscRegNoEffect(misc_reg, val);
1267}
1268
1269template <class Impl>
1270void
1271FullO3CPU<Impl>::setMiscReg(int misc_reg,
1272        const TheISA::MiscReg &val, ThreadID tid)
1273{
1274    miscRegfileWrites++;
1275    this->isa[tid]->setMiscReg(misc_reg, val, tcBase(tid));
1276}
1277
1278template <class Impl>
1279uint64_t
1280FullO3CPU<Impl>::readIntReg(PhysRegIdPtr phys_reg)
1281{
1282    intRegfileReads++;
1283    return regFile.readIntReg(phys_reg);
1284}
1285
1286template <class Impl>
1287FloatReg
1288FullO3CPU<Impl>::readFloatReg(PhysRegIdPtr phys_reg)
1289{
1290    fpRegfileReads++;
1291    return regFile.readFloatReg(phys_reg);
1292}
1293
1294template <class Impl>
1295FloatRegBits
1296FullO3CPU<Impl>::readFloatRegBits(PhysRegIdPtr phys_reg)
1297{
1298    fpRegfileReads++;
1299    return regFile.readFloatRegBits(phys_reg);
1300}
1301
1302template <class Impl>
1303auto
1304FullO3CPU<Impl>::readVecReg(PhysRegIdPtr phys_reg) const
1305        -> const VecRegContainer&
1306{
1307    vecRegfileReads++;
1308    return regFile.readVecReg(phys_reg);
1309}
1310
1311template <class Impl>
1312auto
1313FullO3CPU<Impl>::getWritableVecReg(PhysRegIdPtr phys_reg)
1314        -> VecRegContainer&
1315{
1316    vecRegfileWrites++;
1317    return regFile.getWritableVecReg(phys_reg);
1318}
1319
1320template <class Impl>
1321auto
1322FullO3CPU<Impl>::readVecElem(PhysRegIdPtr phys_reg) const -> const VecElem&
1323{
1324    vecRegfileReads++;
1325    return regFile.readVecElem(phys_reg);
1326}
1327
1328template <class Impl>
1329CCReg
1330FullO3CPU<Impl>::readCCReg(PhysRegIdPtr phys_reg)
1331{
1332    ccRegfileReads++;
1333    return regFile.readCCReg(phys_reg);
1334}
1335
1336template <class Impl>
1337void
1338FullO3CPU<Impl>::setIntReg(PhysRegIdPtr phys_reg, uint64_t val)
1339{
1340    intRegfileWrites++;
1341    regFile.setIntReg(phys_reg, val);
1342}
1343
1344template <class Impl>
1345void
1346FullO3CPU<Impl>::setFloatReg(PhysRegIdPtr phys_reg, FloatReg val)
1347{
1348    fpRegfileWrites++;
1349    regFile.setFloatReg(phys_reg, val);
1350}
1351
1352template <class Impl>
1353void
1354FullO3CPU<Impl>::setFloatRegBits(PhysRegIdPtr phys_reg, FloatRegBits val)
1355{
1356    fpRegfileWrites++;
1357    regFile.setFloatRegBits(phys_reg, val);
1358}
1359
1360template <class Impl>
1361void
1362FullO3CPU<Impl>::setVecReg(PhysRegIdPtr phys_reg, const VecRegContainer& val)
1363{
1364    vecRegfileWrites++;
1365    regFile.setVecReg(phys_reg, val);
1366}
1367
1368template <class Impl>
1369void
1370FullO3CPU<Impl>::setVecElem(PhysRegIdPtr phys_reg, const VecElem& val)
1371{
1372    vecRegfileWrites++;
1373    regFile.setVecElem(phys_reg, val);
1374}
1375
1376template <class Impl>
1377void
1378FullO3CPU<Impl>::setCCReg(PhysRegIdPtr phys_reg, CCReg val)
1379{
1380    ccRegfileWrites++;
1381    regFile.setCCReg(phys_reg, val);
1382}
1383
1384template <class Impl>
1385uint64_t
1386FullO3CPU<Impl>::readArchIntReg(int reg_idx, ThreadID tid)
1387{
1388    intRegfileReads++;
1389    PhysRegIdPtr phys_reg = commitRenameMap[tid].lookup(
1390            RegId(IntRegClass, reg_idx));
1391
1392    return regFile.readIntReg(phys_reg);
1393}
1394
1395template <class Impl>
1396float
1397FullO3CPU<Impl>::readArchFloatReg(int reg_idx, ThreadID tid)
1398{
1399    fpRegfileReads++;
1400    PhysRegIdPtr phys_reg = commitRenameMap[tid].lookup(
1401        RegId(FloatRegClass, reg_idx));
1402
1403    return regFile.readFloatReg(phys_reg);
1404}
1405
1406template <class Impl>
1407uint64_t
1408FullO3CPU<Impl>::readArchFloatRegInt(int reg_idx, ThreadID tid)
1409{
1410    fpRegfileReads++;
1411    PhysRegIdPtr phys_reg = commitRenameMap[tid].lookup(
1412        RegId(FloatRegClass, reg_idx));
1413
1414    return regFile.readFloatRegBits(phys_reg);
1415}
1416
1417template <class Impl>
1418auto
1419FullO3CPU<Impl>::readArchVecReg(int reg_idx, ThreadID tid) const
1420        -> const VecRegContainer&
1421{
1422    PhysRegIdPtr phys_reg = commitRenameMap[tid].lookup(
1423                RegId(VecRegClass, reg_idx));
1424    return readVecReg(phys_reg);
1425}
1426
1427template <class Impl>
1428auto
1429FullO3CPU<Impl>::getWritableArchVecReg(int reg_idx, ThreadID tid)
1430        -> VecRegContainer&
1431{
1432    PhysRegIdPtr phys_reg = commitRenameMap[tid].lookup(
1433                RegId(VecRegClass, reg_idx));
1434    return getWritableVecReg(phys_reg);
1435}
1436
1437template <class Impl>
1438auto
1439FullO3CPU<Impl>::readArchVecElem(const RegIndex& reg_idx, const ElemIndex& ldx,
1440                                 ThreadID tid) const -> const VecElem&
1441{
1442    PhysRegIdPtr phys_reg = commitRenameMap[tid].lookup(
1443                                RegId(VecRegClass, reg_idx, ldx));
1444    return readVecElem(phys_reg);
1445}
1446
1447template <class Impl>
1448CCReg
1449FullO3CPU<Impl>::readArchCCReg(int reg_idx, ThreadID tid)
1450{
1451    ccRegfileReads++;
1452    PhysRegIdPtr phys_reg = commitRenameMap[tid].lookup(
1453        RegId(CCRegClass, reg_idx));
1454
1455    return regFile.readCCReg(phys_reg);
1456}
1457
1458template <class Impl>
1459void
1460FullO3CPU<Impl>::setArchIntReg(int reg_idx, uint64_t val, ThreadID tid)
1461{
1462    intRegfileWrites++;
1463    PhysRegIdPtr phys_reg = commitRenameMap[tid].lookup(
1464            RegId(IntRegClass, reg_idx));
1465
1466    regFile.setIntReg(phys_reg, val);
1467}
1468
1469template <class Impl>
1470void
1471FullO3CPU<Impl>::setArchFloatReg(int reg_idx, float val, ThreadID tid)
1472{
1473    fpRegfileWrites++;
1474    PhysRegIdPtr phys_reg = commitRenameMap[tid].lookup(
1475            RegId(FloatRegClass, reg_idx));
1476
1477    regFile.setFloatReg(phys_reg, val);
1478}
1479
1480template <class Impl>
1481void
1482FullO3CPU<Impl>::setArchFloatRegInt(int reg_idx, uint64_t val, ThreadID tid)
1483{
1484    fpRegfileWrites++;
1485    PhysRegIdPtr phys_reg = commitRenameMap[tid].lookup(
1486            RegId(FloatRegClass, reg_idx));
1487
1488    regFile.setFloatRegBits(phys_reg, val);
1489}
1490
1491template <class Impl>
1492void
1493FullO3CPU<Impl>::setArchVecReg(int reg_idx, const VecRegContainer& val,
1494                               ThreadID tid)
1495{
1496    PhysRegIdPtr phys_reg = commitRenameMap[tid].lookup(
1497                RegId(VecRegClass, reg_idx));
1498    setVecReg(phys_reg, val);
1499}
1500
1501template <class Impl>
1502void
1503FullO3CPU<Impl>::setArchVecElem(const RegIndex& reg_idx, const ElemIndex& ldx,
1504                                const VecElem& val, ThreadID tid)
1505{
1506    PhysRegIdPtr phys_reg = commitRenameMap[tid].lookup(
1507                RegId(VecRegClass, reg_idx, ldx));
1508    setVecElem(phys_reg, val);
1509}
1510
1511template <class Impl>
1512void
1513FullO3CPU<Impl>::setArchCCReg(int reg_idx, CCReg val, ThreadID tid)
1514{
1515    ccRegfileWrites++;
1516    PhysRegIdPtr phys_reg = commitRenameMap[tid].lookup(
1517            RegId(CCRegClass, reg_idx));
1518
1519    regFile.setCCReg(phys_reg, val);
1520}
1521
1522template <class Impl>
1523TheISA::PCState
1524FullO3CPU<Impl>::pcState(ThreadID tid)
1525{
1526    return commit.pcState(tid);
1527}
1528
1529template <class Impl>
1530void
1531FullO3CPU<Impl>::pcState(const TheISA::PCState &val, ThreadID tid)
1532{
1533    commit.pcState(val, tid);
1534}
1535
1536template <class Impl>
1537Addr
1538FullO3CPU<Impl>::instAddr(ThreadID tid)
1539{
1540    return commit.instAddr(tid);
1541}
1542
1543template <class Impl>
1544Addr
1545FullO3CPU<Impl>::nextInstAddr(ThreadID tid)
1546{
1547    return commit.nextInstAddr(tid);
1548}
1549
1550template <class Impl>
1551MicroPC
1552FullO3CPU<Impl>::microPC(ThreadID tid)
1553{
1554    return commit.microPC(tid);
1555}
1556
1557template <class Impl>
1558void
1559FullO3CPU<Impl>::squashFromTC(ThreadID tid)
1560{
1561    this->thread[tid]->noSquashFromTC = true;
1562    this->commit.generateTCEvent(tid);
1563}
1564
1565template <class Impl>
1566typename FullO3CPU<Impl>::ListIt
1567FullO3CPU<Impl>::addInst(DynInstPtr &inst)
1568{
1569    instList.push_back(inst);
1570
1571    return --(instList.end());
1572}
1573
1574template <class Impl>
1575void
1576FullO3CPU<Impl>::instDone(ThreadID tid, DynInstPtr &inst)
1577{
1578    // Keep an instruction count.
1579    if (!inst->isMicroop() || inst->isLastMicroop()) {
1580        thread[tid]->numInst++;
1581        thread[tid]->numInsts++;
1582        committedInsts[tid]++;
1583        system->totalNumInsts++;
1584
1585        // Check for instruction-count-based events.
1586        comInstEventQueue[tid]->serviceEvents(thread[tid]->numInst);
1587        system->instEventQueue.serviceEvents(system->totalNumInsts);
1588    }
1589    thread[tid]->numOp++;
1590    thread[tid]->numOps++;
1591    committedOps[tid]++;
1592
1593    probeInstCommit(inst->staticInst);
1594}
1595
1596template <class Impl>
1597void
1598FullO3CPU<Impl>::removeFrontInst(DynInstPtr &inst)
1599{
1600    DPRINTF(O3CPU, "Removing committed instruction [tid:%i] PC %s "
1601            "[sn:%lli]\n",
1602            inst->threadNumber, inst->pcState(), inst->seqNum);
1603
1604    removeInstsThisCycle = true;
1605
1606    // Remove the front instruction.
1607    removeList.push(inst->getInstListIt());
1608}
1609
1610template <class Impl>
1611void
1612FullO3CPU<Impl>::removeInstsNotInROB(ThreadID tid)
1613{
1614    DPRINTF(O3CPU, "Thread %i: Deleting instructions from instruction"
1615            " list.\n", tid);
1616
1617    ListIt end_it;
1618
1619    bool rob_empty = false;
1620
1621    if (instList.empty()) {
1622        return;
1623    } else if (rob.isEmpty(tid)) {
1624        DPRINTF(O3CPU, "ROB is empty, squashing all insts.\n");
1625        end_it = instList.begin();
1626        rob_empty = true;
1627    } else {
1628        end_it = (rob.readTailInst(tid))->getInstListIt();
1629        DPRINTF(O3CPU, "ROB is not empty, squashing insts not in ROB.\n");
1630    }
1631
1632    removeInstsThisCycle = true;
1633
1634    ListIt inst_it = instList.end();
1635
1636    inst_it--;
1637
1638    // Walk through the instruction list, removing any instructions
1639    // that were inserted after the given instruction iterator, end_it.
1640    while (inst_it != end_it) {
1641        assert(!instList.empty());
1642
1643        squashInstIt(inst_it, tid);
1644
1645        inst_it--;
1646    }
1647
1648    // If the ROB was empty, then we actually need to remove the first
1649    // instruction as well.
1650    if (rob_empty) {
1651        squashInstIt(inst_it, tid);
1652    }
1653}
1654
1655template <class Impl>
1656void
1657FullO3CPU<Impl>::removeInstsUntil(const InstSeqNum &seq_num, ThreadID tid)
1658{
1659    assert(!instList.empty());
1660
1661    removeInstsThisCycle = true;
1662
1663    ListIt inst_iter = instList.end();
1664
1665    inst_iter--;
1666
1667    DPRINTF(O3CPU, "Deleting instructions from instruction "
1668            "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1669            tid, seq_num, (*inst_iter)->seqNum);
1670
1671    while ((*inst_iter)->seqNum > seq_num) {
1672
1673        bool break_loop = (inst_iter == instList.begin());
1674
1675        squashInstIt(inst_iter, tid);
1676
1677        inst_iter--;
1678
1679        if (break_loop)
1680            break;
1681    }
1682}
1683
1684template <class Impl>
1685inline void
1686FullO3CPU<Impl>::squashInstIt(const ListIt &instIt, ThreadID tid)
1687{
1688    if ((*instIt)->threadNumber == tid) {
1689        DPRINTF(O3CPU, "Squashing instruction, "
1690                "[tid:%i] [sn:%lli] PC %s\n",
1691                (*instIt)->threadNumber,
1692                (*instIt)->seqNum,
1693                (*instIt)->pcState());
1694
1695        // Mark it as squashed.
1696        (*instIt)->setSquashed();
1697
1698        // @todo: Formulate a consistent method for deleting
1699        // instructions from the instruction list
1700        // Remove the instruction from the list.
1701        removeList.push(instIt);
1702    }
1703}
1704
1705template <class Impl>
1706void
1707FullO3CPU<Impl>::cleanUpRemovedInsts()
1708{
1709    while (!removeList.empty()) {
1710        DPRINTF(O3CPU, "Removing instruction, "
1711                "[tid:%i] [sn:%lli] PC %s\n",
1712                (*removeList.front())->threadNumber,
1713                (*removeList.front())->seqNum,
1714                (*removeList.front())->pcState());
1715
1716        instList.erase(removeList.front());
1717
1718        removeList.pop();
1719    }
1720
1721    removeInstsThisCycle = false;
1722}
1723/*
1724template <class Impl>
1725void
1726FullO3CPU<Impl>::removeAllInsts()
1727{
1728    instList.clear();
1729}
1730*/
1731template <class Impl>
1732void
1733FullO3CPU<Impl>::dumpInsts()
1734{
1735    int num = 0;
1736
1737    ListIt inst_list_it = instList.begin();
1738
1739    cprintf("Dumping Instruction List\n");
1740
1741    while (inst_list_it != instList.end()) {
1742        cprintf("Instruction:%i\nPC:%#x\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1743                "Squashed:%i\n\n",
1744                num, (*inst_list_it)->instAddr(), (*inst_list_it)->threadNumber,
1745                (*inst_list_it)->seqNum, (*inst_list_it)->isIssued(),
1746                (*inst_list_it)->isSquashed());
1747        inst_list_it++;
1748        ++num;
1749    }
1750}
1751/*
1752template <class Impl>
1753void
1754FullO3CPU<Impl>::wakeDependents(DynInstPtr &inst)
1755{
1756    iew.wakeDependents(inst);
1757}
1758*/
1759template <class Impl>
1760void
1761FullO3CPU<Impl>::wakeCPU()
1762{
1763    if (activityRec.active() || tickEvent.scheduled()) {
1764        DPRINTF(Activity, "CPU already running.\n");
1765        return;
1766    }
1767
1768    DPRINTF(Activity, "Waking up CPU\n");
1769
1770    Cycles cycles(curCycle() - lastRunningCycle);
1771    // @todo: This is an oddity that is only here to match the stats
1772    if (cycles > 1) {
1773        --cycles;
1774        idleCycles += cycles;
1775        numCycles += cycles;
1776        ppCycles->notify(cycles);
1777    }
1778
1779    schedule(tickEvent, clockEdge());
1780}
1781
1782template <class Impl>
1783void
1784FullO3CPU<Impl>::wakeup(ThreadID tid)
1785{
1786    if (this->thread[tid]->status() != ThreadContext::Suspended)
1787        return;
1788
1789    this->wakeCPU();
1790
1791    DPRINTF(Quiesce, "Suspended Processor woken\n");
1792    this->threadContexts[tid]->activate();
1793}
1794
1795template <class Impl>
1796ThreadID
1797FullO3CPU<Impl>::getFreeTid()
1798{
1799    for (ThreadID tid = 0; tid < numThreads; tid++) {
1800        if (!tids[tid]) {
1801            tids[tid] = true;
1802            return tid;
1803        }
1804    }
1805
1806    return InvalidThreadID;
1807}
1808
1809template <class Impl>
1810void
1811FullO3CPU<Impl>::updateThreadPriority()
1812{
1813    if (activeThreads.size() > 1) {
1814        //DEFAULT TO ROUND ROBIN SCHEME
1815        //e.g. Move highest priority to end of thread list
1816        list<ThreadID>::iterator list_begin = activeThreads.begin();
1817
1818        unsigned high_thread = *list_begin;
1819
1820        activeThreads.erase(list_begin);
1821
1822        activeThreads.push_back(high_thread);
1823    }
1824}
1825
1826// Forward declaration of FullO3CPU.
1827template class FullO3CPU<O3CPUImpl>;
1828