1 //===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // MachineScheduler schedules machine instructions after phi elimination. It
11 // preserves LiveIntervals so it can be invoked before register allocation.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/MachineScheduler.h"
16 #include "llvm/ADT/PriorityQueue.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/MachineDominators.h"
20 #include "llvm/CodeGen/MachineLoopInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/RegisterClassInfo.h"
24 #include "llvm/CodeGen/ScheduleDFS.h"
25 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/GraphWriter.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetInstrInfo.h"
36 #define DEBUG_TYPE "misched"
39 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
40 cl::desc("Force top-down list scheduling"));
41 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
42 cl::desc("Force bottom-up list scheduling"));
46 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
47 cl::desc("Pop up a window to show MISched dags after they are processed"));
49 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
50 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
52 static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
53 cl::desc("Only schedule this function"));
54 static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
55 cl::desc("Only schedule this MBB#"));
57 static bool ViewMISchedDAGs = false;
60 static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
61 cl::desc("Enable register pressure scheduling."), cl::init(true));
63 static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
64 cl::desc("Enable cyclic critical path analysis."), cl::init(true));
66 static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
67 cl::desc("Enable load clustering."), cl::init(true));
69 // Experimental heuristics
70 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
71 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
73 static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
74 cl::desc("Verify machine instrs before and after machine scheduling"));
76 // DAG subtrees must have at least this many nodes.
77 static const unsigned MinSubtreeSize = 8;
79 // Pin the vtables to this file.
80 void MachineSchedStrategy::anchor() {}
81 void ScheduleDAGMutation::anchor() {}
83 //===----------------------------------------------------------------------===//
84 // Machine Instruction Scheduling Pass and Registry
85 //===----------------------------------------------------------------------===//
87 MachineSchedContext::MachineSchedContext():
88 MF(nullptr), MLI(nullptr), MDT(nullptr), PassConfig(nullptr), AA(nullptr), LIS(nullptr) {
89 RegClassInfo = new RegisterClassInfo();
92 MachineSchedContext::~MachineSchedContext() {
97 /// Base class for a machine scheduler class that can run at any point.
98 class MachineSchedulerBase : public MachineSchedContext,
99 public MachineFunctionPass {
101 MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
103 void print(raw_ostream &O, const Module* = nullptr) const override;
106 void scheduleRegions(ScheduleDAGInstrs &Scheduler);
109 /// MachineScheduler runs after coalescing and before register allocation.
110 class MachineScheduler : public MachineSchedulerBase {
114 void getAnalysisUsage(AnalysisUsage &AU) const override;
116 bool runOnMachineFunction(MachineFunction&) override;
118 static char ID; // Class identification, replacement for typeinfo
121 ScheduleDAGInstrs *createMachineScheduler();
124 /// PostMachineScheduler runs after shortly before code emission.
125 class PostMachineScheduler : public MachineSchedulerBase {
127 PostMachineScheduler();
129 void getAnalysisUsage(AnalysisUsage &AU) const override;
131 bool runOnMachineFunction(MachineFunction&) override;
133 static char ID; // Class identification, replacement for typeinfo
136 ScheduleDAGInstrs *createPostMachineScheduler();
140 char MachineScheduler::ID = 0;
142 char &llvm::MachineSchedulerID = MachineScheduler::ID;
144 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
145 "Machine Instruction Scheduler", false, false)
146 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
147 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
148 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
149 INITIALIZE_PASS_END(MachineScheduler, "misched",
150 "Machine Instruction Scheduler", false, false)
152 MachineScheduler::MachineScheduler()
153 : MachineSchedulerBase(ID) {
154 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
157 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
158 AU.setPreservesCFG();
159 AU.addRequiredID(MachineDominatorsID);
160 AU.addRequired<MachineLoopInfo>();
161 AU.addRequired<AliasAnalysis>();
162 AU.addRequired<TargetPassConfig>();
163 AU.addRequired<SlotIndexes>();
164 AU.addPreserved<SlotIndexes>();
165 AU.addRequired<LiveIntervals>();
166 AU.addPreserved<LiveIntervals>();
167 MachineFunctionPass::getAnalysisUsage(AU);
170 char PostMachineScheduler::ID = 0;
172 char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
174 INITIALIZE_PASS(PostMachineScheduler, "postmisched",
175 "PostRA Machine Instruction Scheduler", false, false)
177 PostMachineScheduler::PostMachineScheduler()
178 : MachineSchedulerBase(ID) {
179 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
182 void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
183 AU.setPreservesCFG();
184 AU.addRequiredID(MachineDominatorsID);
185 AU.addRequired<MachineLoopInfo>();
186 AU.addRequired<TargetPassConfig>();
187 MachineFunctionPass::getAnalysisUsage(AU);
190 MachinePassRegistry MachineSchedRegistry::Registry;
192 /// A dummy default scheduler factory indicates whether the scheduler
193 /// is overridden on the command line.
194 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
198 /// MachineSchedOpt allows command line selection of the scheduler.
199 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
200 RegisterPassParser<MachineSchedRegistry> >
201 MachineSchedOpt("misched",
202 cl::init(&useDefaultMachineSched), cl::Hidden,
203 cl::desc("Machine instruction scheduler to use"));
205 static MachineSchedRegistry
206 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
207 useDefaultMachineSched);
209 /// Forward declare the standard machine scheduler. This will be used as the
210 /// default scheduler if the target does not set a default.
211 static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C);
212 static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C);
214 /// Decrement this iterator until reaching the top or a non-debug instr.
215 static MachineBasicBlock::const_iterator
216 priorNonDebug(MachineBasicBlock::const_iterator I,
217 MachineBasicBlock::const_iterator Beg) {
218 assert(I != Beg && "reached the top of the region, cannot decrement");
220 if (!I->isDebugValue())
226 /// Non-const version.
227 static MachineBasicBlock::iterator
228 priorNonDebug(MachineBasicBlock::iterator I,
229 MachineBasicBlock::const_iterator Beg) {
230 return const_cast<MachineInstr*>(
231 &*priorNonDebug(MachineBasicBlock::const_iterator(I), Beg));
234 /// If this iterator is a debug value, increment until reaching the End or a
235 /// non-debug instruction.
236 static MachineBasicBlock::const_iterator
237 nextIfDebug(MachineBasicBlock::const_iterator I,
238 MachineBasicBlock::const_iterator End) {
239 for(; I != End; ++I) {
240 if (!I->isDebugValue())
246 /// Non-const version.
247 static MachineBasicBlock::iterator
248 nextIfDebug(MachineBasicBlock::iterator I,
249 MachineBasicBlock::const_iterator End) {
250 // Cast the return value to nonconst MachineInstr, then cast to an
251 // instr_iterator, which does not check for null, finally return a
253 return MachineBasicBlock::instr_iterator(
254 const_cast<MachineInstr*>(
255 &*nextIfDebug(MachineBasicBlock::const_iterator(I), End)));
258 /// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
259 ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
260 // Select the scheduler, or set the default.
261 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
262 if (Ctor != useDefaultMachineSched)
265 // Get the default scheduler set by the target for this function.
266 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
270 // Default to GenericScheduler.
271 return createGenericSchedLive(this);
274 /// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
275 /// the caller. We don't have a command line option to override the postRA
276 /// scheduler. The Target must configure it.
277 ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
278 // Get the postRA scheduler set by the target for this function.
279 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
283 // Default to GenericScheduler.
284 return createGenericSchedPostRA(this);
287 /// Top-level MachineScheduler pass driver.
289 /// Visit blocks in function order. Divide each block into scheduling regions
290 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
291 /// consistent with the DAG builder, which traverses the interior of the
292 /// scheduling regions bottom-up.
294 /// This design avoids exposing scheduling boundaries to the DAG builder,
295 /// simplifying the DAG builder's support for "special" target instructions.
296 /// At the same time the design allows target schedulers to operate across
297 /// scheduling boundaries, for example to bundle the boudary instructions
298 /// without reordering them. This creates complexity, because the target
299 /// scheduler must update the RegionBegin and RegionEnd positions cached by
300 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
301 /// design would be to split blocks at scheduling boundaries, but LLVM has a
302 /// general bias against block splitting purely for implementation simplicity.
303 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
304 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
306 // Initialize the context of the pass.
308 MLI = &getAnalysis<MachineLoopInfo>();
309 MDT = &getAnalysis<MachineDominatorTree>();
310 PassConfig = &getAnalysis<TargetPassConfig>();
311 AA = &getAnalysis<AliasAnalysis>();
313 LIS = &getAnalysis<LiveIntervals>();
315 if (VerifyScheduling) {
317 MF->verify(this, "Before machine scheduling.");
319 RegClassInfo->runOnMachineFunction(*MF);
321 // Instantiate the selected scheduler for this target, function, and
322 // optimization level.
323 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
324 scheduleRegions(*Scheduler);
327 if (VerifyScheduling)
328 MF->verify(this, "After machine scheduling.");
332 bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
333 if (skipOptnoneFunction(*mf.getFunction()))
336 const TargetSubtargetInfo &ST =
337 mf.getTarget().getSubtarget<TargetSubtargetInfo>();
338 if (!ST.enablePostMachineScheduler()) {
339 DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
342 DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
344 // Initialize the context of the pass.
346 PassConfig = &getAnalysis<TargetPassConfig>();
348 if (VerifyScheduling)
349 MF->verify(this, "Before post machine scheduling.");
351 // Instantiate the selected scheduler for this target, function, and
352 // optimization level.
353 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
354 scheduleRegions(*Scheduler);
356 if (VerifyScheduling)
357 MF->verify(this, "After post machine scheduling.");
361 /// Return true of the given instruction should not be included in a scheduling
364 /// MachineScheduler does not currently support scheduling across calls. To
365 /// handle calls, the DAG builder needs to be modified to create register
366 /// anti/output dependencies on the registers clobbered by the call's regmask
367 /// operand. In PreRA scheduling, the stack pointer adjustment already prevents
368 /// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
369 /// the boundary, but there would be no benefit to postRA scheduling across
370 /// calls this late anyway.
371 static bool isSchedBoundary(MachineBasicBlock::iterator MI,
372 MachineBasicBlock *MBB,
374 const TargetInstrInfo *TII,
376 return MI->isCall() || TII->isSchedulingBoundary(MI, MBB, *MF);
379 /// Main driver for both MachineScheduler and PostMachineScheduler.
380 void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler) {
381 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
382 bool IsPostRA = Scheduler.isPostRA();
384 // Visit all machine basic blocks.
386 // TODO: Visit blocks in global postorder or postorder within the bottom-up
387 // loop tree. Then we can optionally compute global RegPressure.
388 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
389 MBB != MBBEnd; ++MBB) {
391 Scheduler.startBlock(MBB);
394 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
396 if (SchedOnlyBlock.getNumOccurrences()
397 && (int)SchedOnlyBlock != MBB->getNumber())
401 // Break the block into scheduling regions [I, RegionEnd), and schedule each
402 // region as soon as it is discovered. RegionEnd points the scheduling
403 // boundary at the bottom of the region. The DAG does not include RegionEnd,
404 // but the region does (i.e. the next RegionEnd is above the previous
405 // RegionBegin). If the current block has no terminator then RegionEnd ==
406 // MBB->end() for the bottom region.
408 // The Scheduler may insert instructions during either schedule() or
409 // exitRegion(), even for empty regions. So the local iterators 'I' and
410 // 'RegionEnd' are invalid across these calls.
412 // MBB::size() uses instr_iterator to count. Here we need a bundle to count
413 // as a single instruction.
414 unsigned RemainingInstrs = std::distance(MBB->begin(), MBB->end());
415 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
416 RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
418 // Avoid decrementing RegionEnd for blocks with no terminator.
419 if (RegionEnd != MBB->end() ||
420 isSchedBoundary(std::prev(RegionEnd), MBB, MF, TII, IsPostRA)) {
422 // Count the boundary instruction.
426 // The next region starts above the previous region. Look backward in the
427 // instruction stream until we find the nearest boundary.
428 unsigned NumRegionInstrs = 0;
429 MachineBasicBlock::iterator I = RegionEnd;
430 for(;I != MBB->begin(); --I, --RemainingInstrs, ++NumRegionInstrs) {
431 if (isSchedBoundary(std::prev(I), MBB, MF, TII, IsPostRA))
434 // Notify the scheduler of the region, even if we may skip scheduling
435 // it. Perhaps it still needs to be bundled.
436 Scheduler.enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
438 // Skip empty scheduling regions (0 or 1 schedulable instructions).
439 if (I == RegionEnd || I == std::prev(RegionEnd)) {
440 // Close the current region. Bundle the terminator if needed.
441 // This invalidates 'RegionEnd' and 'I'.
442 Scheduler.exitRegion();
445 DEBUG(dbgs() << "********** " << ((Scheduler.isPostRA()) ? "PostRA " : "")
446 << "MI Scheduling **********\n");
447 DEBUG(dbgs() << MF->getName()
448 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
449 << "\n From: " << *I << " To: ";
450 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
451 else dbgs() << "End";
452 dbgs() << " RegionInstrs: " << NumRegionInstrs
453 << " Remaining: " << RemainingInstrs << "\n");
455 // Schedule a region: possibly reorder instructions.
456 // This invalidates 'RegionEnd' and 'I'.
457 Scheduler.schedule();
459 // Close the current region.
460 Scheduler.exitRegion();
462 // Scheduling has invalidated the current iterator 'I'. Ask the
463 // scheduler for the top of it's scheduled region.
464 RegionEnd = Scheduler.begin();
466 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
467 Scheduler.finishBlock();
468 if (Scheduler.isPostRA()) {
469 // FIXME: Ideally, no further passes should rely on kill flags. However,
470 // thumb2 size reduction is currently an exception.
471 Scheduler.fixupKills(MBB);
474 Scheduler.finalizeSchedule();
477 void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
481 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
482 void ReadyQueue::dump() {
483 dbgs() << Name << ": ";
484 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
485 dbgs() << Queue[i]->NodeNum << " ";
490 //===----------------------------------------------------------------------===//
491 // ScheduleDAGMI - Basic machine instruction scheduling. This is
492 // independent of PreRA/PostRA scheduling and involves no extra book-keeping for
493 // virtual registers.
494 // ===----------------------------------------------------------------------===/
496 // Provide a vtable anchor.
497 ScheduleDAGMI::~ScheduleDAGMI() {
500 bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
501 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
504 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
505 if (SuccSU != &ExitSU) {
506 // Do not use WillCreateCycle, it assumes SD scheduling.
507 // If Pred is reachable from Succ, then the edge creates a cycle.
508 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
510 Topo.AddPred(SuccSU, PredDep.getSUnit());
512 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
513 // Return true regardless of whether a new edge needed to be inserted.
517 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
518 /// NumPredsLeft reaches zero, release the successor node.
520 /// FIXME: Adjust SuccSU height based on MinLatency.
521 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
522 SUnit *SuccSU = SuccEdge->getSUnit();
524 if (SuccEdge->isWeak()) {
525 --SuccSU->WeakPredsLeft;
526 if (SuccEdge->isCluster())
527 NextClusterSucc = SuccSU;
531 if (SuccSU->NumPredsLeft == 0) {
532 dbgs() << "*** Scheduling failed! ***\n";
534 dbgs() << " has been released too many times!\n";
535 llvm_unreachable(nullptr);
538 --SuccSU->NumPredsLeft;
539 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
540 SchedImpl->releaseTopNode(SuccSU);
543 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
544 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
545 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
547 releaseSucc(SU, &*I);
551 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
552 /// NumSuccsLeft reaches zero, release the predecessor node.
554 /// FIXME: Adjust PredSU height based on MinLatency.
555 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
556 SUnit *PredSU = PredEdge->getSUnit();
558 if (PredEdge->isWeak()) {
559 --PredSU->WeakSuccsLeft;
560 if (PredEdge->isCluster())
561 NextClusterPred = PredSU;
565 if (PredSU->NumSuccsLeft == 0) {
566 dbgs() << "*** Scheduling failed! ***\n";
568 dbgs() << " has been released too many times!\n";
569 llvm_unreachable(nullptr);
572 --PredSU->NumSuccsLeft;
573 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
574 SchedImpl->releaseBottomNode(PredSU);
577 /// releasePredecessors - Call releasePred on each of SU's predecessors.
578 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
579 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
581 releasePred(SU, &*I);
585 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
586 /// crossing a scheduling boundary. [begin, end) includes all instructions in
587 /// the region, including the boundary itself and single-instruction regions
588 /// that don't get scheduled.
589 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
590 MachineBasicBlock::iterator begin,
591 MachineBasicBlock::iterator end,
592 unsigned regioninstrs)
594 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
596 SchedImpl->initPolicy(begin, end, regioninstrs);
599 /// This is normally called from the main scheduler loop but may also be invoked
600 /// by the scheduling strategy to perform additional code motion.
601 void ScheduleDAGMI::moveInstruction(
602 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
603 // Advance RegionBegin if the first instruction moves down.
604 if (&*RegionBegin == MI)
607 // Update the instruction stream.
608 BB->splice(InsertPos, BB, MI);
610 // Update LiveIntervals
612 LIS->handleMove(MI, /*UpdateFlags=*/true);
614 // Recede RegionBegin if an instruction moves above the first.
615 if (RegionBegin == InsertPos)
619 bool ScheduleDAGMI::checkSchedLimit() {
621 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
622 CurrentTop = CurrentBottom;
625 ++NumInstrsScheduled;
630 /// Per-region scheduling driver, called back from
631 /// MachineScheduler::runOnMachineFunction. This is a simplified driver that
632 /// does not consider liveness or register pressure. It is useful for PostRA
633 /// scheduling and potentially other custom schedulers.
634 void ScheduleDAGMI::schedule() {
638 Topo.InitDAGTopologicalSorting();
642 SmallVector<SUnit*, 8> TopRoots, BotRoots;
643 findRootsAndBiasEdges(TopRoots, BotRoots);
645 // Initialize the strategy before modifying the DAG.
646 // This may initialize a DFSResult to be used for queue priority.
647 SchedImpl->initialize(this);
649 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
650 SUnits[su].dumpAll(this));
651 if (ViewMISchedDAGs) viewGraph();
653 // Initialize ready queues now that the DAG and priority data are finalized.
654 initQueues(TopRoots, BotRoots);
656 bool IsTopNode = false;
657 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
658 assert(!SU->isScheduled && "Node already scheduled");
659 if (!checkSchedLimit())
662 MachineInstr *MI = SU->getInstr();
664 assert(SU->isTopReady() && "node still has unscheduled dependencies");
665 if (&*CurrentTop == MI)
666 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
668 moveInstruction(MI, CurrentTop);
671 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
672 MachineBasicBlock::iterator priorII =
673 priorNonDebug(CurrentBottom, CurrentTop);
675 CurrentBottom = priorII;
677 if (&*CurrentTop == MI)
678 CurrentTop = nextIfDebug(++CurrentTop, priorII);
679 moveInstruction(MI, CurrentBottom);
683 updateQueues(SU, IsTopNode);
685 // Notify the scheduling strategy after updating the DAG.
686 SchedImpl->schedNode(SU, IsTopNode);
688 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
693 unsigned BBNum = begin()->getParent()->getNumber();
694 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
700 /// Apply each ScheduleDAGMutation step in order.
701 void ScheduleDAGMI::postprocessDAG() {
702 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
703 Mutations[i]->apply(this);
708 findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
709 SmallVectorImpl<SUnit*> &BotRoots) {
710 for (std::vector<SUnit>::iterator
711 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
713 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
715 // Order predecessors so DFSResult follows the critical path.
716 SU->biasCriticalPath();
718 // A SUnit is ready to top schedule if it has no predecessors.
719 if (!I->NumPredsLeft)
720 TopRoots.push_back(SU);
721 // A SUnit is ready to bottom schedule if it has no successors.
722 if (!I->NumSuccsLeft)
723 BotRoots.push_back(SU);
725 ExitSU.biasCriticalPath();
728 /// Identify DAG roots and setup scheduler queues.
729 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
730 ArrayRef<SUnit*> BotRoots) {
731 NextClusterSucc = nullptr;
732 NextClusterPred = nullptr;
734 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
736 // Nodes with unreleased weak edges can still be roots.
737 // Release top roots in forward order.
738 for (SmallVectorImpl<SUnit*>::const_iterator
739 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
740 SchedImpl->releaseTopNode(*I);
742 // Release bottom roots in reverse order so the higher priority nodes appear
743 // first. This is more natural and slightly more efficient.
744 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
745 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
746 SchedImpl->releaseBottomNode(*I);
749 releaseSuccessors(&EntrySU);
750 releasePredecessors(&ExitSU);
752 SchedImpl->registerRoots();
754 // Advance past initial DebugValues.
755 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
756 CurrentBottom = RegionEnd;
759 /// Update scheduler queues after scheduling an instruction.
760 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
761 // Release dependent instructions for scheduling.
763 releaseSuccessors(SU);
765 releasePredecessors(SU);
767 SU->isScheduled = true;
770 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
771 void ScheduleDAGMI::placeDebugValues() {
772 // If first instruction was a DBG_VALUE then put it back.
774 BB->splice(RegionBegin, BB, FirstDbgValue);
775 RegionBegin = FirstDbgValue;
778 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
779 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
780 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
781 MachineInstr *DbgValue = P.first;
782 MachineBasicBlock::iterator OrigPrevMI = P.second;
783 if (&*RegionBegin == DbgValue)
785 BB->splice(++OrigPrevMI, BB, DbgValue);
786 if (OrigPrevMI == std::prev(RegionEnd))
787 RegionEnd = DbgValue;
790 FirstDbgValue = nullptr;
793 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
794 void ScheduleDAGMI::dumpSchedule() const {
795 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
796 if (SUnit *SU = getSUnit(&(*MI)))
799 dbgs() << "Missing SUnit\n";
804 //===----------------------------------------------------------------------===//
805 // ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
807 //===----------------------------------------------------------------------===//
809 ScheduleDAGMILive::~ScheduleDAGMILive() {
813 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
814 /// crossing a scheduling boundary. [begin, end) includes all instructions in
815 /// the region, including the boundary itself and single-instruction regions
816 /// that don't get scheduled.
817 void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
818 MachineBasicBlock::iterator begin,
819 MachineBasicBlock::iterator end,
820 unsigned regioninstrs)
822 // ScheduleDAGMI initializes SchedImpl's per-region policy.
823 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
825 // For convenience remember the end of the liveness region.
826 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
828 SUPressureDiffs.clear();
830 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
833 // Setup the register pressure trackers for the top scheduled top and bottom
834 // scheduled regions.
835 void ScheduleDAGMILive::initRegPressure() {
836 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
837 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
839 // Close the RPTracker to finalize live ins.
840 RPTracker.closeRegion();
842 DEBUG(RPTracker.dump());
844 // Initialize the live ins and live outs.
845 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
846 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
848 // Close one end of the tracker so we can call
849 // getMaxUpward/DownwardPressureDelta before advancing across any
850 // instructions. This converts currently live regs into live ins/outs.
851 TopRPTracker.closeTop();
852 BotRPTracker.closeBottom();
854 BotRPTracker.initLiveThru(RPTracker);
855 if (!BotRPTracker.getLiveThru().empty()) {
856 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
857 DEBUG(dbgs() << "Live Thru: ";
858 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
861 // For each live out vreg reduce the pressure change associated with other
862 // uses of the same vreg below the live-out reaching def.
863 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
865 // Account for liveness generated by the region boundary.
866 if (LiveRegionEnd != RegionEnd) {
867 SmallVector<unsigned, 8> LiveUses;
868 BotRPTracker.recede(&LiveUses);
869 updatePressureDiffs(LiveUses);
872 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
874 // Cache the list of excess pressure sets in this region. This will also track
875 // the max pressure in the scheduled code for these sets.
876 RegionCriticalPSets.clear();
877 const std::vector<unsigned> &RegionPressure =
878 RPTracker.getPressure().MaxSetPressure;
879 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
880 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
881 if (RegionPressure[i] > Limit) {
882 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
883 << " Limit " << Limit
884 << " Actual " << RegionPressure[i] << "\n");
885 RegionCriticalPSets.push_back(PressureChange(i));
888 DEBUG(dbgs() << "Excess PSets: ";
889 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
890 dbgs() << TRI->getRegPressureSetName(
891 RegionCriticalPSets[i].getPSet()) << " ";
895 void ScheduleDAGMILive::
896 updateScheduledPressure(const SUnit *SU,
897 const std::vector<unsigned> &NewMaxPressure) {
898 const PressureDiff &PDiff = getPressureDiff(SU);
899 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
900 for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
904 unsigned ID = I->getPSet();
905 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
907 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
908 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
909 && NewMaxPressure[ID] <= INT16_MAX)
910 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
912 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
913 if (NewMaxPressure[ID] >= Limit - 2) {
914 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
915 << NewMaxPressure[ID] << " > " << Limit << "(+ "
916 << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
921 /// Update the PressureDiff array for liveness after scheduling this
923 void ScheduleDAGMILive::updatePressureDiffs(ArrayRef<unsigned> LiveUses) {
924 for (unsigned LUIdx = 0, LUEnd = LiveUses.size(); LUIdx != LUEnd; ++LUIdx) {
925 /// FIXME: Currently assuming single-use physregs.
926 unsigned Reg = LiveUses[LUIdx];
927 DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
928 if (!TRI->isVirtualRegister(Reg))
931 // This may be called before CurrentBottom has been initialized. However,
932 // BotRPTracker must have a valid position. We want the value live into the
933 // instruction or live out of the block, so ask for the previous
934 // instruction's live-out.
935 const LiveInterval &LI = LIS->getInterval(Reg);
937 MachineBasicBlock::const_iterator I =
938 nextIfDebug(BotRPTracker.getPos(), BB->end());
940 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
942 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(I));
945 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
946 assert(VNI && "No live value at use.");
947 for (VReg2UseMap::iterator
948 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
950 DEBUG(dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
952 // If this use comes before the reaching def, it cannot be a last use, so
953 // descrease its pressure change.
954 if (!SU->isScheduled && SU != &ExitSU) {
956 = LI.Query(LIS->getInstructionIndex(SU->getInstr()));
957 if (LRQ.valueIn() == VNI)
958 getPressureDiff(SU).addPressureChange(Reg, true, &MRI);
964 /// schedule - Called back from MachineScheduler::runOnMachineFunction
965 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
966 /// only includes instructions that have DAG nodes, not scheduling boundaries.
968 /// This is a skeletal driver, with all the functionality pushed into helpers,
969 /// so that it can be easilly extended by experimental schedulers. Generally,
970 /// implementing MachineSchedStrategy should be sufficient to implement a new
971 /// scheduling algorithm. However, if a scheduler further subclasses
972 /// ScheduleDAGMILive then it will want to override this virtual method in order
973 /// to update any specialized state.
974 void ScheduleDAGMILive::schedule() {
975 buildDAGWithRegPressure();
977 Topo.InitDAGTopologicalSorting();
981 SmallVector<SUnit*, 8> TopRoots, BotRoots;
982 findRootsAndBiasEdges(TopRoots, BotRoots);
984 // Initialize the strategy before modifying the DAG.
985 // This may initialize a DFSResult to be used for queue priority.
986 SchedImpl->initialize(this);
988 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
989 SUnits[su].dumpAll(this));
990 if (ViewMISchedDAGs) viewGraph();
992 // Initialize ready queues now that the DAG and priority data are finalized.
993 initQueues(TopRoots, BotRoots);
995 if (ShouldTrackPressure) {
996 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
997 TopRPTracker.setPos(CurrentTop);
1000 bool IsTopNode = false;
1001 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
1002 assert(!SU->isScheduled && "Node already scheduled");
1003 if (!checkSchedLimit())
1006 scheduleMI(SU, IsTopNode);
1008 updateQueues(SU, IsTopNode);
1011 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1012 if (!ScheduledTrees.test(SubtreeID)) {
1013 ScheduledTrees.set(SubtreeID);
1014 DFSResult->scheduleTree(SubtreeID);
1015 SchedImpl->scheduleTree(SubtreeID);
1019 // Notify the scheduling strategy after updating the DAG.
1020 SchedImpl->schedNode(SU, IsTopNode);
1022 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1027 unsigned BBNum = begin()->getParent()->getNumber();
1028 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1034 /// Build the DAG and setup three register pressure trackers.
1035 void ScheduleDAGMILive::buildDAGWithRegPressure() {
1036 if (!ShouldTrackPressure) {
1038 RegionCriticalPSets.clear();
1039 buildSchedGraph(AA);
1043 // Initialize the register pressure tracker used by buildSchedGraph.
1044 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1045 /*TrackUntiedDefs=*/true);
1047 // Account for liveness generate by the region boundary.
1048 if (LiveRegionEnd != RegionEnd)
1051 // Build the DAG, and compute current register pressure.
1052 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs);
1054 // Initialize top/bottom trackers after computing region pressure.
1058 void ScheduleDAGMILive::computeDFSResult() {
1060 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1062 ScheduledTrees.clear();
1063 DFSResult->resize(SUnits.size());
1064 DFSResult->compute(SUnits);
1065 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1068 /// Compute the max cyclic critical path through the DAG. The scheduling DAG
1069 /// only provides the critical path for single block loops. To handle loops that
1070 /// span blocks, we could use the vreg path latencies provided by
1071 /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1072 /// available for use in the scheduler.
1074 /// The cyclic path estimation identifies a def-use pair that crosses the back
1075 /// edge and considers the depth and height of the nodes. For example, consider
1076 /// the following instruction sequence where each instruction has unit latency
1077 /// and defines an epomymous virtual register:
1079 /// a->b(a,c)->c(b)->d(c)->exit
1081 /// The cyclic critical path is a two cycles: b->c->b
1082 /// The acyclic critical path is four cycles: a->b->c->d->exit
1083 /// LiveOutHeight = height(c) = len(c->d->exit) = 2
1084 /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1085 /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1086 /// LiveInDepth = depth(b) = len(a->b) = 1
1088 /// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1089 /// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1090 /// CyclicCriticalPath = min(2, 2) = 2
1092 /// This could be relevant to PostRA scheduling, but is currently implemented
1093 /// assuming LiveIntervals.
1094 unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
1095 // This only applies to single block loop.
1096 if (!BB->isSuccessor(BB))
1099 unsigned MaxCyclicLatency = 0;
1100 // Visit each live out vreg def to find def/use pairs that cross iterations.
1101 ArrayRef<unsigned> LiveOuts = RPTracker.getPressure().LiveOutRegs;
1102 for (ArrayRef<unsigned>::iterator RI = LiveOuts.begin(), RE = LiveOuts.end();
1105 if (!TRI->isVirtualRegister(Reg))
1107 const LiveInterval &LI = LIS->getInterval(Reg);
1108 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1112 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1113 const SUnit *DefSU = getSUnit(DefMI);
1117 unsigned LiveOutHeight = DefSU->getHeight();
1118 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1119 // Visit all local users of the vreg def.
1120 for (VReg2UseMap::iterator
1121 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
1122 if (UI->SU == &ExitSU)
1125 // Only consider uses of the phi.
1126 LiveQueryResult LRQ =
1127 LI.Query(LIS->getInstructionIndex(UI->SU->getInstr()));
1128 if (!LRQ.valueIn()->isPHIDef())
1131 // Assume that a path spanning two iterations is a cycle, which could
1132 // overestimate in strange cases. This allows cyclic latency to be
1133 // estimated as the minimum slack of the vreg's depth or height.
1134 unsigned CyclicLatency = 0;
1135 if (LiveOutDepth > UI->SU->getDepth())
1136 CyclicLatency = LiveOutDepth - UI->SU->getDepth();
1138 unsigned LiveInHeight = UI->SU->getHeight() + DefSU->Latency;
1139 if (LiveInHeight > LiveOutHeight) {
1140 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1141 CyclicLatency = LiveInHeight - LiveOutHeight;
1146 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1147 << UI->SU->NodeNum << ") = " << CyclicLatency << "c\n");
1148 if (CyclicLatency > MaxCyclicLatency)
1149 MaxCyclicLatency = CyclicLatency;
1152 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1153 return MaxCyclicLatency;
1156 /// Move an instruction and update register pressure.
1157 void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
1158 // Move the instruction to its new location in the instruction stream.
1159 MachineInstr *MI = SU->getInstr();
1162 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1163 if (&*CurrentTop == MI)
1164 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
1166 moveInstruction(MI, CurrentTop);
1167 TopRPTracker.setPos(MI);
1170 if (ShouldTrackPressure) {
1171 // Update top scheduled pressure.
1172 TopRPTracker.advance();
1173 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
1174 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
1178 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1179 MachineBasicBlock::iterator priorII =
1180 priorNonDebug(CurrentBottom, CurrentTop);
1181 if (&*priorII == MI)
1182 CurrentBottom = priorII;
1184 if (&*CurrentTop == MI) {
1185 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1186 TopRPTracker.setPos(CurrentTop);
1188 moveInstruction(MI, CurrentBottom);
1191 if (ShouldTrackPressure) {
1192 // Update bottom scheduled pressure.
1193 SmallVector<unsigned, 8> LiveUses;
1194 BotRPTracker.recede(&LiveUses);
1195 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
1196 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
1197 updatePressureDiffs(LiveUses);
1202 //===----------------------------------------------------------------------===//
1203 // LoadClusterMutation - DAG post-processing to cluster loads.
1204 //===----------------------------------------------------------------------===//
1207 /// \brief Post-process the DAG to create cluster edges between neighboring
1209 class LoadClusterMutation : public ScheduleDAGMutation {
1214 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
1215 : SU(su), BaseReg(reg), Offset(ofs) {}
1217 bool operator<(const LoadInfo &RHS) const {
1218 return std::tie(BaseReg, Offset) < std::tie(RHS.BaseReg, RHS.Offset);
1222 const TargetInstrInfo *TII;
1223 const TargetRegisterInfo *TRI;
1225 LoadClusterMutation(const TargetInstrInfo *tii,
1226 const TargetRegisterInfo *tri)
1227 : TII(tii), TRI(tri) {}
1229 void apply(ScheduleDAGMI *DAG) override;
1231 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
1235 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
1236 ScheduleDAGMI *DAG) {
1237 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
1238 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
1239 SUnit *SU = Loads[Idx];
1242 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
1243 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
1245 if (LoadRecords.size() < 2)
1247 std::sort(LoadRecords.begin(), LoadRecords.end());
1248 unsigned ClusterLength = 1;
1249 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
1250 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
1255 SUnit *SUa = LoadRecords[Idx].SU;
1256 SUnit *SUb = LoadRecords[Idx+1].SU;
1257 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
1258 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
1260 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
1261 << SUb->NodeNum << ")\n");
1262 // Copy successor edges from SUa to SUb. Interleaving computation
1263 // dependent on SUa can prevent load combining due to register reuse.
1264 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1265 // loads should have effectively the same inputs.
1266 for (SUnit::const_succ_iterator
1267 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
1268 if (SI->getSUnit() == SUb)
1270 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
1271 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
1280 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
1281 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
1282 // Map DAG NodeNum to store chain ID.
1283 DenseMap<unsigned, unsigned> StoreChainIDs;
1284 // Map each store chain to a set of dependent loads.
1285 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1286 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1287 SUnit *SU = &DAG->SUnits[Idx];
1288 if (!SU->getInstr()->mayLoad())
1290 unsigned ChainPredID = DAG->SUnits.size();
1291 for (SUnit::const_pred_iterator
1292 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1294 ChainPredID = PI->getSUnit()->NodeNum;
1298 // Check if this chain-like pred has been seen
1299 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
1300 unsigned NumChains = StoreChainDependents.size();
1301 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1302 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1304 StoreChainDependents.resize(NumChains + 1);
1305 StoreChainDependents[Result.first->second].push_back(SU);
1307 // Iterate over the store chains.
1308 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
1309 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
1312 //===----------------------------------------------------------------------===//
1313 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
1314 //===----------------------------------------------------------------------===//
1317 /// \brief Post-process the DAG to create cluster edges between instructions
1318 /// that may be fused by the processor into a single operation.
1319 class MacroFusion : public ScheduleDAGMutation {
1320 const TargetInstrInfo *TII;
1322 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
1324 void apply(ScheduleDAGMI *DAG) override;
1328 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
1329 /// fused operations.
1330 void MacroFusion::apply(ScheduleDAGMI *DAG) {
1331 // For now, assume targets can only fuse with the branch.
1332 MachineInstr *Branch = DAG->ExitSU.getInstr();
1336 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
1337 SUnit *SU = &DAG->SUnits[--Idx];
1338 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
1341 // Create a single weak edge from SU to ExitSU. The only effect is to cause
1342 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
1343 // need to copy predecessor edges from ExitSU to SU, since top-down
1344 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
1345 // of SU, we could create an artificial edge from the deepest root, but it
1346 // hasn't been needed yet.
1347 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
1349 assert(Success && "No DAG nodes should be reachable from ExitSU");
1351 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
1356 //===----------------------------------------------------------------------===//
1357 // CopyConstrain - DAG post-processing to encourage copy elimination.
1358 //===----------------------------------------------------------------------===//
1361 /// \brief Post-process the DAG to create weak edges from all uses of a copy to
1362 /// the one use that defines the copy's source vreg, most likely an induction
1363 /// variable increment.
1364 class CopyConstrain : public ScheduleDAGMutation {
1366 SlotIndex RegionBeginIdx;
1367 // RegionEndIdx is the slot index of the last non-debug instruction in the
1368 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
1369 SlotIndex RegionEndIdx;
1371 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1373 void apply(ScheduleDAGMI *DAG) override;
1376 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
1380 /// constrainLocalCopy handles two possibilities:
1385 /// I3: dst = src (copy)
1386 /// (create pred->succ edges I0->I1, I2->I1)
1389 /// I0: dst = src (copy)
1393 /// (create pred->succ edges I1->I2, I3->I2)
1395 /// Although the MachineScheduler is currently constrained to single blocks,
1396 /// this algorithm should handle extended blocks. An EBB is a set of
1397 /// contiguously numbered blocks such that the previous block in the EBB is
1398 /// always the single predecessor.
1399 void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
1400 LiveIntervals *LIS = DAG->getLIS();
1401 MachineInstr *Copy = CopySU->getInstr();
1403 // Check for pure vreg copies.
1404 unsigned SrcReg = Copy->getOperand(1).getReg();
1405 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1408 unsigned DstReg = Copy->getOperand(0).getReg();
1409 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1412 // Check if either the dest or source is local. If it's live across a back
1413 // edge, it's not local. Note that if both vregs are live across the back
1414 // edge, we cannot successfully contrain the copy without cyclic scheduling.
1415 unsigned LocalReg = DstReg;
1416 unsigned GlobalReg = SrcReg;
1417 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1418 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
1421 LocalLI = &LIS->getInterval(LocalReg);
1422 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1425 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1427 // Find the global segment after the start of the local LI.
1428 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1429 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1430 // local live range. We could create edges from other global uses to the local
1431 // start, but the coalescer should have already eliminated these cases, so
1432 // don't bother dealing with it.
1433 if (GlobalSegment == GlobalLI->end())
1436 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1437 // returned the next global segment. But if GlobalSegment overlaps with
1438 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1439 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1440 if (GlobalSegment->contains(LocalLI->beginIndex()))
1443 if (GlobalSegment == GlobalLI->end())
1446 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1447 if (GlobalSegment != GlobalLI->begin()) {
1448 // Two address defs have no hole.
1449 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
1450 GlobalSegment->start)) {
1453 // If the prior global segment may be defined by the same two-address
1454 // instruction that also defines LocalLI, then can't make a hole here.
1455 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
1456 LocalLI->beginIndex())) {
1459 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1460 // it would be a disconnected component in the live range.
1461 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
1462 "Disconnected LRG within the scheduling region.");
1464 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1468 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1472 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1473 // constraining the uses of the last local def to precede GlobalDef.
1474 SmallVector<SUnit*,8> LocalUses;
1475 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1476 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1477 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1478 for (SUnit::const_succ_iterator
1479 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1481 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1483 if (I->getSUnit() == GlobalSU)
1485 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1487 LocalUses.push_back(I->getSUnit());
1489 // Open the top of the GlobalLI hole by constraining any earlier global uses
1490 // to precede the start of LocalLI.
1491 SmallVector<SUnit*,8> GlobalUses;
1492 MachineInstr *FirstLocalDef =
1493 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1494 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1495 for (SUnit::const_pred_iterator
1496 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1497 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1499 if (I->getSUnit() == FirstLocalSU)
1501 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1503 GlobalUses.push_back(I->getSUnit());
1505 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1506 // Add the weak edges.
1507 for (SmallVectorImpl<SUnit*>::const_iterator
1508 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1509 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1510 << GlobalSU->NodeNum << ")\n");
1511 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1513 for (SmallVectorImpl<SUnit*>::const_iterator
1514 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1515 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1516 << FirstLocalSU->NodeNum << ")\n");
1517 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1521 /// \brief Callback from DAG postProcessing to create weak edges to encourage
1522 /// copy elimination.
1523 void CopyConstrain::apply(ScheduleDAGMI *DAG) {
1524 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1526 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1527 if (FirstPos == DAG->end())
1529 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(&*FirstPos);
1530 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1531 &*priorNonDebug(DAG->end(), DAG->begin()));
1533 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1534 SUnit *SU = &DAG->SUnits[Idx];
1535 if (!SU->getInstr()->isCopy())
1538 constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
1542 //===----------------------------------------------------------------------===//
1543 // MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1544 // and possibly other custom schedulers.
1545 //===----------------------------------------------------------------------===//
1547 static const unsigned InvalidCycle = ~0U;
1549 SchedBoundary::~SchedBoundary() { delete HazardRec; }
1551 void SchedBoundary::reset() {
1552 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1553 // Destroying and reconstructing it is very expensive though. So keep
1554 // invalid, placeholder HazardRecs.
1555 if (HazardRec && HazardRec->isEnabled()) {
1557 HazardRec = nullptr;
1561 CheckPending = false;
1565 MinReadyCycle = UINT_MAX;
1566 ExpectedLatency = 0;
1567 DependentLatency = 0;
1569 MaxExecutedResCount = 0;
1571 IsResourceLimited = false;
1572 ReservedCycles.clear();
1574 // Track the maximum number of stall cycles that could arise either from the
1575 // latency of a DAG edge or the number of cycles that a processor resource is
1576 // reserved (SchedBoundary::ReservedCycles).
1577 MaxObservedLatency = 0;
1579 // Reserve a zero-count for invalid CritResIdx.
1580 ExecutedResCounts.resize(1);
1581 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1584 void SchedRemainder::
1585 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1587 if (!SchedModel->hasInstrSchedModel())
1589 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1590 for (std::vector<SUnit>::iterator
1591 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1592 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1593 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1594 * SchedModel->getMicroOpFactor();
1595 for (TargetSchedModel::ProcResIter
1596 PI = SchedModel->getWriteProcResBegin(SC),
1597 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1598 unsigned PIdx = PI->ProcResourceIdx;
1599 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1600 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1605 void SchedBoundary::
1606 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1609 SchedModel = smodel;
1611 if (SchedModel->hasInstrSchedModel()) {
1612 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
1613 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1617 /// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1618 /// these "soft stalls" differently than the hard stall cycles based on CPU
1619 /// resources and computed by checkHazard(). A fully in-order model
1620 /// (MicroOpBufferSize==0) will not make use of this since instructions are not
1621 /// available for scheduling until they are ready. However, a weaker in-order
1622 /// model may use this for heuristics. For example, if a processor has in-order
1623 /// behavior when reading certain resources, this may come into play.
1624 unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
1625 if (!SU->isUnbuffered)
1628 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1629 if (ReadyCycle > CurrCycle)
1630 return ReadyCycle - CurrCycle;
1634 /// Compute the next cycle at which the given processor resource can be
1636 unsigned SchedBoundary::
1637 getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1638 unsigned NextUnreserved = ReservedCycles[PIdx];
1639 // If this resource has never been used, always return cycle zero.
1640 if (NextUnreserved == InvalidCycle)
1642 // For bottom-up scheduling add the cycles needed for the current operation.
1644 NextUnreserved += Cycles;
1645 return NextUnreserved;
1648 /// Does this SU have a hazard within the current instruction group.
1650 /// The scheduler supports two modes of hazard recognition. The first is the
1651 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1652 /// supports highly complicated in-order reservation tables
1653 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1655 /// The second is a streamlined mechanism that checks for hazards based on
1656 /// simple counters that the scheduler itself maintains. It explicitly checks
1657 /// for instruction dispatch limitations, including the number of micro-ops that
1658 /// can dispatch per cycle.
1660 /// TODO: Also check whether the SU must start a new group.
1661 bool SchedBoundary::checkHazard(SUnit *SU) {
1662 if (HazardRec->isEnabled()
1663 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1666 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1667 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
1668 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1669 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1672 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1673 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1674 for (TargetSchedModel::ProcResIter
1675 PI = SchedModel->getWriteProcResBegin(SC),
1676 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1677 if (getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles) > CurrCycle)
1684 // Find the unscheduled node in ReadySUs with the highest latency.
1685 unsigned SchedBoundary::
1686 findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
1687 SUnit *LateSU = nullptr;
1688 unsigned RemLatency = 0;
1689 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
1691 unsigned L = getUnscheduledLatency(*I);
1692 if (L > RemLatency) {
1698 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1699 << LateSU->NodeNum << ") " << RemLatency << "c\n");
1704 // Count resources in this zone and the remaining unscheduled
1705 // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1706 // resource index, or zero if the zone is issue limited.
1707 unsigned SchedBoundary::
1708 getOtherResourceCount(unsigned &OtherCritIdx) {
1710 if (!SchedModel->hasInstrSchedModel())
1713 unsigned OtherCritCount = Rem->RemIssueCount
1714 + (RetiredMOps * SchedModel->getMicroOpFactor());
1715 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1716 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
1717 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1718 PIdx != PEnd; ++PIdx) {
1719 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1720 if (OtherCount > OtherCritCount) {
1721 OtherCritCount = OtherCount;
1722 OtherCritIdx = PIdx;
1726 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
1727 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
1728 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
1730 return OtherCritCount;
1733 void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
1734 if (ReadyCycle < MinReadyCycle)
1735 MinReadyCycle = ReadyCycle;
1737 // Check for interlocks first. For the purpose of other heuristics, an
1738 // instruction that cannot issue appears as if it's not in the ReadyQueue.
1739 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1740 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU))
1745 // Record this node as an immediate dependent of the scheduled node.
1749 void SchedBoundary::releaseTopNode(SUnit *SU) {
1750 if (SU->isScheduled)
1753 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1757 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1758 unsigned Latency = I->getLatency();
1760 MaxObservedLatency = std::max(Latency, MaxObservedLatency);
1762 if (SU->TopReadyCycle < PredReadyCycle + Latency)
1763 SU->TopReadyCycle = PredReadyCycle + Latency;
1765 releaseNode(SU, SU->TopReadyCycle);
1768 void SchedBoundary::releaseBottomNode(SUnit *SU) {
1769 if (SU->isScheduled)
1772 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1774 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1778 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1779 unsigned Latency = I->getLatency();
1781 MaxObservedLatency = std::max(Latency, MaxObservedLatency);
1783 if (SU->BotReadyCycle < SuccReadyCycle + Latency)
1784 SU->BotReadyCycle = SuccReadyCycle + Latency;
1786 releaseNode(SU, SU->BotReadyCycle);
1789 /// Move the boundary of scheduled code by one cycle.
1790 void SchedBoundary::bumpCycle(unsigned NextCycle) {
1791 if (SchedModel->getMicroOpBufferSize() == 0) {
1792 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1793 if (MinReadyCycle > NextCycle)
1794 NextCycle = MinReadyCycle;
1796 // Update the current micro-ops, which will issue in the next cycle.
1797 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1798 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1800 // Decrement DependentLatency based on the next cycle.
1801 if ((NextCycle - CurrCycle) > DependentLatency)
1802 DependentLatency = 0;
1804 DependentLatency -= (NextCycle - CurrCycle);
1806 if (!HazardRec->isEnabled()) {
1807 // Bypass HazardRec virtual calls.
1808 CurrCycle = NextCycle;
1811 // Bypass getHazardType calls in case of long latency.
1812 for (; CurrCycle != NextCycle; ++CurrCycle) {
1814 HazardRec->AdvanceCycle();
1816 HazardRec->RecedeCycle();
1819 CheckPending = true;
1820 unsigned LFactor = SchedModel->getLatencyFactor();
1822 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1825 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
1828 void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
1829 ExecutedResCounts[PIdx] += Count;
1830 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
1831 MaxExecutedResCount = ExecutedResCounts[PIdx];
1834 /// Add the given processor resource to this scheduled zone.
1836 /// \param Cycles indicates the number of consecutive (non-pipelined) cycles
1837 /// during which this resource is consumed.
1839 /// \return the next cycle at which the instruction may execute without
1840 /// oversubscribing resources.
1841 unsigned SchedBoundary::
1842 countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
1843 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1844 unsigned Count = Factor * Cycles;
1845 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
1846 << " +" << Cycles << "x" << Factor << "u\n");
1848 // Update Executed resources counts.
1849 incExecutedResources(PIdx, Count);
1850 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1851 Rem->RemainingCounts[PIdx] -= Count;
1853 // Check if this resource exceeds the current critical resource. If so, it
1854 // becomes the critical resource.
1855 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
1856 ZoneCritResIdx = PIdx;
1857 DEBUG(dbgs() << " *** Critical resource "
1858 << SchedModel->getResourceName(PIdx) << ": "
1859 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
1861 // For reserved resources, record the highest cycle using the resource.
1862 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
1863 if (NextAvailable > CurrCycle) {
1864 DEBUG(dbgs() << " Resource conflict: "
1865 << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
1866 << NextAvailable << "\n");
1868 return NextAvailable;
1871 /// Move the boundary of scheduled code by one SUnit.
1872 void SchedBoundary::bumpNode(SUnit *SU) {
1873 // Update the reservation table.
1874 if (HazardRec->isEnabled()) {
1875 if (!isTop() && SU->isCall) {
1876 // Calls are scheduled with their preceding instructions. For bottom-up
1877 // scheduling, clear the pipeline state before emitting.
1880 HazardRec->EmitInstruction(SU);
1882 // checkHazard should prevent scheduling multiple instructions per cycle that
1883 // exceed the issue width.
1884 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1885 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
1887 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
1888 "Cannot schedule this instruction's MicroOps in the current cycle.");
1890 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1891 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
1893 unsigned NextCycle = CurrCycle;
1894 switch (SchedModel->getMicroOpBufferSize()) {
1896 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
1899 if (ReadyCycle > NextCycle) {
1900 NextCycle = ReadyCycle;
1901 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
1905 // We don't currently model the OOO reorder buffer, so consider all
1906 // scheduled MOps to be "retired". We do loosely model in-order resource
1907 // latency. If this instruction uses an in-order resource, account for any
1908 // likely stall cycles.
1909 if (SU->isUnbuffered && ReadyCycle > NextCycle)
1910 NextCycle = ReadyCycle;
1913 RetiredMOps += IncMOps;
1915 // Update resource counts and critical resource.
1916 if (SchedModel->hasInstrSchedModel()) {
1917 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
1918 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
1919 Rem->RemIssueCount -= DecRemIssue;
1920 if (ZoneCritResIdx) {
1921 // Scale scheduled micro-ops for comparing with the critical resource.
1922 unsigned ScaledMOps =
1923 RetiredMOps * SchedModel->getMicroOpFactor();
1925 // If scaled micro-ops are now more than the previous critical resource by
1926 // a full cycle, then micro-ops issue becomes critical.
1927 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
1928 >= (int)SchedModel->getLatencyFactor()) {
1930 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
1931 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
1934 for (TargetSchedModel::ProcResIter
1935 PI = SchedModel->getWriteProcResBegin(SC),
1936 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1938 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
1939 if (RCycle > NextCycle)
1942 if (SU->hasReservedResource) {
1943 // For reserved resources, record the highest cycle using the resource.
1944 // For top-down scheduling, this is the cycle in which we schedule this
1945 // instruction plus the number of cycles the operations reserves the
1946 // resource. For bottom-up is it simply the instruction's cycle.
1947 for (TargetSchedModel::ProcResIter
1948 PI = SchedModel->getWriteProcResBegin(SC),
1949 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1950 unsigned PIdx = PI->ProcResourceIdx;
1951 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
1952 ReservedCycles[PIdx] = isTop() ? NextCycle + PI->Cycles : NextCycle;
1954 MaxObservedLatency = std::max(PI->Cycles, MaxObservedLatency);
1960 // Update ExpectedLatency and DependentLatency.
1961 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
1962 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
1963 if (SU->getDepth() > TopLatency) {
1964 TopLatency = SU->getDepth();
1965 DEBUG(dbgs() << " " << Available.getName()
1966 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
1968 if (SU->getHeight() > BotLatency) {
1969 BotLatency = SU->getHeight();
1970 DEBUG(dbgs() << " " << Available.getName()
1971 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
1973 // If we stall for any reason, bump the cycle.
1974 if (NextCycle > CurrCycle) {
1975 bumpCycle(NextCycle);
1978 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
1979 // resource limited. If a stall occurred, bumpCycle does this.
1980 unsigned LFactor = SchedModel->getLatencyFactor();
1982 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1985 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
1986 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
1987 // one cycle. Since we commonly reach the max MOps here, opportunistically
1988 // bump the cycle to avoid uselessly checking everything in the readyQ.
1989 CurrMOps += IncMOps;
1990 while (CurrMOps >= SchedModel->getIssueWidth()) {
1991 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
1992 << " at cycle " << CurrCycle << '\n');
1993 bumpCycle(++NextCycle);
1995 DEBUG(dumpScheduledState());
1998 /// Release pending ready nodes in to the available queue. This makes them
1999 /// visible to heuristics.
2000 void SchedBoundary::releasePending() {
2001 // If the available queue is empty, it is safe to reset MinReadyCycle.
2002 if (Available.empty())
2003 MinReadyCycle = UINT_MAX;
2005 // Check to see if any of the pending instructions are ready to issue. If
2006 // so, add them to the available queue.
2007 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
2008 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2009 SUnit *SU = *(Pending.begin()+i);
2010 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
2012 if (ReadyCycle < MinReadyCycle)
2013 MinReadyCycle = ReadyCycle;
2015 if (!IsBuffered && ReadyCycle > CurrCycle)
2018 if (checkHazard(SU))
2022 Pending.remove(Pending.begin()+i);
2025 DEBUG(if (!Pending.empty()) Pending.dump());
2026 CheckPending = false;
2029 /// Remove SU from the ready set for this boundary.
2030 void SchedBoundary::removeReady(SUnit *SU) {
2031 if (Available.isInQueue(SU))
2032 Available.remove(Available.find(SU));
2034 assert(Pending.isInQueue(SU) && "bad ready count");
2035 Pending.remove(Pending.find(SU));
2039 /// If this queue only has one ready candidate, return it. As a side effect,
2040 /// defer any nodes that now hit a hazard, and advance the cycle until at least
2041 /// one node is ready. If multiple instructions are ready, return NULL.
2042 SUnit *SchedBoundary::pickOnlyChoice() {
2047 // Defer any ready instrs that now have a hazard.
2048 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2049 if (checkHazard(*I)) {
2051 I = Available.remove(I);
2057 for (unsigned i = 0; Available.empty(); ++i) {
2058 assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedLatency) &&
2059 "permanent hazard"); (void)i;
2060 bumpCycle(CurrCycle + 1);
2063 if (Available.size() == 1)
2064 return *Available.begin();
2069 // This is useful information to dump after bumpNode.
2070 // Note that the Queue contents are more useful before pickNodeFromQueue.
2071 void SchedBoundary::dumpScheduledState() {
2074 if (ZoneCritResIdx) {
2075 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2076 ResCount = getResourceCount(ZoneCritResIdx);
2079 ResFactor = SchedModel->getMicroOpFactor();
2080 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
2082 unsigned LFactor = SchedModel->getLatencyFactor();
2083 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2084 << " Retired: " << RetiredMOps;
2085 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2086 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
2087 << ResCount / ResFactor << " "
2088 << SchedModel->getResourceName(ZoneCritResIdx)
2089 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2090 << (IsResourceLimited ? " - Resource" : " - Latency")
2095 //===----------------------------------------------------------------------===//
2096 // GenericScheduler - Generic implementation of MachineSchedStrategy.
2097 //===----------------------------------------------------------------------===//
2099 void GenericSchedulerBase::SchedCandidate::
2100 initResourceDelta(const ScheduleDAGMI *DAG,
2101 const TargetSchedModel *SchedModel) {
2102 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2105 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2106 for (TargetSchedModel::ProcResIter
2107 PI = SchedModel->getWriteProcResBegin(SC),
2108 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2109 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2110 ResDelta.CritResources += PI->Cycles;
2111 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2112 ResDelta.DemandedResources += PI->Cycles;
2116 /// Set the CandPolicy given a scheduling zone given the current resources and
2117 /// latencies inside and outside the zone.
2118 void GenericSchedulerBase::setPolicy(CandPolicy &Policy,
2120 SchedBoundary &CurrZone,
2121 SchedBoundary *OtherZone) {
2122 // Apply preemptive heuristics based on the the total latency and resources
2123 // inside and outside this zone. Potential stalls should be considered before
2124 // following this policy.
2126 // Compute remaining latency. We need this both to determine whether the
2127 // overall schedule has become latency-limited and whether the instructions
2128 // outside this zone are resource or latency limited.
2130 // The "dependent" latency is updated incrementally during scheduling as the
2131 // max height/depth of scheduled nodes minus the cycles since it was
2133 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2135 // The "independent" latency is the max ready queue depth:
2136 // ILat = max N.depth for N in Available|Pending
2138 // RemainingLatency is the greater of independent and dependent latency.
2139 unsigned RemLatency = CurrZone.getDependentLatency();
2140 RemLatency = std::max(RemLatency,
2141 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2142 RemLatency = std::max(RemLatency,
2143 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2145 // Compute the critical resource outside the zone.
2146 unsigned OtherCritIdx = 0;
2147 unsigned OtherCount =
2148 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2150 bool OtherResLimited = false;
2151 if (SchedModel->hasInstrSchedModel()) {
2152 unsigned LFactor = SchedModel->getLatencyFactor();
2153 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2155 // Schedule aggressively for latency in PostRA mode. We don't check for
2156 // acyclic latency during PostRA, and highly out-of-order processors will
2157 // skip PostRA scheduling.
2158 if (!OtherResLimited) {
2159 if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2160 Policy.ReduceLatency |= true;
2161 DEBUG(dbgs() << " " << CurrZone.Available.getName()
2162 << " RemainingLatency " << RemLatency << " + "
2163 << CurrZone.getCurrCycle() << "c > CritPath "
2164 << Rem.CriticalPath << "\n");
2167 // If the same resource is limiting inside and outside the zone, do nothing.
2168 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2172 if (CurrZone.isResourceLimited()) {
2173 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2174 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2177 if (OtherResLimited)
2178 dbgs() << " RemainingLimit: "
2179 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2180 if (!CurrZone.isResourceLimited() && !OtherResLimited)
2181 dbgs() << " Latency limited both directions.\n");
2183 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2184 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2186 if (OtherResLimited)
2187 Policy.DemandResIdx = OtherCritIdx;
2191 const char *GenericSchedulerBase::getReasonStr(
2192 GenericSchedulerBase::CandReason Reason) {
2194 case NoCand: return "NOCAND ";
2195 case PhysRegCopy: return "PREG-COPY";
2196 case RegExcess: return "REG-EXCESS";
2197 case RegCritical: return "REG-CRIT ";
2198 case Stall: return "STALL ";
2199 case Cluster: return "CLUSTER ";
2200 case Weak: return "WEAK ";
2201 case RegMax: return "REG-MAX ";
2202 case ResourceReduce: return "RES-REDUCE";
2203 case ResourceDemand: return "RES-DEMAND";
2204 case TopDepthReduce: return "TOP-DEPTH ";
2205 case TopPathReduce: return "TOP-PATH ";
2206 case BotHeightReduce:return "BOT-HEIGHT";
2207 case BotPathReduce: return "BOT-PATH ";
2208 case NextDefUse: return "DEF-USE ";
2209 case NodeOrder: return "ORDER ";
2211 llvm_unreachable("Unknown reason!");
2214 void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2216 unsigned ResIdx = 0;
2217 unsigned Latency = 0;
2218 switch (Cand.Reason) {
2222 P = Cand.RPDelta.Excess;
2225 P = Cand.RPDelta.CriticalMax;
2228 P = Cand.RPDelta.CurrentMax;
2230 case ResourceReduce:
2231 ResIdx = Cand.Policy.ReduceResIdx;
2233 case ResourceDemand:
2234 ResIdx = Cand.Policy.DemandResIdx;
2236 case TopDepthReduce:
2237 Latency = Cand.SU->getDepth();
2240 Latency = Cand.SU->getHeight();
2242 case BotHeightReduce:
2243 Latency = Cand.SU->getHeight();
2246 Latency = Cand.SU->getDepth();
2249 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
2251 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2252 << ":" << P.getUnitInc() << " ";
2256 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2260 dbgs() << " " << Latency << " cycles ";
2267 /// Return true if this heuristic determines order.
2268 static bool tryLess(int TryVal, int CandVal,
2269 GenericSchedulerBase::SchedCandidate &TryCand,
2270 GenericSchedulerBase::SchedCandidate &Cand,
2271 GenericSchedulerBase::CandReason Reason) {
2272 if (TryVal < CandVal) {
2273 TryCand.Reason = Reason;
2276 if (TryVal > CandVal) {
2277 if (Cand.Reason > Reason)
2278 Cand.Reason = Reason;
2281 Cand.setRepeat(Reason);
2285 static bool tryGreater(int TryVal, int CandVal,
2286 GenericSchedulerBase::SchedCandidate &TryCand,
2287 GenericSchedulerBase::SchedCandidate &Cand,
2288 GenericSchedulerBase::CandReason Reason) {
2289 if (TryVal > CandVal) {
2290 TryCand.Reason = Reason;
2293 if (TryVal < CandVal) {
2294 if (Cand.Reason > Reason)
2295 Cand.Reason = Reason;
2298 Cand.setRepeat(Reason);
2302 static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2303 GenericSchedulerBase::SchedCandidate &Cand,
2304 SchedBoundary &Zone) {
2306 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2307 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2308 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2311 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2312 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2316 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2317 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2318 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2321 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2322 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2328 static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand,
2330 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2331 << GenericSchedulerBase::getReasonStr(Cand.Reason) << '\n');
2334 void GenericScheduler::initialize(ScheduleDAGMI *dag) {
2335 assert(dag->hasVRegLiveness() &&
2336 "(PreRA)GenericScheduler needs vreg liveness");
2337 DAG = static_cast<ScheduleDAGMILive*>(dag);
2338 SchedModel = DAG->getSchedModel();
2341 Rem.init(DAG, SchedModel);
2342 Top.init(DAG, SchedModel, &Rem);
2343 Bot.init(DAG, SchedModel, &Rem);
2345 // Initialize resource counts.
2347 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2348 // are disabled, then these HazardRecs will be disabled.
2349 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
2350 const TargetMachine &TM = DAG->MF.getTarget();
2351 if (!Top.HazardRec) {
2353 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2355 if (!Bot.HazardRec) {
2357 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2361 /// Initialize the per-region scheduling policy.
2362 void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2363 MachineBasicBlock::iterator End,
2364 unsigned NumRegionInstrs) {
2365 const TargetMachine &TM = Context->MF->getTarget();
2366 const TargetLowering *TLI = TM.getTargetLowering();
2368 // Avoid setting up the register pressure tracker for small regions to save
2369 // compile time. As a rough heuristic, only track pressure when the number of
2370 // schedulable instructions exceeds half the integer register file.
2371 RegionPolicy.ShouldTrackPressure = true;
2372 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2373 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2374 if (TLI->isTypeLegal(LegalIntVT)) {
2375 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
2376 TLI->getRegClassFor(LegalIntVT));
2377 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2381 // For generic targets, we default to bottom-up, because it's simpler and more
2382 // compile-time optimizations have been implemented in that direction.
2383 RegionPolicy.OnlyBottomUp = true;
2385 // Allow the subtarget to override default policy.
2386 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
2387 ST.overrideSchedPolicy(RegionPolicy, Begin, End, NumRegionInstrs);
2389 // After subtarget overrides, apply command line options.
2390 if (!EnableRegPressure)
2391 RegionPolicy.ShouldTrackPressure = false;
2393 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2394 // e.g. -misched-bottomup=false allows scheduling in both directions.
2395 assert((!ForceTopDown || !ForceBottomUp) &&
2396 "-misched-topdown incompatible with -misched-bottomup");
2397 if (ForceBottomUp.getNumOccurrences() > 0) {
2398 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2399 if (RegionPolicy.OnlyBottomUp)
2400 RegionPolicy.OnlyTopDown = false;
2402 if (ForceTopDown.getNumOccurrences() > 0) {
2403 RegionPolicy.OnlyTopDown = ForceTopDown;
2404 if (RegionPolicy.OnlyTopDown)
2405 RegionPolicy.OnlyBottomUp = false;
2409 /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2410 /// critical path by more cycles than it takes to drain the instruction buffer.
2411 /// We estimate an upper bounds on in-flight instructions as:
2413 /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2414 /// InFlightIterations = AcyclicPath / CyclesPerIteration
2415 /// InFlightResources = InFlightIterations * LoopResources
2417 /// TODO: Check execution resources in addition to IssueCount.
2418 void GenericScheduler::checkAcyclicLatency() {
2419 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2422 // Scaled number of cycles per loop iteration.
2423 unsigned IterCount =
2424 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2426 // Scaled acyclic critical path.
2427 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2428 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2429 unsigned InFlightCount =
2430 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2431 unsigned BufferLimit =
2432 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2434 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2436 DEBUG(dbgs() << "IssueCycles="
2437 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2438 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2439 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2440 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2441 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2442 if (Rem.IsAcyclicLatencyLimited)
2443 dbgs() << " ACYCLIC LATENCY LIMIT\n");
2446 void GenericScheduler::registerRoots() {
2447 Rem.CriticalPath = DAG->ExitSU.getDepth();
2449 // Some roots may not feed into ExitSU. Check all of them in case.
2450 for (std::vector<SUnit*>::const_iterator
2451 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
2452 if ((*I)->getDepth() > Rem.CriticalPath)
2453 Rem.CriticalPath = (*I)->getDepth();
2455 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
2457 if (EnableCyclicPath) {
2458 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2459 checkAcyclicLatency();
2463 static bool tryPressure(const PressureChange &TryP,
2464 const PressureChange &CandP,
2465 GenericSchedulerBase::SchedCandidate &TryCand,
2466 GenericSchedulerBase::SchedCandidate &Cand,
2467 GenericSchedulerBase::CandReason Reason) {
2468 int TryRank = TryP.getPSetOrMax();
2469 int CandRank = CandP.getPSetOrMax();
2470 // If both candidates affect the same set, go with the smallest increase.
2471 if (TryRank == CandRank) {
2472 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2475 // If one candidate decreases and the other increases, go with it.
2476 // Invalid candidates have UnitInc==0.
2477 if (tryLess(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2481 // If the candidates are decreasing pressure, reverse priority.
2482 if (TryP.getUnitInc() < 0)
2483 std::swap(TryRank, CandRank);
2484 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2487 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2488 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2491 /// Minimize physical register live ranges. Regalloc wants them adjacent to
2492 /// their physreg def/use.
2494 /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2495 /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2496 /// with the operation that produces or consumes the physreg. We'll do this when
2497 /// regalloc has support for parallel copies.
2498 static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2499 const MachineInstr *MI = SU->getInstr();
2503 unsigned ScheduledOper = isTop ? 1 : 0;
2504 unsigned UnscheduledOper = isTop ? 0 : 1;
2505 // If we have already scheduled the physreg produce/consumer, immediately
2506 // schedule the copy.
2507 if (TargetRegisterInfo::isPhysicalRegister(
2508 MI->getOperand(ScheduledOper).getReg()))
2510 // If the physreg is at the boundary, defer it. Otherwise schedule it
2511 // immediately to free the dependent. We can hoist the copy later.
2512 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2513 if (TargetRegisterInfo::isPhysicalRegister(
2514 MI->getOperand(UnscheduledOper).getReg()))
2515 return AtBoundary ? -1 : 1;
2519 /// Apply a set of heursitics to a new candidate. Heuristics are currently
2520 /// hierarchical. This may be more efficient than a graduated cost model because
2521 /// we don't need to evaluate all aspects of the model for each node in the
2522 /// queue. But it's really done to make the heuristics easier to debug and
2523 /// statistically analyze.
2525 /// \param Cand provides the policy and current best candidate.
2526 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2527 /// \param Zone describes the scheduled zone that we are extending.
2528 /// \param RPTracker describes reg pressure within the scheduled zone.
2529 /// \param TempTracker is a scratch pressure tracker to reuse in queries.
2530 void GenericScheduler::tryCandidate(SchedCandidate &Cand,
2531 SchedCandidate &TryCand,
2532 SchedBoundary &Zone,
2533 const RegPressureTracker &RPTracker,
2534 RegPressureTracker &TempTracker) {
2536 if (DAG->isTrackingPressure()) {
2537 // Always initialize TryCand's RPDelta.
2539 TempTracker.getMaxDownwardPressureDelta(
2540 TryCand.SU->getInstr(),
2542 DAG->getRegionCriticalPSets(),
2543 DAG->getRegPressure().MaxSetPressure);
2546 if (VerifyScheduling) {
2547 TempTracker.getMaxUpwardPressureDelta(
2548 TryCand.SU->getInstr(),
2549 &DAG->getPressureDiff(TryCand.SU),
2551 DAG->getRegionCriticalPSets(),
2552 DAG->getRegPressure().MaxSetPressure);
2555 RPTracker.getUpwardPressureDelta(
2556 TryCand.SU->getInstr(),
2557 DAG->getPressureDiff(TryCand.SU),
2559 DAG->getRegionCriticalPSets(),
2560 DAG->getRegPressure().MaxSetPressure);
2564 DEBUG(if (TryCand.RPDelta.Excess.isValid())
2565 dbgs() << " SU(" << TryCand.SU->NodeNum << ") "
2566 << TRI->getRegPressureSetName(TryCand.RPDelta.Excess.getPSet())
2567 << ":" << TryCand.RPDelta.Excess.getUnitInc() << "\n");
2569 // Initialize the candidate if needed.
2570 if (!Cand.isValid()) {
2571 TryCand.Reason = NodeOrder;
2575 if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2576 biasPhysRegCopy(Cand.SU, Zone.isTop()),
2577 TryCand, Cand, PhysRegCopy))
2580 // Avoid exceeding the target's limit. If signed PSetID is negative, it is
2581 // invalid; convert it to INT_MAX to give it lowest priority.
2582 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2583 Cand.RPDelta.Excess,
2584 TryCand, Cand, RegExcess))
2587 // Avoid increasing the max critical pressure in the scheduled region.
2588 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2589 Cand.RPDelta.CriticalMax,
2590 TryCand, Cand, RegCritical))
2593 // For loops that are acyclic path limited, aggressively schedule for latency.
2594 // This can result in very long dependence chains scheduled in sequence, so
2595 // once every cycle (when CurrMOps == 0), switch to normal heuristics.
2596 if (Rem.IsAcyclicLatencyLimited && !Zone.getCurrMOps()
2597 && tryLatency(TryCand, Cand, Zone))
2600 // Prioritize instructions that read unbuffered resources by stall cycles.
2601 if (tryLess(Zone.getLatencyStallCycles(TryCand.SU),
2602 Zone.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2605 // Keep clustered nodes together to encourage downstream peephole
2606 // optimizations which may reduce resource requirements.
2608 // This is a best effort to set things up for a post-RA pass. Optimizations
2609 // like generating loads of multiple registers should ideally be done within
2610 // the scheduler pass by combining the loads during DAG postprocessing.
2611 const SUnit *NextClusterSU =
2612 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2613 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2614 TryCand, Cand, Cluster))
2617 // Weak edges are for clustering and other constraints.
2618 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2619 getWeakLeft(Cand.SU, Zone.isTop()),
2620 TryCand, Cand, Weak)) {
2623 // Avoid increasing the max pressure of the entire region.
2624 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2625 Cand.RPDelta.CurrentMax,
2626 TryCand, Cand, RegMax))
2629 // Avoid critical resource consumption and balance the schedule.
2630 TryCand.initResourceDelta(DAG, SchedModel);
2631 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2632 TryCand, Cand, ResourceReduce))
2634 if (tryGreater(TryCand.ResDelta.DemandedResources,
2635 Cand.ResDelta.DemandedResources,
2636 TryCand, Cand, ResourceDemand))
2639 // Avoid serializing long latency dependence chains.
2640 // For acyclic path limited loops, latency was already checked above.
2641 if (Cand.Policy.ReduceLatency && !Rem.IsAcyclicLatencyLimited
2642 && tryLatency(TryCand, Cand, Zone)) {
2646 // Prefer immediate defs/users of the last scheduled instruction. This is a
2647 // local pressure avoidance strategy that also makes the machine code
2649 if (tryGreater(Zone.isNextSU(TryCand.SU), Zone.isNextSU(Cand.SU),
2650 TryCand, Cand, NextDefUse))
2653 // Fall through to original instruction order.
2654 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2655 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2656 TryCand.Reason = NodeOrder;
2660 /// Pick the best candidate from the queue.
2662 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2663 /// DAG building. To adjust for the current scheduling location we need to
2664 /// maintain the number of vreg uses remaining to be top-scheduled.
2665 void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
2666 const RegPressureTracker &RPTracker,
2667 SchedCandidate &Cand) {
2668 ReadyQueue &Q = Zone.Available;
2672 // getMaxPressureDelta temporarily modifies the tracker.
2673 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2675 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
2677 SchedCandidate TryCand(Cand.Policy);
2679 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
2680 if (TryCand.Reason != NoCand) {
2681 // Initialize resource delta if needed in case future heuristics query it.
2682 if (TryCand.ResDelta == SchedResourceDelta())
2683 TryCand.initResourceDelta(DAG, SchedModel);
2684 Cand.setBest(TryCand);
2685 DEBUG(traceCandidate(Cand));
2690 /// Pick the best candidate node from either the top or bottom queue.
2691 SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
2692 // Schedule as far as possible in the direction of no choice. This is most
2693 // efficient, but also provides the best heuristics for CriticalPSets.
2694 if (SUnit *SU = Bot.pickOnlyChoice()) {
2696 DEBUG(dbgs() << "Pick Bot NOCAND\n");
2699 if (SUnit *SU = Top.pickOnlyChoice()) {
2701 DEBUG(dbgs() << "Pick Top NOCAND\n");
2704 CandPolicy NoPolicy;
2705 SchedCandidate BotCand(NoPolicy);
2706 SchedCandidate TopCand(NoPolicy);
2707 // Set the bottom-up policy based on the state of the current bottom zone and
2708 // the instructions outside the zone, including the top zone.
2709 setPolicy(BotCand.Policy, /*IsPostRA=*/false, Bot, &Top);
2710 // Set the top-down policy based on the state of the current top zone and
2711 // the instructions outside the zone, including the bottom zone.
2712 setPolicy(TopCand.Policy, /*IsPostRA=*/false, Top, &Bot);
2714 // Prefer bottom scheduling when heuristics are silent.
2715 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2716 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2718 // If either Q has a single candidate that provides the least increase in
2719 // Excess pressure, we can immediately schedule from that Q.
2721 // RegionCriticalPSets summarizes the pressure within the scheduled region and
2722 // affects picking from either Q. If scheduling in one direction must
2723 // increase pressure for one of the excess PSets, then schedule in that
2724 // direction first to provide more freedom in the other direction.
2725 if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
2726 || (BotCand.Reason == RegCritical
2727 && !BotCand.isRepeat(RegCritical)))
2730 tracePick(BotCand, IsTopNode);
2733 // Check if the top Q has a better candidate.
2734 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2735 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2737 // Choose the queue with the most important (lowest enum) reason.
2738 if (TopCand.Reason < BotCand.Reason) {
2740 tracePick(TopCand, IsTopNode);
2743 // Otherwise prefer the bottom candidate, in node order if all else failed.
2745 tracePick(BotCand, IsTopNode);
2749 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
2750 SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
2751 if (DAG->top() == DAG->bottom()) {
2752 assert(Top.Available.empty() && Top.Pending.empty() &&
2753 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
2758 if (RegionPolicy.OnlyTopDown) {
2759 SU = Top.pickOnlyChoice();
2761 CandPolicy NoPolicy;
2762 SchedCandidate TopCand(NoPolicy);
2763 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2764 assert(TopCand.Reason != NoCand && "failed to find a candidate");
2765 tracePick(TopCand, true);
2770 else if (RegionPolicy.OnlyBottomUp) {
2771 SU = Bot.pickOnlyChoice();
2773 CandPolicy NoPolicy;
2774 SchedCandidate BotCand(NoPolicy);
2775 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2776 assert(BotCand.Reason != NoCand && "failed to find a candidate");
2777 tracePick(BotCand, false);
2783 SU = pickNodeBidirectional(IsTopNode);
2785 } while (SU->isScheduled);
2787 if (SU->isTopReady())
2788 Top.removeReady(SU);
2789 if (SU->isBottomReady())
2790 Bot.removeReady(SU);
2792 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
2796 void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
2798 MachineBasicBlock::iterator InsertPos = SU->getInstr();
2801 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
2803 // Find already scheduled copies with a single physreg dependence and move
2804 // them just above the scheduled instruction.
2805 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
2807 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
2809 SUnit *DepSU = I->getSUnit();
2810 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
2812 MachineInstr *Copy = DepSU->getInstr();
2813 if (!Copy->isCopy())
2815 DEBUG(dbgs() << " Rescheduling physreg copy ";
2816 I->getSUnit()->dump(DAG));
2817 DAG->moveInstruction(Copy, InsertPos);
2821 /// Update the scheduler's state after scheduling a node. This is the same node
2822 /// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
2823 /// update it's state based on the current cycle before MachineSchedStrategy
2826 /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
2827 /// them here. See comments in biasPhysRegCopy.
2828 void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2830 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
2832 if (SU->hasPhysRegUses)
2833 reschedulePhysRegCopies(SU, true);
2836 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
2838 if (SU->hasPhysRegDefs)
2839 reschedulePhysRegCopies(SU, false);
2843 /// Create the standard converging machine scheduler. This will be used as the
2844 /// default scheduler if the target does not set a default.
2845 static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C) {
2846 ScheduleDAGMILive *DAG = new ScheduleDAGMILive(C, make_unique<GenericScheduler>(C));
2847 // Register DAG post-processors.
2849 // FIXME: extend the mutation API to allow earlier mutations to instantiate
2850 // data and pass it to later mutations. Have a single mutation that gathers
2851 // the interesting nodes in one pass.
2852 DAG->addMutation(make_unique<CopyConstrain>(DAG->TII, DAG->TRI));
2853 if (EnableLoadCluster && DAG->TII->enableClusterLoads())
2854 DAG->addMutation(make_unique<LoadClusterMutation>(DAG->TII, DAG->TRI));
2855 if (EnableMacroFusion)
2856 DAG->addMutation(make_unique<MacroFusion>(DAG->TII));
2860 static MachineSchedRegistry
2861 GenericSchedRegistry("converge", "Standard converging scheduler.",
2862 createGenericSchedLive);
2864 //===----------------------------------------------------------------------===//
2865 // PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
2866 //===----------------------------------------------------------------------===//
2868 void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
2870 SchedModel = DAG->getSchedModel();
2873 Rem.init(DAG, SchedModel);
2874 Top.init(DAG, SchedModel, &Rem);
2877 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
2878 // or are disabled, then these HazardRecs will be disabled.
2879 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
2880 const TargetMachine &TM = DAG->MF.getTarget();
2881 if (!Top.HazardRec) {
2883 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2888 void PostGenericScheduler::registerRoots() {
2889 Rem.CriticalPath = DAG->ExitSU.getDepth();
2891 // Some roots may not feed into ExitSU. Check all of them in case.
2892 for (SmallVectorImpl<SUnit*>::const_iterator
2893 I = BotRoots.begin(), E = BotRoots.end(); I != E; ++I) {
2894 if ((*I)->getDepth() > Rem.CriticalPath)
2895 Rem.CriticalPath = (*I)->getDepth();
2897 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
2900 /// Apply a set of heursitics to a new candidate for PostRA scheduling.
2902 /// \param Cand provides the policy and current best candidate.
2903 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2904 void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
2905 SchedCandidate &TryCand) {
2907 // Initialize the candidate if needed.
2908 if (!Cand.isValid()) {
2909 TryCand.Reason = NodeOrder;
2913 // Prioritize instructions that read unbuffered resources by stall cycles.
2914 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
2915 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2918 // Avoid critical resource consumption and balance the schedule.
2919 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2920 TryCand, Cand, ResourceReduce))
2922 if (tryGreater(TryCand.ResDelta.DemandedResources,
2923 Cand.ResDelta.DemandedResources,
2924 TryCand, Cand, ResourceDemand))
2927 // Avoid serializing long latency dependence chains.
2928 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
2932 // Fall through to original instruction order.
2933 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
2934 TryCand.Reason = NodeOrder;
2937 void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
2938 ReadyQueue &Q = Top.Available;
2942 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
2943 SchedCandidate TryCand(Cand.Policy);
2945 TryCand.initResourceDelta(DAG, SchedModel);
2946 tryCandidate(Cand, TryCand);
2947 if (TryCand.Reason != NoCand) {
2948 Cand.setBest(TryCand);
2949 DEBUG(traceCandidate(Cand));
2954 /// Pick the next node to schedule.
2955 SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
2956 if (DAG->top() == DAG->bottom()) {
2957 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
2962 SU = Top.pickOnlyChoice();
2964 CandPolicy NoPolicy;
2965 SchedCandidate TopCand(NoPolicy);
2966 // Set the top-down policy based on the state of the current top zone and
2967 // the instructions outside the zone, including the bottom zone.
2968 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
2969 pickNodeFromQueue(TopCand);
2970 assert(TopCand.Reason != NoCand && "failed to find a candidate");
2971 tracePick(TopCand, true);
2974 } while (SU->isScheduled);
2977 Top.removeReady(SU);
2979 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
2983 /// Called after ScheduleDAGMI has scheduled an instruction and updated
2984 /// scheduled/remaining flags in the DAG nodes.
2985 void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2986 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
2990 /// Create a generic scheduler with no vreg liveness or DAG mutation passes.
2991 static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C) {
2992 return new ScheduleDAGMI(C, make_unique<PostGenericScheduler>(C), /*IsPostRA=*/true);
2995 //===----------------------------------------------------------------------===//
2996 // ILP Scheduler. Currently for experimental analysis of heuristics.
2997 //===----------------------------------------------------------------------===//
3000 /// \brief Order nodes by the ILP metric.
3002 const SchedDFSResult *DFSResult;
3003 const BitVector *ScheduledTrees;
3006 ILPOrder(bool MaxILP)
3007 : DFSResult(nullptr), ScheduledTrees(nullptr), MaximizeILP(MaxILP) {}
3009 /// \brief Apply a less-than relation on node priority.
3011 /// (Return true if A comes after B in the Q.)
3012 bool operator()(const SUnit *A, const SUnit *B) const {
3013 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3014 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3015 if (SchedTreeA != SchedTreeB) {
3016 // Unscheduled trees have lower priority.
3017 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3018 return ScheduledTrees->test(SchedTreeB);
3020 // Trees with shallower connections have have lower priority.
3021 if (DFSResult->getSubtreeLevel(SchedTreeA)
3022 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3023 return DFSResult->getSubtreeLevel(SchedTreeA)
3024 < DFSResult->getSubtreeLevel(SchedTreeB);
3028 return DFSResult->getILP(A) < DFSResult->getILP(B);
3030 return DFSResult->getILP(A) > DFSResult->getILP(B);
3034 /// \brief Schedule based on the ILP metric.
3035 class ILPScheduler : public MachineSchedStrategy {
3036 ScheduleDAGMILive *DAG;
3039 std::vector<SUnit*> ReadyQ;
3041 ILPScheduler(bool MaximizeILP): DAG(nullptr), Cmp(MaximizeILP) {}
3043 void initialize(ScheduleDAGMI *dag) override {
3044 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3045 DAG = static_cast<ScheduleDAGMILive*>(dag);
3046 DAG->computeDFSResult();
3047 Cmp.DFSResult = DAG->getDFSResult();
3048 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
3052 void registerRoots() override {
3053 // Restore the heap in ReadyQ with the updated DFS results.
3054 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3057 /// Implement MachineSchedStrategy interface.
3058 /// -----------------------------------------
3060 /// Callback to select the highest priority node from the ready Q.
3061 SUnit *pickNode(bool &IsTopNode) override {
3062 if (ReadyQ.empty()) return nullptr;
3063 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3064 SUnit *SU = ReadyQ.back();
3067 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
3068 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3069 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3070 << DAG->getDFSResult()->getSubtreeLevel(
3071 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3072 << "Scheduling " << *SU->getInstr());
3076 /// \brief Scheduler callback to notify that a new subtree is scheduled.
3077 void scheduleTree(unsigned SubtreeID) override {
3078 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3081 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3082 /// DFSResults, and resort the priority Q.
3083 void schedNode(SUnit *SU, bool IsTopNode) override {
3084 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
3087 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
3089 void releaseBottomNode(SUnit *SU) override {
3090 ReadyQ.push_back(SU);
3091 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3096 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
3097 return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(true));
3099 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
3100 return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(false));
3102 static MachineSchedRegistry ILPMaxRegistry(
3103 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3104 static MachineSchedRegistry ILPMinRegistry(
3105 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3107 //===----------------------------------------------------------------------===//
3108 // Machine Instruction Shuffler for Correctness Testing
3109 //===----------------------------------------------------------------------===//
3113 /// Apply a less-than relation on the node order, which corresponds to the
3114 /// instruction order prior to scheduling. IsReverse implements greater-than.
3115 template<bool IsReverse>
3117 bool operator()(SUnit *A, SUnit *B) const {
3119 return A->NodeNum > B->NodeNum;
3121 return A->NodeNum < B->NodeNum;
3125 /// Reorder instructions as much as possible.
3126 class InstructionShuffler : public MachineSchedStrategy {
3130 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3131 // gives nodes with a higher number higher priority causing the latest
3132 // instructions to be scheduled first.
3133 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
3135 // When scheduling bottom-up, use greater-than as the queue priority.
3136 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
3139 InstructionShuffler(bool alternate, bool topdown)
3140 : IsAlternating(alternate), IsTopDown(topdown) {}
3142 void initialize(ScheduleDAGMI*) override {
3147 /// Implement MachineSchedStrategy interface.
3148 /// -----------------------------------------
3150 SUnit *pickNode(bool &IsTopNode) override {
3154 if (TopQ.empty()) return nullptr;
3157 } while (SU->isScheduled);
3162 if (BottomQ.empty()) return nullptr;
3165 } while (SU->isScheduled);
3169 IsTopDown = !IsTopDown;
3173 void schedNode(SUnit *SU, bool IsTopNode) override {}
3175 void releaseTopNode(SUnit *SU) override {
3178 void releaseBottomNode(SUnit *SU) override {
3184 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
3185 bool Alternate = !ForceTopDown && !ForceBottomUp;
3186 bool TopDown = !ForceBottomUp;
3187 assert((TopDown || !ForceTopDown) &&
3188 "-misched-topdown incompatible with -misched-bottomup");
3189 return new ScheduleDAGMILive(C, make_unique<InstructionShuffler>(Alternate, TopDown));
3191 static MachineSchedRegistry ShufflerRegistry(
3192 "shuffle", "Shuffle machine instructions alternating directions",
3193 createInstructionShuffler);
3196 //===----------------------------------------------------------------------===//
3197 // GraphWriter support for ScheduleDAGMILive.
3198 //===----------------------------------------------------------------------===//
3203 template<> struct GraphTraits<
3204 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3207 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
3209 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3211 static std::string getGraphName(const ScheduleDAG *G) {
3212 return G->MF.getName();
3215 static bool renderGraphFromBottomUp() {
3219 static bool isNodeHidden(const SUnit *Node) {
3220 return (Node->Preds.size() > 10 || Node->Succs.size() > 10);
3223 static bool hasNodeAddressLabel(const SUnit *Node,
3224 const ScheduleDAG *Graph) {
3228 /// If you want to override the dot attributes printed for a particular
3229 /// edge, override this method.
3230 static std::string getEdgeAttributes(const SUnit *Node,
3232 const ScheduleDAG *Graph) {
3233 if (EI.isArtificialDep())
3234 return "color=cyan,style=dashed";
3236 return "color=blue,style=dashed";
3240 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
3242 raw_string_ostream SS(Str);
3243 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3244 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3245 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
3246 SS << "SU:" << SU->NodeNum;
3248 SS << " I:" << DFS->getNumInstrs(SU);
3251 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3252 return G->getGraphNodeLabel(SU);
3255 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
3256 std::string Str("shape=Mrecord");
3257 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3258 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3259 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
3261 Str += ",style=filled,fillcolor=\"#";
3262 Str += DOT::getColorString(DFS->getSubtreeID(N));
3271 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3272 /// rendered using 'dot'.
3274 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3276 ViewGraph(this, Name, false, Title);
3278 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3279 << "systems with Graphviz or gv!\n";
3283 /// Out-of-line implementation with no arguments is handy for gdb.
3284 void ScheduleDAGMI::viewGraph() {
3285 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());