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 #define DEBUG_TYPE "misched"
17 #include "llvm/CodeGen/MachineScheduler.h"
18 #include "llvm/ADT/PriorityQueue.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/MachineDominators.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegisterClassInfo.h"
26 #include "llvm/CodeGen/ScheduleDFS.h"
27 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/GraphWriter.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetInstrInfo.h"
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(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
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* = 0) 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 DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
335 // Initialize the context of the pass.
337 PassConfig = &getAnalysis<TargetPassConfig>();
339 if (VerifyScheduling)
340 MF->verify(this, "Before post machine scheduling.");
342 // Instantiate the selected scheduler for this target, function, and
343 // optimization level.
344 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
345 scheduleRegions(*Scheduler);
347 if (VerifyScheduling)
348 MF->verify(this, "After post machine scheduling.");
352 /// Return true of the given instruction should not be included in a scheduling
355 /// MachineScheduler does not currently support scheduling across calls. To
356 /// handle calls, the DAG builder needs to be modified to create register
357 /// anti/output dependencies on the registers clobbered by the call's regmask
358 /// operand. In PreRA scheduling, the stack pointer adjustment already prevents
359 /// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
360 /// the boundary, but there would be no benefit to postRA scheduling across
361 /// calls this late anyway.
362 static bool isSchedBoundary(MachineBasicBlock::iterator MI,
363 MachineBasicBlock *MBB,
365 const TargetInstrInfo *TII,
367 return MI->isCall() || TII->isSchedulingBoundary(MI, MBB, *MF);
370 /// Main driver for both MachineScheduler and PostMachineScheduler.
371 void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler) {
372 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
373 bool IsPostRA = Scheduler.isPostRA();
375 // Visit all machine basic blocks.
377 // TODO: Visit blocks in global postorder or postorder within the bottom-up
378 // loop tree. Then we can optionally compute global RegPressure.
379 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
380 MBB != MBBEnd; ++MBB) {
382 Scheduler.startBlock(MBB);
385 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
387 if (SchedOnlyBlock.getNumOccurrences()
388 && (int)SchedOnlyBlock != MBB->getNumber())
392 // Break the block into scheduling regions [I, RegionEnd), and schedule each
393 // region as soon as it is discovered. RegionEnd points the scheduling
394 // boundary at the bottom of the region. The DAG does not include RegionEnd,
395 // but the region does (i.e. the next RegionEnd is above the previous
396 // RegionBegin). If the current block has no terminator then RegionEnd ==
397 // MBB->end() for the bottom region.
399 // The Scheduler may insert instructions during either schedule() or
400 // exitRegion(), even for empty regions. So the local iterators 'I' and
401 // 'RegionEnd' are invalid across these calls.
403 // MBB::size() uses instr_iterator to count. Here we need a bundle to count
404 // as a single instruction.
405 unsigned RemainingInstrs = std::distance(MBB->begin(), MBB->end());
406 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
407 RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
409 // Avoid decrementing RegionEnd for blocks with no terminator.
410 if (RegionEnd != MBB->end() ||
411 isSchedBoundary(std::prev(RegionEnd), MBB, MF, TII, IsPostRA)) {
413 // Count the boundary instruction.
417 // The next region starts above the previous region. Look backward in the
418 // instruction stream until we find the nearest boundary.
419 unsigned NumRegionInstrs = 0;
420 MachineBasicBlock::iterator I = RegionEnd;
421 for(;I != MBB->begin(); --I, --RemainingInstrs, ++NumRegionInstrs) {
422 if (isSchedBoundary(std::prev(I), MBB, MF, TII, IsPostRA))
425 // Notify the scheduler of the region, even if we may skip scheduling
426 // it. Perhaps it still needs to be bundled.
427 Scheduler.enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
429 // Skip empty scheduling regions (0 or 1 schedulable instructions).
430 if (I == RegionEnd || I == std::prev(RegionEnd)) {
431 // Close the current region. Bundle the terminator if needed.
432 // This invalidates 'RegionEnd' and 'I'.
433 Scheduler.exitRegion();
436 DEBUG(dbgs() << "********** " << ((Scheduler.isPostRA()) ? "PostRA " : "")
437 << "MI Scheduling **********\n");
438 DEBUG(dbgs() << MF->getName()
439 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
440 << "\n From: " << *I << " To: ";
441 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
442 else dbgs() << "End";
443 dbgs() << " RegionInstrs: " << NumRegionInstrs
444 << " Remaining: " << RemainingInstrs << "\n");
446 // Schedule a region: possibly reorder instructions.
447 // This invalidates 'RegionEnd' and 'I'.
448 Scheduler.schedule();
450 // Close the current region.
451 Scheduler.exitRegion();
453 // Scheduling has invalidated the current iterator 'I'. Ask the
454 // scheduler for the top of it's scheduled region.
455 RegionEnd = Scheduler.begin();
457 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
458 Scheduler.finishBlock();
459 if (Scheduler.isPostRA()) {
460 // FIXME: Ideally, no further passes should rely on kill flags. However,
461 // thumb2 size reduction is currently an exception.
462 Scheduler.fixupKills(MBB);
465 Scheduler.finalizeSchedule();
468 void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
472 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
473 void ReadyQueue::dump() {
474 dbgs() << Name << ": ";
475 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
476 dbgs() << Queue[i]->NodeNum << " ";
481 //===----------------------------------------------------------------------===//
482 // ScheduleDAGMI - Basic machine instruction scheduling. This is
483 // independent of PreRA/PostRA scheduling and involves no extra book-keeping for
484 // virtual registers.
485 // ===----------------------------------------------------------------------===/
487 ScheduleDAGMI::~ScheduleDAGMI() {
488 DeleteContainerPointers(Mutations);
492 bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
493 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
496 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
497 if (SuccSU != &ExitSU) {
498 // Do not use WillCreateCycle, it assumes SD scheduling.
499 // If Pred is reachable from Succ, then the edge creates a cycle.
500 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
502 Topo.AddPred(SuccSU, PredDep.getSUnit());
504 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
505 // Return true regardless of whether a new edge needed to be inserted.
509 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
510 /// NumPredsLeft reaches zero, release the successor node.
512 /// FIXME: Adjust SuccSU height based on MinLatency.
513 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
514 SUnit *SuccSU = SuccEdge->getSUnit();
516 if (SuccEdge->isWeak()) {
517 --SuccSU->WeakPredsLeft;
518 if (SuccEdge->isCluster())
519 NextClusterSucc = SuccSU;
523 if (SuccSU->NumPredsLeft == 0) {
524 dbgs() << "*** Scheduling failed! ***\n";
526 dbgs() << " has been released too many times!\n";
530 --SuccSU->NumPredsLeft;
531 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
532 SchedImpl->releaseTopNode(SuccSU);
535 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
536 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
537 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
539 releaseSucc(SU, &*I);
543 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
544 /// NumSuccsLeft reaches zero, release the predecessor node.
546 /// FIXME: Adjust PredSU height based on MinLatency.
547 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
548 SUnit *PredSU = PredEdge->getSUnit();
550 if (PredEdge->isWeak()) {
551 --PredSU->WeakSuccsLeft;
552 if (PredEdge->isCluster())
553 NextClusterPred = PredSU;
557 if (PredSU->NumSuccsLeft == 0) {
558 dbgs() << "*** Scheduling failed! ***\n";
560 dbgs() << " has been released too many times!\n";
564 --PredSU->NumSuccsLeft;
565 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
566 SchedImpl->releaseBottomNode(PredSU);
569 /// releasePredecessors - Call releasePred on each of SU's predecessors.
570 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
571 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
573 releasePred(SU, &*I);
577 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
578 /// crossing a scheduling boundary. [begin, end) includes all instructions in
579 /// the region, including the boundary itself and single-instruction regions
580 /// that don't get scheduled.
581 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
582 MachineBasicBlock::iterator begin,
583 MachineBasicBlock::iterator end,
584 unsigned regioninstrs)
586 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
588 SchedImpl->initPolicy(begin, end, regioninstrs);
591 /// This is normally called from the main scheduler loop but may also be invoked
592 /// by the scheduling strategy to perform additional code motion.
593 void ScheduleDAGMI::moveInstruction(
594 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
595 // Advance RegionBegin if the first instruction moves down.
596 if (&*RegionBegin == MI)
599 // Update the instruction stream.
600 BB->splice(InsertPos, BB, MI);
602 // Update LiveIntervals
604 LIS->handleMove(MI, /*UpdateFlags=*/true);
606 // Recede RegionBegin if an instruction moves above the first.
607 if (RegionBegin == InsertPos)
611 bool ScheduleDAGMI::checkSchedLimit() {
613 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
614 CurrentTop = CurrentBottom;
617 ++NumInstrsScheduled;
622 /// Per-region scheduling driver, called back from
623 /// MachineScheduler::runOnMachineFunction. This is a simplified driver that
624 /// does not consider liveness or register pressure. It is useful for PostRA
625 /// scheduling and potentially other custom schedulers.
626 void ScheduleDAGMI::schedule() {
630 Topo.InitDAGTopologicalSorting();
634 SmallVector<SUnit*, 8> TopRoots, BotRoots;
635 findRootsAndBiasEdges(TopRoots, BotRoots);
637 // Initialize the strategy before modifying the DAG.
638 // This may initialize a DFSResult to be used for queue priority.
639 SchedImpl->initialize(this);
641 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
642 SUnits[su].dumpAll(this));
643 if (ViewMISchedDAGs) viewGraph();
645 // Initialize ready queues now that the DAG and priority data are finalized.
646 initQueues(TopRoots, BotRoots);
648 bool IsTopNode = false;
649 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
650 assert(!SU->isScheduled && "Node already scheduled");
651 if (!checkSchedLimit())
654 MachineInstr *MI = SU->getInstr();
656 assert(SU->isTopReady() && "node still has unscheduled dependencies");
657 if (&*CurrentTop == MI)
658 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
660 moveInstruction(MI, CurrentTop);
663 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
664 MachineBasicBlock::iterator priorII =
665 priorNonDebug(CurrentBottom, CurrentTop);
667 CurrentBottom = priorII;
669 if (&*CurrentTop == MI)
670 CurrentTop = nextIfDebug(++CurrentTop, priorII);
671 moveInstruction(MI, CurrentBottom);
675 updateQueues(SU, IsTopNode);
677 // Notify the scheduling strategy after updating the DAG.
678 SchedImpl->schedNode(SU, IsTopNode);
680 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
685 unsigned BBNum = begin()->getParent()->getNumber();
686 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
692 /// Apply each ScheduleDAGMutation step in order.
693 void ScheduleDAGMI::postprocessDAG() {
694 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
695 Mutations[i]->apply(this);
700 findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
701 SmallVectorImpl<SUnit*> &BotRoots) {
702 for (std::vector<SUnit>::iterator
703 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
705 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
707 // Order predecessors so DFSResult follows the critical path.
708 SU->biasCriticalPath();
710 // A SUnit is ready to top schedule if it has no predecessors.
711 if (!I->NumPredsLeft)
712 TopRoots.push_back(SU);
713 // A SUnit is ready to bottom schedule if it has no successors.
714 if (!I->NumSuccsLeft)
715 BotRoots.push_back(SU);
717 ExitSU.biasCriticalPath();
720 /// Identify DAG roots and setup scheduler queues.
721 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
722 ArrayRef<SUnit*> BotRoots) {
723 NextClusterSucc = NULL;
724 NextClusterPred = NULL;
726 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
728 // Nodes with unreleased weak edges can still be roots.
729 // Release top roots in forward order.
730 for (SmallVectorImpl<SUnit*>::const_iterator
731 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
732 SchedImpl->releaseTopNode(*I);
734 // Release bottom roots in reverse order so the higher priority nodes appear
735 // first. This is more natural and slightly more efficient.
736 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
737 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
738 SchedImpl->releaseBottomNode(*I);
741 releaseSuccessors(&EntrySU);
742 releasePredecessors(&ExitSU);
744 SchedImpl->registerRoots();
746 // Advance past initial DebugValues.
747 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
748 CurrentBottom = RegionEnd;
751 /// Update scheduler queues after scheduling an instruction.
752 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
753 // Release dependent instructions for scheduling.
755 releaseSuccessors(SU);
757 releasePredecessors(SU);
759 SU->isScheduled = true;
762 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
763 void ScheduleDAGMI::placeDebugValues() {
764 // If first instruction was a DBG_VALUE then put it back.
766 BB->splice(RegionBegin, BB, FirstDbgValue);
767 RegionBegin = FirstDbgValue;
770 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
771 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
772 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
773 MachineInstr *DbgValue = P.first;
774 MachineBasicBlock::iterator OrigPrevMI = P.second;
775 if (&*RegionBegin == DbgValue)
777 BB->splice(++OrigPrevMI, BB, DbgValue);
778 if (OrigPrevMI == std::prev(RegionEnd))
779 RegionEnd = DbgValue;
782 FirstDbgValue = NULL;
785 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
786 void ScheduleDAGMI::dumpSchedule() const {
787 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
788 if (SUnit *SU = getSUnit(&(*MI)))
791 dbgs() << "Missing SUnit\n";
796 //===----------------------------------------------------------------------===//
797 // ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
799 //===----------------------------------------------------------------------===//
801 ScheduleDAGMILive::~ScheduleDAGMILive() {
805 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
806 /// crossing a scheduling boundary. [begin, end) includes all instructions in
807 /// the region, including the boundary itself and single-instruction regions
808 /// that don't get scheduled.
809 void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
810 MachineBasicBlock::iterator begin,
811 MachineBasicBlock::iterator end,
812 unsigned regioninstrs)
814 // ScheduleDAGMI initializes SchedImpl's per-region policy.
815 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
817 // For convenience remember the end of the liveness region.
818 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
820 SUPressureDiffs.clear();
822 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
825 // Setup the register pressure trackers for the top scheduled top and bottom
826 // scheduled regions.
827 void ScheduleDAGMILive::initRegPressure() {
828 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
829 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
831 // Close the RPTracker to finalize live ins.
832 RPTracker.closeRegion();
834 DEBUG(RPTracker.dump());
836 // Initialize the live ins and live outs.
837 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
838 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
840 // Close one end of the tracker so we can call
841 // getMaxUpward/DownwardPressureDelta before advancing across any
842 // instructions. This converts currently live regs into live ins/outs.
843 TopRPTracker.closeTop();
844 BotRPTracker.closeBottom();
846 BotRPTracker.initLiveThru(RPTracker);
847 if (!BotRPTracker.getLiveThru().empty()) {
848 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
849 DEBUG(dbgs() << "Live Thru: ";
850 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
853 // For each live out vreg reduce the pressure change associated with other
854 // uses of the same vreg below the live-out reaching def.
855 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
857 // Account for liveness generated by the region boundary.
858 if (LiveRegionEnd != RegionEnd) {
859 SmallVector<unsigned, 8> LiveUses;
860 BotRPTracker.recede(&LiveUses);
861 updatePressureDiffs(LiveUses);
864 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
866 // Cache the list of excess pressure sets in this region. This will also track
867 // the max pressure in the scheduled code for these sets.
868 RegionCriticalPSets.clear();
869 const std::vector<unsigned> &RegionPressure =
870 RPTracker.getPressure().MaxSetPressure;
871 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
872 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
873 if (RegionPressure[i] > Limit) {
874 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
875 << " Limit " << Limit
876 << " Actual " << RegionPressure[i] << "\n");
877 RegionCriticalPSets.push_back(PressureChange(i));
880 DEBUG(dbgs() << "Excess PSets: ";
881 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
882 dbgs() << TRI->getRegPressureSetName(
883 RegionCriticalPSets[i].getPSet()) << " ";
887 void ScheduleDAGMILive::
888 updateScheduledPressure(const SUnit *SU,
889 const std::vector<unsigned> &NewMaxPressure) {
890 const PressureDiff &PDiff = getPressureDiff(SU);
891 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
892 for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
896 unsigned ID = I->getPSet();
897 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
899 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
900 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
901 && NewMaxPressure[ID] <= INT16_MAX)
902 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
904 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
905 if (NewMaxPressure[ID] >= Limit - 2) {
906 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
907 << NewMaxPressure[ID] << " > " << Limit << "(+ "
908 << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
913 /// Update the PressureDiff array for liveness after scheduling this
915 void ScheduleDAGMILive::updatePressureDiffs(ArrayRef<unsigned> LiveUses) {
916 for (unsigned LUIdx = 0, LUEnd = LiveUses.size(); LUIdx != LUEnd; ++LUIdx) {
917 /// FIXME: Currently assuming single-use physregs.
918 unsigned Reg = LiveUses[LUIdx];
919 DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
920 if (!TRI->isVirtualRegister(Reg))
923 // This may be called before CurrentBottom has been initialized. However,
924 // BotRPTracker must have a valid position. We want the value live into the
925 // instruction or live out of the block, so ask for the previous
926 // instruction's live-out.
927 const LiveInterval &LI = LIS->getInterval(Reg);
929 MachineBasicBlock::const_iterator I =
930 nextIfDebug(BotRPTracker.getPos(), BB->end());
932 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
934 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(I));
937 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
938 assert(VNI && "No live value at use.");
939 for (VReg2UseMap::iterator
940 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
942 DEBUG(dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
944 // If this use comes before the reaching def, it cannot be a last use, so
945 // descrease its pressure change.
946 if (!SU->isScheduled && SU != &ExitSU) {
948 = LI.Query(LIS->getInstructionIndex(SU->getInstr()));
949 if (LRQ.valueIn() == VNI)
950 getPressureDiff(SU).addPressureChange(Reg, true, &MRI);
956 /// schedule - Called back from MachineScheduler::runOnMachineFunction
957 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
958 /// only includes instructions that have DAG nodes, not scheduling boundaries.
960 /// This is a skeletal driver, with all the functionality pushed into helpers,
961 /// so that it can be easilly extended by experimental schedulers. Generally,
962 /// implementing MachineSchedStrategy should be sufficient to implement a new
963 /// scheduling algorithm. However, if a scheduler further subclasses
964 /// ScheduleDAGMILive then it will want to override this virtual method in order
965 /// to update any specialized state.
966 void ScheduleDAGMILive::schedule() {
967 buildDAGWithRegPressure();
969 Topo.InitDAGTopologicalSorting();
973 SmallVector<SUnit*, 8> TopRoots, BotRoots;
974 findRootsAndBiasEdges(TopRoots, BotRoots);
976 // Initialize the strategy before modifying the DAG.
977 // This may initialize a DFSResult to be used for queue priority.
978 SchedImpl->initialize(this);
980 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
981 SUnits[su].dumpAll(this));
982 if (ViewMISchedDAGs) viewGraph();
984 // Initialize ready queues now that the DAG and priority data are finalized.
985 initQueues(TopRoots, BotRoots);
987 if (ShouldTrackPressure) {
988 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
989 TopRPTracker.setPos(CurrentTop);
992 bool IsTopNode = false;
993 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
994 assert(!SU->isScheduled && "Node already scheduled");
995 if (!checkSchedLimit())
998 scheduleMI(SU, IsTopNode);
1000 updateQueues(SU, IsTopNode);
1003 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1004 if (!ScheduledTrees.test(SubtreeID)) {
1005 ScheduledTrees.set(SubtreeID);
1006 DFSResult->scheduleTree(SubtreeID);
1007 SchedImpl->scheduleTree(SubtreeID);
1011 // Notify the scheduling strategy after updating the DAG.
1012 SchedImpl->schedNode(SU, IsTopNode);
1014 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1019 unsigned BBNum = begin()->getParent()->getNumber();
1020 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1026 /// Build the DAG and setup three register pressure trackers.
1027 void ScheduleDAGMILive::buildDAGWithRegPressure() {
1028 if (!ShouldTrackPressure) {
1030 RegionCriticalPSets.clear();
1031 buildSchedGraph(AA);
1035 // Initialize the register pressure tracker used by buildSchedGraph.
1036 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1037 /*TrackUntiedDefs=*/true);
1039 // Account for liveness generate by the region boundary.
1040 if (LiveRegionEnd != RegionEnd)
1043 // Build the DAG, and compute current register pressure.
1044 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs);
1046 // Initialize top/bottom trackers after computing region pressure.
1050 void ScheduleDAGMILive::computeDFSResult() {
1052 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1054 ScheduledTrees.clear();
1055 DFSResult->resize(SUnits.size());
1056 DFSResult->compute(SUnits);
1057 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1060 /// Compute the max cyclic critical path through the DAG. The scheduling DAG
1061 /// only provides the critical path for single block loops. To handle loops that
1062 /// span blocks, we could use the vreg path latencies provided by
1063 /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1064 /// available for use in the scheduler.
1066 /// The cyclic path estimation identifies a def-use pair that crosses the back
1067 /// edge and considers the depth and height of the nodes. For example, consider
1068 /// the following instruction sequence where each instruction has unit latency
1069 /// and defines an epomymous virtual register:
1071 /// a->b(a,c)->c(b)->d(c)->exit
1073 /// The cyclic critical path is a two cycles: b->c->b
1074 /// The acyclic critical path is four cycles: a->b->c->d->exit
1075 /// LiveOutHeight = height(c) = len(c->d->exit) = 2
1076 /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1077 /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1078 /// LiveInDepth = depth(b) = len(a->b) = 1
1080 /// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1081 /// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1082 /// CyclicCriticalPath = min(2, 2) = 2
1084 /// This could be relevant to PostRA scheduling, but is currently implemented
1085 /// assuming LiveIntervals.
1086 unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
1087 // This only applies to single block loop.
1088 if (!BB->isSuccessor(BB))
1091 unsigned MaxCyclicLatency = 0;
1092 // Visit each live out vreg def to find def/use pairs that cross iterations.
1093 ArrayRef<unsigned> LiveOuts = RPTracker.getPressure().LiveOutRegs;
1094 for (ArrayRef<unsigned>::iterator RI = LiveOuts.begin(), RE = LiveOuts.end();
1097 if (!TRI->isVirtualRegister(Reg))
1099 const LiveInterval &LI = LIS->getInterval(Reg);
1100 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1104 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1105 const SUnit *DefSU = getSUnit(DefMI);
1109 unsigned LiveOutHeight = DefSU->getHeight();
1110 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1111 // Visit all local users of the vreg def.
1112 for (VReg2UseMap::iterator
1113 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
1114 if (UI->SU == &ExitSU)
1117 // Only consider uses of the phi.
1118 LiveQueryResult LRQ =
1119 LI.Query(LIS->getInstructionIndex(UI->SU->getInstr()));
1120 if (!LRQ.valueIn()->isPHIDef())
1123 // Assume that a path spanning two iterations is a cycle, which could
1124 // overestimate in strange cases. This allows cyclic latency to be
1125 // estimated as the minimum slack of the vreg's depth or height.
1126 unsigned CyclicLatency = 0;
1127 if (LiveOutDepth > UI->SU->getDepth())
1128 CyclicLatency = LiveOutDepth - UI->SU->getDepth();
1130 unsigned LiveInHeight = UI->SU->getHeight() + DefSU->Latency;
1131 if (LiveInHeight > LiveOutHeight) {
1132 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1133 CyclicLatency = LiveInHeight - LiveOutHeight;
1138 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1139 << UI->SU->NodeNum << ") = " << CyclicLatency << "c\n");
1140 if (CyclicLatency > MaxCyclicLatency)
1141 MaxCyclicLatency = CyclicLatency;
1144 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1145 return MaxCyclicLatency;
1148 /// Move an instruction and update register pressure.
1149 void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
1150 // Move the instruction to its new location in the instruction stream.
1151 MachineInstr *MI = SU->getInstr();
1154 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1155 if (&*CurrentTop == MI)
1156 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
1158 moveInstruction(MI, CurrentTop);
1159 TopRPTracker.setPos(MI);
1162 if (ShouldTrackPressure) {
1163 // Update top scheduled pressure.
1164 TopRPTracker.advance();
1165 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
1166 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
1170 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1171 MachineBasicBlock::iterator priorII =
1172 priorNonDebug(CurrentBottom, CurrentTop);
1173 if (&*priorII == MI)
1174 CurrentBottom = priorII;
1176 if (&*CurrentTop == MI) {
1177 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1178 TopRPTracker.setPos(CurrentTop);
1180 moveInstruction(MI, CurrentBottom);
1183 if (ShouldTrackPressure) {
1184 // Update bottom scheduled pressure.
1185 SmallVector<unsigned, 8> LiveUses;
1186 BotRPTracker.recede(&LiveUses);
1187 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
1188 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
1189 updatePressureDiffs(LiveUses);
1194 //===----------------------------------------------------------------------===//
1195 // LoadClusterMutation - DAG post-processing to cluster loads.
1196 //===----------------------------------------------------------------------===//
1199 /// \brief Post-process the DAG to create cluster edges between neighboring
1201 class LoadClusterMutation : public ScheduleDAGMutation {
1206 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
1207 : SU(su), BaseReg(reg), Offset(ofs) {}
1209 bool operator<(const LoadInfo &RHS) const {
1210 return std::tie(BaseReg, Offset) < std::tie(RHS.BaseReg, RHS.Offset);
1214 const TargetInstrInfo *TII;
1215 const TargetRegisterInfo *TRI;
1217 LoadClusterMutation(const TargetInstrInfo *tii,
1218 const TargetRegisterInfo *tri)
1219 : TII(tii), TRI(tri) {}
1221 void apply(ScheduleDAGMI *DAG) override;
1223 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
1227 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
1228 ScheduleDAGMI *DAG) {
1229 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
1230 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
1231 SUnit *SU = Loads[Idx];
1234 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
1235 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
1237 if (LoadRecords.size() < 2)
1239 std::sort(LoadRecords.begin(), LoadRecords.end());
1240 unsigned ClusterLength = 1;
1241 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
1242 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
1247 SUnit *SUa = LoadRecords[Idx].SU;
1248 SUnit *SUb = LoadRecords[Idx+1].SU;
1249 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
1250 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
1252 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
1253 << SUb->NodeNum << ")\n");
1254 // Copy successor edges from SUa to SUb. Interleaving computation
1255 // dependent on SUa can prevent load combining due to register reuse.
1256 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1257 // loads should have effectively the same inputs.
1258 for (SUnit::const_succ_iterator
1259 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
1260 if (SI->getSUnit() == SUb)
1262 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
1263 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
1272 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
1273 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
1274 // Map DAG NodeNum to store chain ID.
1275 DenseMap<unsigned, unsigned> StoreChainIDs;
1276 // Map each store chain to a set of dependent loads.
1277 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1278 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1279 SUnit *SU = &DAG->SUnits[Idx];
1280 if (!SU->getInstr()->mayLoad())
1282 unsigned ChainPredID = DAG->SUnits.size();
1283 for (SUnit::const_pred_iterator
1284 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1286 ChainPredID = PI->getSUnit()->NodeNum;
1290 // Check if this chain-like pred has been seen
1291 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
1292 unsigned NumChains = StoreChainDependents.size();
1293 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1294 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1296 StoreChainDependents.resize(NumChains + 1);
1297 StoreChainDependents[Result.first->second].push_back(SU);
1299 // Iterate over the store chains.
1300 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
1301 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
1304 //===----------------------------------------------------------------------===//
1305 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
1306 //===----------------------------------------------------------------------===//
1309 /// \brief Post-process the DAG to create cluster edges between instructions
1310 /// that may be fused by the processor into a single operation.
1311 class MacroFusion : public ScheduleDAGMutation {
1312 const TargetInstrInfo *TII;
1314 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
1316 void apply(ScheduleDAGMI *DAG) override;
1320 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
1321 /// fused operations.
1322 void MacroFusion::apply(ScheduleDAGMI *DAG) {
1323 // For now, assume targets can only fuse with the branch.
1324 MachineInstr *Branch = DAG->ExitSU.getInstr();
1328 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
1329 SUnit *SU = &DAG->SUnits[--Idx];
1330 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
1333 // Create a single weak edge from SU to ExitSU. The only effect is to cause
1334 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
1335 // need to copy predecessor edges from ExitSU to SU, since top-down
1336 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
1337 // of SU, we could create an artificial edge from the deepest root, but it
1338 // hasn't been needed yet.
1339 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
1341 assert(Success && "No DAG nodes should be reachable from ExitSU");
1343 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
1348 //===----------------------------------------------------------------------===//
1349 // CopyConstrain - DAG post-processing to encourage copy elimination.
1350 //===----------------------------------------------------------------------===//
1353 /// \brief Post-process the DAG to create weak edges from all uses of a copy to
1354 /// the one use that defines the copy's source vreg, most likely an induction
1355 /// variable increment.
1356 class CopyConstrain : public ScheduleDAGMutation {
1358 SlotIndex RegionBeginIdx;
1359 // RegionEndIdx is the slot index of the last non-debug instruction in the
1360 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
1361 SlotIndex RegionEndIdx;
1363 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1365 void apply(ScheduleDAGMI *DAG) override;
1368 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
1372 /// constrainLocalCopy handles two possibilities:
1377 /// I3: dst = src (copy)
1378 /// (create pred->succ edges I0->I1, I2->I1)
1381 /// I0: dst = src (copy)
1385 /// (create pred->succ edges I1->I2, I3->I2)
1387 /// Although the MachineScheduler is currently constrained to single blocks,
1388 /// this algorithm should handle extended blocks. An EBB is a set of
1389 /// contiguously numbered blocks such that the previous block in the EBB is
1390 /// always the single predecessor.
1391 void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
1392 LiveIntervals *LIS = DAG->getLIS();
1393 MachineInstr *Copy = CopySU->getInstr();
1395 // Check for pure vreg copies.
1396 unsigned SrcReg = Copy->getOperand(1).getReg();
1397 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1400 unsigned DstReg = Copy->getOperand(0).getReg();
1401 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1404 // Check if either the dest or source is local. If it's live across a back
1405 // edge, it's not local. Note that if both vregs are live across the back
1406 // edge, we cannot successfully contrain the copy without cyclic scheduling.
1407 unsigned LocalReg = DstReg;
1408 unsigned GlobalReg = SrcReg;
1409 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1410 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
1413 LocalLI = &LIS->getInterval(LocalReg);
1414 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1417 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1419 // Find the global segment after the start of the local LI.
1420 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1421 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1422 // local live range. We could create edges from other global uses to the local
1423 // start, but the coalescer should have already eliminated these cases, so
1424 // don't bother dealing with it.
1425 if (GlobalSegment == GlobalLI->end())
1428 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1429 // returned the next global segment. But if GlobalSegment overlaps with
1430 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1431 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1432 if (GlobalSegment->contains(LocalLI->beginIndex()))
1435 if (GlobalSegment == GlobalLI->end())
1438 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1439 if (GlobalSegment != GlobalLI->begin()) {
1440 // Two address defs have no hole.
1441 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
1442 GlobalSegment->start)) {
1445 // If the prior global segment may be defined by the same two-address
1446 // instruction that also defines LocalLI, then can't make a hole here.
1447 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
1448 LocalLI->beginIndex())) {
1451 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1452 // it would be a disconnected component in the live range.
1453 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
1454 "Disconnected LRG within the scheduling region.");
1456 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1460 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1464 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1465 // constraining the uses of the last local def to precede GlobalDef.
1466 SmallVector<SUnit*,8> LocalUses;
1467 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1468 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1469 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1470 for (SUnit::const_succ_iterator
1471 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1473 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1475 if (I->getSUnit() == GlobalSU)
1477 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1479 LocalUses.push_back(I->getSUnit());
1481 // Open the top of the GlobalLI hole by constraining any earlier global uses
1482 // to precede the start of LocalLI.
1483 SmallVector<SUnit*,8> GlobalUses;
1484 MachineInstr *FirstLocalDef =
1485 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1486 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1487 for (SUnit::const_pred_iterator
1488 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1489 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1491 if (I->getSUnit() == FirstLocalSU)
1493 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1495 GlobalUses.push_back(I->getSUnit());
1497 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1498 // Add the weak edges.
1499 for (SmallVectorImpl<SUnit*>::const_iterator
1500 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1501 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1502 << GlobalSU->NodeNum << ")\n");
1503 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1505 for (SmallVectorImpl<SUnit*>::const_iterator
1506 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1507 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1508 << FirstLocalSU->NodeNum << ")\n");
1509 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1513 /// \brief Callback from DAG postProcessing to create weak edges to encourage
1514 /// copy elimination.
1515 void CopyConstrain::apply(ScheduleDAGMI *DAG) {
1516 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1518 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1519 if (FirstPos == DAG->end())
1521 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(&*FirstPos);
1522 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1523 &*priorNonDebug(DAG->end(), DAG->begin()));
1525 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1526 SUnit *SU = &DAG->SUnits[Idx];
1527 if (!SU->getInstr()->isCopy())
1530 constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
1534 //===----------------------------------------------------------------------===//
1535 // MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1536 // and possibly other custom schedulers.
1537 //===----------------------------------------------------------------------===//
1539 static const unsigned InvalidCycle = ~0U;
1541 SchedBoundary::~SchedBoundary() { delete HazardRec; }
1543 void SchedBoundary::reset() {
1544 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1545 // Destroying and reconstructing it is very expensive though. So keep
1546 // invalid, placeholder HazardRecs.
1547 if (HazardRec && HazardRec->isEnabled()) {
1553 CheckPending = false;
1557 MinReadyCycle = UINT_MAX;
1558 ExpectedLatency = 0;
1559 DependentLatency = 0;
1561 MaxExecutedResCount = 0;
1563 IsResourceLimited = false;
1564 ReservedCycles.clear();
1566 // Track the maximum number of stall cycles that could arise either from the
1567 // latency of a DAG edge or the number of cycles that a processor resource is
1568 // reserved (SchedBoundary::ReservedCycles).
1569 MaxObservedLatency = 0;
1571 // Reserve a zero-count for invalid CritResIdx.
1572 ExecutedResCounts.resize(1);
1573 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1576 void SchedRemainder::
1577 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1579 if (!SchedModel->hasInstrSchedModel())
1581 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1582 for (std::vector<SUnit>::iterator
1583 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1584 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1585 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1586 * SchedModel->getMicroOpFactor();
1587 for (TargetSchedModel::ProcResIter
1588 PI = SchedModel->getWriteProcResBegin(SC),
1589 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1590 unsigned PIdx = PI->ProcResourceIdx;
1591 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1592 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1597 void SchedBoundary::
1598 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1601 SchedModel = smodel;
1603 if (SchedModel->hasInstrSchedModel()) {
1604 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
1605 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1609 /// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1610 /// these "soft stalls" differently than the hard stall cycles based on CPU
1611 /// resources and computed by checkHazard(). A fully in-order model
1612 /// (MicroOpBufferSize==0) will not make use of this since instructions are not
1613 /// available for scheduling until they are ready. However, a weaker in-order
1614 /// model may use this for heuristics. For example, if a processor has in-order
1615 /// behavior when reading certain resources, this may come into play.
1616 unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
1617 if (!SU->isUnbuffered)
1620 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1621 if (ReadyCycle > CurrCycle)
1622 return ReadyCycle - CurrCycle;
1626 /// Compute the next cycle at which the given processor resource can be
1628 unsigned SchedBoundary::
1629 getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1630 unsigned NextUnreserved = ReservedCycles[PIdx];
1631 // If this resource has never been used, always return cycle zero.
1632 if (NextUnreserved == InvalidCycle)
1634 // For bottom-up scheduling add the cycles needed for the current operation.
1636 NextUnreserved += Cycles;
1637 return NextUnreserved;
1640 /// Does this SU have a hazard within the current instruction group.
1642 /// The scheduler supports two modes of hazard recognition. The first is the
1643 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1644 /// supports highly complicated in-order reservation tables
1645 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1647 /// The second is a streamlined mechanism that checks for hazards based on
1648 /// simple counters that the scheduler itself maintains. It explicitly checks
1649 /// for instruction dispatch limitations, including the number of micro-ops that
1650 /// can dispatch per cycle.
1652 /// TODO: Also check whether the SU must start a new group.
1653 bool SchedBoundary::checkHazard(SUnit *SU) {
1654 if (HazardRec->isEnabled()
1655 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1658 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1659 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
1660 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1661 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1664 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1665 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1666 for (TargetSchedModel::ProcResIter
1667 PI = SchedModel->getWriteProcResBegin(SC),
1668 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1669 if (getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles) > CurrCycle)
1676 // Find the unscheduled node in ReadySUs with the highest latency.
1677 unsigned SchedBoundary::
1678 findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
1680 unsigned RemLatency = 0;
1681 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
1683 unsigned L = getUnscheduledLatency(*I);
1684 if (L > RemLatency) {
1690 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1691 << LateSU->NodeNum << ") " << RemLatency << "c\n");
1696 // Count resources in this zone and the remaining unscheduled
1697 // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1698 // resource index, or zero if the zone is issue limited.
1699 unsigned SchedBoundary::
1700 getOtherResourceCount(unsigned &OtherCritIdx) {
1702 if (!SchedModel->hasInstrSchedModel())
1705 unsigned OtherCritCount = Rem->RemIssueCount
1706 + (RetiredMOps * SchedModel->getMicroOpFactor());
1707 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1708 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
1709 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1710 PIdx != PEnd; ++PIdx) {
1711 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1712 if (OtherCount > OtherCritCount) {
1713 OtherCritCount = OtherCount;
1714 OtherCritIdx = PIdx;
1718 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
1719 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
1720 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
1722 return OtherCritCount;
1725 void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
1726 if (ReadyCycle < MinReadyCycle)
1727 MinReadyCycle = ReadyCycle;
1729 // Check for interlocks first. For the purpose of other heuristics, an
1730 // instruction that cannot issue appears as if it's not in the ReadyQueue.
1731 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1732 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU))
1737 // Record this node as an immediate dependent of the scheduled node.
1741 void SchedBoundary::releaseTopNode(SUnit *SU) {
1742 if (SU->isScheduled)
1745 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1749 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1750 unsigned Latency = I->getLatency();
1752 MaxObservedLatency = std::max(Latency, MaxObservedLatency);
1754 if (SU->TopReadyCycle < PredReadyCycle + Latency)
1755 SU->TopReadyCycle = PredReadyCycle + Latency;
1757 releaseNode(SU, SU->TopReadyCycle);
1760 void SchedBoundary::releaseBottomNode(SUnit *SU) {
1761 if (SU->isScheduled)
1764 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1766 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1770 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1771 unsigned Latency = I->getLatency();
1773 MaxObservedLatency = std::max(Latency, MaxObservedLatency);
1775 if (SU->BotReadyCycle < SuccReadyCycle + Latency)
1776 SU->BotReadyCycle = SuccReadyCycle + Latency;
1778 releaseNode(SU, SU->BotReadyCycle);
1781 /// Move the boundary of scheduled code by one cycle.
1782 void SchedBoundary::bumpCycle(unsigned NextCycle) {
1783 if (SchedModel->getMicroOpBufferSize() == 0) {
1784 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1785 if (MinReadyCycle > NextCycle)
1786 NextCycle = MinReadyCycle;
1788 // Update the current micro-ops, which will issue in the next cycle.
1789 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1790 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1792 // Decrement DependentLatency based on the next cycle.
1793 if ((NextCycle - CurrCycle) > DependentLatency)
1794 DependentLatency = 0;
1796 DependentLatency -= (NextCycle - CurrCycle);
1798 if (!HazardRec->isEnabled()) {
1799 // Bypass HazardRec virtual calls.
1800 CurrCycle = NextCycle;
1803 // Bypass getHazardType calls in case of long latency.
1804 for (; CurrCycle != NextCycle; ++CurrCycle) {
1806 HazardRec->AdvanceCycle();
1808 HazardRec->RecedeCycle();
1811 CheckPending = true;
1812 unsigned LFactor = SchedModel->getLatencyFactor();
1814 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1817 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
1820 void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
1821 ExecutedResCounts[PIdx] += Count;
1822 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
1823 MaxExecutedResCount = ExecutedResCounts[PIdx];
1826 /// Add the given processor resource to this scheduled zone.
1828 /// \param Cycles indicates the number of consecutive (non-pipelined) cycles
1829 /// during which this resource is consumed.
1831 /// \return the next cycle at which the instruction may execute without
1832 /// oversubscribing resources.
1833 unsigned SchedBoundary::
1834 countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
1835 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1836 unsigned Count = Factor * Cycles;
1837 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
1838 << " +" << Cycles << "x" << Factor << "u\n");
1840 // Update Executed resources counts.
1841 incExecutedResources(PIdx, Count);
1842 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1843 Rem->RemainingCounts[PIdx] -= Count;
1845 // Check if this resource exceeds the current critical resource. If so, it
1846 // becomes the critical resource.
1847 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
1848 ZoneCritResIdx = PIdx;
1849 DEBUG(dbgs() << " *** Critical resource "
1850 << SchedModel->getResourceName(PIdx) << ": "
1851 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
1853 // For reserved resources, record the highest cycle using the resource.
1854 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
1855 if (NextAvailable > CurrCycle) {
1856 DEBUG(dbgs() << " Resource conflict: "
1857 << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
1858 << NextAvailable << "\n");
1860 return NextAvailable;
1863 /// Move the boundary of scheduled code by one SUnit.
1864 void SchedBoundary::bumpNode(SUnit *SU) {
1865 // Update the reservation table.
1866 if (HazardRec->isEnabled()) {
1867 if (!isTop() && SU->isCall) {
1868 // Calls are scheduled with their preceding instructions. For bottom-up
1869 // scheduling, clear the pipeline state before emitting.
1872 HazardRec->EmitInstruction(SU);
1874 // checkHazard should prevent scheduling multiple instructions per cycle that
1875 // exceed the issue width.
1876 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1877 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
1879 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
1880 "Cannot schedule this instruction's MicroOps in the current cycle.");
1882 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1883 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
1885 unsigned NextCycle = CurrCycle;
1886 switch (SchedModel->getMicroOpBufferSize()) {
1888 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
1891 if (ReadyCycle > NextCycle) {
1892 NextCycle = ReadyCycle;
1893 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
1897 // We don't currently model the OOO reorder buffer, so consider all
1898 // scheduled MOps to be "retired". We do loosely model in-order resource
1899 // latency. If this instruction uses an in-order resource, account for any
1900 // likely stall cycles.
1901 if (SU->isUnbuffered && ReadyCycle > NextCycle)
1902 NextCycle = ReadyCycle;
1905 RetiredMOps += IncMOps;
1907 // Update resource counts and critical resource.
1908 if (SchedModel->hasInstrSchedModel()) {
1909 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
1910 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
1911 Rem->RemIssueCount -= DecRemIssue;
1912 if (ZoneCritResIdx) {
1913 // Scale scheduled micro-ops for comparing with the critical resource.
1914 unsigned ScaledMOps =
1915 RetiredMOps * SchedModel->getMicroOpFactor();
1917 // If scaled micro-ops are now more than the previous critical resource by
1918 // a full cycle, then micro-ops issue becomes critical.
1919 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
1920 >= (int)SchedModel->getLatencyFactor()) {
1922 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
1923 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
1926 for (TargetSchedModel::ProcResIter
1927 PI = SchedModel->getWriteProcResBegin(SC),
1928 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1930 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
1931 if (RCycle > NextCycle)
1934 if (SU->hasReservedResource) {
1935 // For reserved resources, record the highest cycle using the resource.
1936 // For top-down scheduling, this is the cycle in which we schedule this
1937 // instruction plus the number of cycles the operations reserves the
1938 // resource. For bottom-up is it simply the instruction's cycle.
1939 for (TargetSchedModel::ProcResIter
1940 PI = SchedModel->getWriteProcResBegin(SC),
1941 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1942 unsigned PIdx = PI->ProcResourceIdx;
1943 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
1944 ReservedCycles[PIdx] = isTop() ? NextCycle + PI->Cycles : NextCycle;
1946 MaxObservedLatency = std::max(PI->Cycles, MaxObservedLatency);
1952 // Update ExpectedLatency and DependentLatency.
1953 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
1954 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
1955 if (SU->getDepth() > TopLatency) {
1956 TopLatency = SU->getDepth();
1957 DEBUG(dbgs() << " " << Available.getName()
1958 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
1960 if (SU->getHeight() > BotLatency) {
1961 BotLatency = SU->getHeight();
1962 DEBUG(dbgs() << " " << Available.getName()
1963 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
1965 // If we stall for any reason, bump the cycle.
1966 if (NextCycle > CurrCycle) {
1967 bumpCycle(NextCycle);
1970 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
1971 // resource limited. If a stall occurred, bumpCycle does this.
1972 unsigned LFactor = SchedModel->getLatencyFactor();
1974 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1977 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
1978 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
1979 // one cycle. Since we commonly reach the max MOps here, opportunistically
1980 // bump the cycle to avoid uselessly checking everything in the readyQ.
1981 CurrMOps += IncMOps;
1982 while (CurrMOps >= SchedModel->getIssueWidth()) {
1983 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
1984 << " at cycle " << CurrCycle << '\n');
1985 bumpCycle(++NextCycle);
1987 DEBUG(dumpScheduledState());
1990 /// Release pending ready nodes in to the available queue. This makes them
1991 /// visible to heuristics.
1992 void SchedBoundary::releasePending() {
1993 // If the available queue is empty, it is safe to reset MinReadyCycle.
1994 if (Available.empty())
1995 MinReadyCycle = UINT_MAX;
1997 // Check to see if any of the pending instructions are ready to issue. If
1998 // so, add them to the available queue.
1999 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
2000 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2001 SUnit *SU = *(Pending.begin()+i);
2002 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
2004 if (ReadyCycle < MinReadyCycle)
2005 MinReadyCycle = ReadyCycle;
2007 if (!IsBuffered && ReadyCycle > CurrCycle)
2010 if (checkHazard(SU))
2014 Pending.remove(Pending.begin()+i);
2017 DEBUG(if (!Pending.empty()) Pending.dump());
2018 CheckPending = false;
2021 /// Remove SU from the ready set for this boundary.
2022 void SchedBoundary::removeReady(SUnit *SU) {
2023 if (Available.isInQueue(SU))
2024 Available.remove(Available.find(SU));
2026 assert(Pending.isInQueue(SU) && "bad ready count");
2027 Pending.remove(Pending.find(SU));
2031 /// If this queue only has one ready candidate, return it. As a side effect,
2032 /// defer any nodes that now hit a hazard, and advance the cycle until at least
2033 /// one node is ready. If multiple instructions are ready, return NULL.
2034 SUnit *SchedBoundary::pickOnlyChoice() {
2039 // Defer any ready instrs that now have a hazard.
2040 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2041 if (checkHazard(*I)) {
2043 I = Available.remove(I);
2049 for (unsigned i = 0; Available.empty(); ++i) {
2050 assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedLatency) &&
2051 "permanent hazard"); (void)i;
2052 bumpCycle(CurrCycle + 1);
2055 if (Available.size() == 1)
2056 return *Available.begin();
2061 // This is useful information to dump after bumpNode.
2062 // Note that the Queue contents are more useful before pickNodeFromQueue.
2063 void SchedBoundary::dumpScheduledState() {
2066 if (ZoneCritResIdx) {
2067 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2068 ResCount = getResourceCount(ZoneCritResIdx);
2071 ResFactor = SchedModel->getMicroOpFactor();
2072 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
2074 unsigned LFactor = SchedModel->getLatencyFactor();
2075 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2076 << " Retired: " << RetiredMOps;
2077 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2078 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
2079 << ResCount / ResFactor << " "
2080 << SchedModel->getResourceName(ZoneCritResIdx)
2081 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2082 << (IsResourceLimited ? " - Resource" : " - Latency")
2087 //===----------------------------------------------------------------------===//
2088 // GenericScheduler - Generic implementation of MachineSchedStrategy.
2089 //===----------------------------------------------------------------------===//
2092 /// Base class for GenericScheduler. This class maintains information about
2093 /// scheduling candidates based on TargetSchedModel making it easy to implement
2094 /// heuristics for either preRA or postRA scheduling.
2095 class GenericSchedulerBase : public MachineSchedStrategy {
2097 /// Represent the type of SchedCandidate found within a single queue.
2098 /// pickNodeBidirectional depends on these listed by decreasing priority.
2100 NoCand, PhysRegCopy, RegExcess, RegCritical, Stall, Cluster, Weak, RegMax,
2101 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
2102 TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
2105 static const char *getReasonStr(GenericSchedulerBase::CandReason Reason);
2108 /// Policy for scheduling the next instruction in the candidate's zone.
2111 unsigned ReduceResIdx;
2112 unsigned DemandResIdx;
2114 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
2117 /// Status of an instruction's critical resource consumption.
2118 struct SchedResourceDelta {
2119 // Count critical resources in the scheduled region required by SU.
2120 unsigned CritResources;
2122 // Count critical resources from another region consumed by SU.
2123 unsigned DemandedResources;
2125 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
2127 bool operator==(const SchedResourceDelta &RHS) const {
2128 return CritResources == RHS.CritResources
2129 && DemandedResources == RHS.DemandedResources;
2131 bool operator!=(const SchedResourceDelta &RHS) const {
2132 return !operator==(RHS);
2136 /// Store the state used by GenericScheduler heuristics, required for the
2137 /// lifetime of one invocation of pickNode().
2138 struct SchedCandidate {
2141 // The best SUnit candidate.
2144 // The reason for this candidate.
2147 // Set of reasons that apply to multiple candidates.
2148 uint32_t RepeatReasonSet;
2150 // Register pressure values for the best candidate.
2151 RegPressureDelta RPDelta;
2153 // Critical resource consumption of the best candidate.
2154 SchedResourceDelta ResDelta;
2156 SchedCandidate(const CandPolicy &policy)
2157 : Policy(policy), SU(NULL), Reason(NoCand), RepeatReasonSet(0) {}
2159 bool isValid() const { return SU; }
2161 // Copy the status of another candidate without changing policy.
2162 void setBest(SchedCandidate &Best) {
2163 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
2165 Reason = Best.Reason;
2166 RPDelta = Best.RPDelta;
2167 ResDelta = Best.ResDelta;
2170 bool isRepeat(CandReason R) { return RepeatReasonSet & (1 << R); }
2171 void setRepeat(CandReason R) { RepeatReasonSet |= (1 << R); }
2173 void initResourceDelta(const ScheduleDAGMI *DAG,
2174 const TargetSchedModel *SchedModel);
2178 const MachineSchedContext *Context;
2179 const TargetSchedModel *SchedModel;
2180 const TargetRegisterInfo *TRI;
2184 GenericSchedulerBase(const MachineSchedContext *C):
2185 Context(C), SchedModel(0), TRI(0) {}
2187 void setPolicy(CandPolicy &Policy, bool IsPostRA, SchedBoundary &CurrZone,
2188 SchedBoundary *OtherZone);
2191 void traceCandidate(const SchedCandidate &Cand);
2196 void GenericSchedulerBase::SchedCandidate::
2197 initResourceDelta(const ScheduleDAGMI *DAG,
2198 const TargetSchedModel *SchedModel) {
2199 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2202 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2203 for (TargetSchedModel::ProcResIter
2204 PI = SchedModel->getWriteProcResBegin(SC),
2205 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2206 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2207 ResDelta.CritResources += PI->Cycles;
2208 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2209 ResDelta.DemandedResources += PI->Cycles;
2213 /// Set the CandPolicy given a scheduling zone given the current resources and
2214 /// latencies inside and outside the zone.
2215 void GenericSchedulerBase::setPolicy(CandPolicy &Policy,
2217 SchedBoundary &CurrZone,
2218 SchedBoundary *OtherZone) {
2219 // Apply preemptive heuristics based on the the total latency and resources
2220 // inside and outside this zone. Potential stalls should be considered before
2221 // following this policy.
2223 // Compute remaining latency. We need this both to determine whether the
2224 // overall schedule has become latency-limited and whether the instructions
2225 // outside this zone are resource or latency limited.
2227 // The "dependent" latency is updated incrementally during scheduling as the
2228 // max height/depth of scheduled nodes minus the cycles since it was
2230 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2232 // The "independent" latency is the max ready queue depth:
2233 // ILat = max N.depth for N in Available|Pending
2235 // RemainingLatency is the greater of independent and dependent latency.
2236 unsigned RemLatency = CurrZone.getDependentLatency();
2237 RemLatency = std::max(RemLatency,
2238 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2239 RemLatency = std::max(RemLatency,
2240 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2242 // Compute the critical resource outside the zone.
2243 unsigned OtherCritIdx = 0;
2244 unsigned OtherCount =
2245 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2247 bool OtherResLimited = false;
2248 if (SchedModel->hasInstrSchedModel()) {
2249 unsigned LFactor = SchedModel->getLatencyFactor();
2250 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2252 // Schedule aggressively for latency in PostRA mode. We don't check for
2253 // acyclic latency during PostRA, and highly out-of-order processors will
2254 // skip PostRA scheduling.
2255 if (!OtherResLimited) {
2256 if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2257 Policy.ReduceLatency |= true;
2258 DEBUG(dbgs() << " " << CurrZone.Available.getName()
2259 << " RemainingLatency " << RemLatency << " + "
2260 << CurrZone.getCurrCycle() << "c > CritPath "
2261 << Rem.CriticalPath << "\n");
2264 // If the same resource is limiting inside and outside the zone, do nothing.
2265 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2269 if (CurrZone.isResourceLimited()) {
2270 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2271 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2274 if (OtherResLimited)
2275 dbgs() << " RemainingLimit: "
2276 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2277 if (!CurrZone.isResourceLimited() && !OtherResLimited)
2278 dbgs() << " Latency limited both directions.\n");
2280 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2281 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2283 if (OtherResLimited)
2284 Policy.DemandResIdx = OtherCritIdx;
2288 const char *GenericSchedulerBase::getReasonStr(
2289 GenericSchedulerBase::CandReason Reason) {
2291 case NoCand: return "NOCAND ";
2292 case PhysRegCopy: return "PREG-COPY";
2293 case RegExcess: return "REG-EXCESS";
2294 case RegCritical: return "REG-CRIT ";
2295 case Stall: return "STALL ";
2296 case Cluster: return "CLUSTER ";
2297 case Weak: return "WEAK ";
2298 case RegMax: return "REG-MAX ";
2299 case ResourceReduce: return "RES-REDUCE";
2300 case ResourceDemand: return "RES-DEMAND";
2301 case TopDepthReduce: return "TOP-DEPTH ";
2302 case TopPathReduce: return "TOP-PATH ";
2303 case BotHeightReduce:return "BOT-HEIGHT";
2304 case BotPathReduce: return "BOT-PATH ";
2305 case NextDefUse: return "DEF-USE ";
2306 case NodeOrder: return "ORDER ";
2308 llvm_unreachable("Unknown reason!");
2311 void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2313 unsigned ResIdx = 0;
2314 unsigned Latency = 0;
2315 switch (Cand.Reason) {
2319 P = Cand.RPDelta.Excess;
2322 P = Cand.RPDelta.CriticalMax;
2325 P = Cand.RPDelta.CurrentMax;
2327 case ResourceReduce:
2328 ResIdx = Cand.Policy.ReduceResIdx;
2330 case ResourceDemand:
2331 ResIdx = Cand.Policy.DemandResIdx;
2333 case TopDepthReduce:
2334 Latency = Cand.SU->getDepth();
2337 Latency = Cand.SU->getHeight();
2339 case BotHeightReduce:
2340 Latency = Cand.SU->getHeight();
2343 Latency = Cand.SU->getDepth();
2346 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
2348 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2349 << ":" << P.getUnitInc() << " ";
2353 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2357 dbgs() << " " << Latency << " cycles ";
2364 /// Return true if this heuristic determines order.
2365 static bool tryLess(int TryVal, int CandVal,
2366 GenericSchedulerBase::SchedCandidate &TryCand,
2367 GenericSchedulerBase::SchedCandidate &Cand,
2368 GenericSchedulerBase::CandReason Reason) {
2369 if (TryVal < CandVal) {
2370 TryCand.Reason = Reason;
2373 if (TryVal > CandVal) {
2374 if (Cand.Reason > Reason)
2375 Cand.Reason = Reason;
2378 Cand.setRepeat(Reason);
2382 static bool tryGreater(int TryVal, int CandVal,
2383 GenericSchedulerBase::SchedCandidate &TryCand,
2384 GenericSchedulerBase::SchedCandidate &Cand,
2385 GenericSchedulerBase::CandReason Reason) {
2386 if (TryVal > CandVal) {
2387 TryCand.Reason = Reason;
2390 if (TryVal < CandVal) {
2391 if (Cand.Reason > Reason)
2392 Cand.Reason = Reason;
2395 Cand.setRepeat(Reason);
2399 static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2400 GenericSchedulerBase::SchedCandidate &Cand,
2401 SchedBoundary &Zone) {
2403 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2404 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2405 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2408 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2409 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2413 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2414 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2415 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2418 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2419 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2425 static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand,
2427 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2428 << GenericSchedulerBase::getReasonStr(Cand.Reason) << '\n');
2432 /// GenericScheduler shrinks the unscheduled zone using heuristics to balance
2434 class GenericScheduler : public GenericSchedulerBase {
2435 ScheduleDAGMILive *DAG;
2437 // State of the top and bottom scheduled instruction boundaries.
2441 MachineSchedPolicy RegionPolicy;
2443 GenericScheduler(const MachineSchedContext *C):
2444 GenericSchedulerBase(C), DAG(0), Top(SchedBoundary::TopQID, "TopQ"),
2445 Bot(SchedBoundary::BotQID, "BotQ") {}
2447 void initPolicy(MachineBasicBlock::iterator Begin,
2448 MachineBasicBlock::iterator End,
2449 unsigned NumRegionInstrs) override;
2451 bool shouldTrackPressure() const override {
2452 return RegionPolicy.ShouldTrackPressure;
2455 void initialize(ScheduleDAGMI *dag) override;
2457 SUnit *pickNode(bool &IsTopNode) override;
2459 void schedNode(SUnit *SU, bool IsTopNode) override;
2461 void releaseTopNode(SUnit *SU) override {
2462 Top.releaseTopNode(SU);
2465 void releaseBottomNode(SUnit *SU) override {
2466 Bot.releaseBottomNode(SU);
2469 void registerRoots() override;
2472 void checkAcyclicLatency();
2474 void tryCandidate(SchedCandidate &Cand,
2475 SchedCandidate &TryCand,
2476 SchedBoundary &Zone,
2477 const RegPressureTracker &RPTracker,
2478 RegPressureTracker &TempTracker);
2480 SUnit *pickNodeBidirectional(bool &IsTopNode);
2482 void pickNodeFromQueue(SchedBoundary &Zone,
2483 const RegPressureTracker &RPTracker,
2484 SchedCandidate &Candidate);
2486 void reschedulePhysRegCopies(SUnit *SU, bool isTop);
2490 void GenericScheduler::initialize(ScheduleDAGMI *dag) {
2491 assert(dag->hasVRegLiveness() &&
2492 "(PreRA)GenericScheduler needs vreg liveness");
2493 DAG = static_cast<ScheduleDAGMILive*>(dag);
2494 SchedModel = DAG->getSchedModel();
2497 Rem.init(DAG, SchedModel);
2498 Top.init(DAG, SchedModel, &Rem);
2499 Bot.init(DAG, SchedModel, &Rem);
2501 // Initialize resource counts.
2503 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2504 // are disabled, then these HazardRecs will be disabled.
2505 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
2506 const TargetMachine &TM = DAG->MF.getTarget();
2507 if (!Top.HazardRec) {
2509 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2511 if (!Bot.HazardRec) {
2513 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2517 /// Initialize the per-region scheduling policy.
2518 void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2519 MachineBasicBlock::iterator End,
2520 unsigned NumRegionInstrs) {
2521 const TargetMachine &TM = Context->MF->getTarget();
2522 const TargetLowering *TLI = TM.getTargetLowering();
2524 // Avoid setting up the register pressure tracker for small regions to save
2525 // compile time. As a rough heuristic, only track pressure when the number of
2526 // schedulable instructions exceeds half the integer register file.
2527 RegionPolicy.ShouldTrackPressure = true;
2528 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2529 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2530 if (TLI->isTypeLegal(LegalIntVT)) {
2531 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
2532 TLI->getRegClassFor(LegalIntVT));
2533 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2537 // For generic targets, we default to bottom-up, because it's simpler and more
2538 // compile-time optimizations have been implemented in that direction.
2539 RegionPolicy.OnlyBottomUp = true;
2541 // Allow the subtarget to override default policy.
2542 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
2543 ST.overrideSchedPolicy(RegionPolicy, Begin, End, NumRegionInstrs);
2545 // After subtarget overrides, apply command line options.
2546 if (!EnableRegPressure)
2547 RegionPolicy.ShouldTrackPressure = false;
2549 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2550 // e.g. -misched-bottomup=false allows scheduling in both directions.
2551 assert((!ForceTopDown || !ForceBottomUp) &&
2552 "-misched-topdown incompatible with -misched-bottomup");
2553 if (ForceBottomUp.getNumOccurrences() > 0) {
2554 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2555 if (RegionPolicy.OnlyBottomUp)
2556 RegionPolicy.OnlyTopDown = false;
2558 if (ForceTopDown.getNumOccurrences() > 0) {
2559 RegionPolicy.OnlyTopDown = ForceTopDown;
2560 if (RegionPolicy.OnlyTopDown)
2561 RegionPolicy.OnlyBottomUp = false;
2565 /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2566 /// critical path by more cycles than it takes to drain the instruction buffer.
2567 /// We estimate an upper bounds on in-flight instructions as:
2569 /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2570 /// InFlightIterations = AcyclicPath / CyclesPerIteration
2571 /// InFlightResources = InFlightIterations * LoopResources
2573 /// TODO: Check execution resources in addition to IssueCount.
2574 void GenericScheduler::checkAcyclicLatency() {
2575 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2578 // Scaled number of cycles per loop iteration.
2579 unsigned IterCount =
2580 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2582 // Scaled acyclic critical path.
2583 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2584 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2585 unsigned InFlightCount =
2586 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2587 unsigned BufferLimit =
2588 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2590 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2592 DEBUG(dbgs() << "IssueCycles="
2593 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2594 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2595 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2596 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2597 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2598 if (Rem.IsAcyclicLatencyLimited)
2599 dbgs() << " ACYCLIC LATENCY LIMIT\n");
2602 void GenericScheduler::registerRoots() {
2603 Rem.CriticalPath = DAG->ExitSU.getDepth();
2605 // Some roots may not feed into ExitSU. Check all of them in case.
2606 for (std::vector<SUnit*>::const_iterator
2607 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
2608 if ((*I)->getDepth() > Rem.CriticalPath)
2609 Rem.CriticalPath = (*I)->getDepth();
2611 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
2613 if (EnableCyclicPath) {
2614 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2615 checkAcyclicLatency();
2619 static bool tryPressure(const PressureChange &TryP,
2620 const PressureChange &CandP,
2621 GenericSchedulerBase::SchedCandidate &TryCand,
2622 GenericSchedulerBase::SchedCandidate &Cand,
2623 GenericSchedulerBase::CandReason Reason) {
2624 int TryRank = TryP.getPSetOrMax();
2625 int CandRank = CandP.getPSetOrMax();
2626 // If both candidates affect the same set, go with the smallest increase.
2627 if (TryRank == CandRank) {
2628 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2631 // If one candidate decreases and the other increases, go with it.
2632 // Invalid candidates have UnitInc==0.
2633 if (tryLess(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2637 // If the candidates are decreasing pressure, reverse priority.
2638 if (TryP.getUnitInc() < 0)
2639 std::swap(TryRank, CandRank);
2640 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2643 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2644 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2647 /// Minimize physical register live ranges. Regalloc wants them adjacent to
2648 /// their physreg def/use.
2650 /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2651 /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2652 /// with the operation that produces or consumes the physreg. We'll do this when
2653 /// regalloc has support for parallel copies.
2654 static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2655 const MachineInstr *MI = SU->getInstr();
2659 unsigned ScheduledOper = isTop ? 1 : 0;
2660 unsigned UnscheduledOper = isTop ? 0 : 1;
2661 // If we have already scheduled the physreg produce/consumer, immediately
2662 // schedule the copy.
2663 if (TargetRegisterInfo::isPhysicalRegister(
2664 MI->getOperand(ScheduledOper).getReg()))
2666 // If the physreg is at the boundary, defer it. Otherwise schedule it
2667 // immediately to free the dependent. We can hoist the copy later.
2668 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2669 if (TargetRegisterInfo::isPhysicalRegister(
2670 MI->getOperand(UnscheduledOper).getReg()))
2671 return AtBoundary ? -1 : 1;
2675 /// Apply a set of heursitics to a new candidate. Heuristics are currently
2676 /// hierarchical. This may be more efficient than a graduated cost model because
2677 /// we don't need to evaluate all aspects of the model for each node in the
2678 /// queue. But it's really done to make the heuristics easier to debug and
2679 /// statistically analyze.
2681 /// \param Cand provides the policy and current best candidate.
2682 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2683 /// \param Zone describes the scheduled zone that we are extending.
2684 /// \param RPTracker describes reg pressure within the scheduled zone.
2685 /// \param TempTracker is a scratch pressure tracker to reuse in queries.
2686 void GenericScheduler::tryCandidate(SchedCandidate &Cand,
2687 SchedCandidate &TryCand,
2688 SchedBoundary &Zone,
2689 const RegPressureTracker &RPTracker,
2690 RegPressureTracker &TempTracker) {
2692 if (DAG->isTrackingPressure()) {
2693 // Always initialize TryCand's RPDelta.
2695 TempTracker.getMaxDownwardPressureDelta(
2696 TryCand.SU->getInstr(),
2698 DAG->getRegionCriticalPSets(),
2699 DAG->getRegPressure().MaxSetPressure);
2702 if (VerifyScheduling) {
2703 TempTracker.getMaxUpwardPressureDelta(
2704 TryCand.SU->getInstr(),
2705 &DAG->getPressureDiff(TryCand.SU),
2707 DAG->getRegionCriticalPSets(),
2708 DAG->getRegPressure().MaxSetPressure);
2711 RPTracker.getUpwardPressureDelta(
2712 TryCand.SU->getInstr(),
2713 DAG->getPressureDiff(TryCand.SU),
2715 DAG->getRegionCriticalPSets(),
2716 DAG->getRegPressure().MaxSetPressure);
2720 DEBUG(if (TryCand.RPDelta.Excess.isValid())
2721 dbgs() << " SU(" << TryCand.SU->NodeNum << ") "
2722 << TRI->getRegPressureSetName(TryCand.RPDelta.Excess.getPSet())
2723 << ":" << TryCand.RPDelta.Excess.getUnitInc() << "\n");
2725 // Initialize the candidate if needed.
2726 if (!Cand.isValid()) {
2727 TryCand.Reason = NodeOrder;
2731 if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2732 biasPhysRegCopy(Cand.SU, Zone.isTop()),
2733 TryCand, Cand, PhysRegCopy))
2736 // Avoid exceeding the target's limit. If signed PSetID is negative, it is
2737 // invalid; convert it to INT_MAX to give it lowest priority.
2738 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2739 Cand.RPDelta.Excess,
2740 TryCand, Cand, RegExcess))
2743 // Avoid increasing the max critical pressure in the scheduled region.
2744 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2745 Cand.RPDelta.CriticalMax,
2746 TryCand, Cand, RegCritical))
2749 // For loops that are acyclic path limited, aggressively schedule for latency.
2750 // This can result in very long dependence chains scheduled in sequence, so
2751 // once every cycle (when CurrMOps == 0), switch to normal heuristics.
2752 if (Rem.IsAcyclicLatencyLimited && !Zone.getCurrMOps()
2753 && tryLatency(TryCand, Cand, Zone))
2756 // Prioritize instructions that read unbuffered resources by stall cycles.
2757 if (tryLess(Zone.getLatencyStallCycles(TryCand.SU),
2758 Zone.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2761 // Keep clustered nodes together to encourage downstream peephole
2762 // optimizations which may reduce resource requirements.
2764 // This is a best effort to set things up for a post-RA pass. Optimizations
2765 // like generating loads of multiple registers should ideally be done within
2766 // the scheduler pass by combining the loads during DAG postprocessing.
2767 const SUnit *NextClusterSU =
2768 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2769 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2770 TryCand, Cand, Cluster))
2773 // Weak edges are for clustering and other constraints.
2774 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2775 getWeakLeft(Cand.SU, Zone.isTop()),
2776 TryCand, Cand, Weak)) {
2779 // Avoid increasing the max pressure of the entire region.
2780 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2781 Cand.RPDelta.CurrentMax,
2782 TryCand, Cand, RegMax))
2785 // Avoid critical resource consumption and balance the schedule.
2786 TryCand.initResourceDelta(DAG, SchedModel);
2787 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2788 TryCand, Cand, ResourceReduce))
2790 if (tryGreater(TryCand.ResDelta.DemandedResources,
2791 Cand.ResDelta.DemandedResources,
2792 TryCand, Cand, ResourceDemand))
2795 // Avoid serializing long latency dependence chains.
2796 // For acyclic path limited loops, latency was already checked above.
2797 if (Cand.Policy.ReduceLatency && !Rem.IsAcyclicLatencyLimited
2798 && tryLatency(TryCand, Cand, Zone)) {
2802 // Prefer immediate defs/users of the last scheduled instruction. This is a
2803 // local pressure avoidance strategy that also makes the machine code
2805 if (tryGreater(Zone.isNextSU(TryCand.SU), Zone.isNextSU(Cand.SU),
2806 TryCand, Cand, NextDefUse))
2809 // Fall through to original instruction order.
2810 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2811 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2812 TryCand.Reason = NodeOrder;
2816 /// Pick the best candidate from the queue.
2818 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2819 /// DAG building. To adjust for the current scheduling location we need to
2820 /// maintain the number of vreg uses remaining to be top-scheduled.
2821 void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
2822 const RegPressureTracker &RPTracker,
2823 SchedCandidate &Cand) {
2824 ReadyQueue &Q = Zone.Available;
2828 // getMaxPressureDelta temporarily modifies the tracker.
2829 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2831 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
2833 SchedCandidate TryCand(Cand.Policy);
2835 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
2836 if (TryCand.Reason != NoCand) {
2837 // Initialize resource delta if needed in case future heuristics query it.
2838 if (TryCand.ResDelta == SchedResourceDelta())
2839 TryCand.initResourceDelta(DAG, SchedModel);
2840 Cand.setBest(TryCand);
2841 DEBUG(traceCandidate(Cand));
2846 /// Pick the best candidate node from either the top or bottom queue.
2847 SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
2848 // Schedule as far as possible in the direction of no choice. This is most
2849 // efficient, but also provides the best heuristics for CriticalPSets.
2850 if (SUnit *SU = Bot.pickOnlyChoice()) {
2852 DEBUG(dbgs() << "Pick Bot NOCAND\n");
2855 if (SUnit *SU = Top.pickOnlyChoice()) {
2857 DEBUG(dbgs() << "Pick Top NOCAND\n");
2860 CandPolicy NoPolicy;
2861 SchedCandidate BotCand(NoPolicy);
2862 SchedCandidate TopCand(NoPolicy);
2863 // Set the bottom-up policy based on the state of the current bottom zone and
2864 // the instructions outside the zone, including the top zone.
2865 setPolicy(BotCand.Policy, /*IsPostRA=*/false, Bot, &Top);
2866 // Set the top-down policy based on the state of the current top zone and
2867 // the instructions outside the zone, including the bottom zone.
2868 setPolicy(TopCand.Policy, /*IsPostRA=*/false, Top, &Bot);
2870 // Prefer bottom scheduling when heuristics are silent.
2871 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2872 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2874 // If either Q has a single candidate that provides the least increase in
2875 // Excess pressure, we can immediately schedule from that Q.
2877 // RegionCriticalPSets summarizes the pressure within the scheduled region and
2878 // affects picking from either Q. If scheduling in one direction must
2879 // increase pressure for one of the excess PSets, then schedule in that
2880 // direction first to provide more freedom in the other direction.
2881 if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
2882 || (BotCand.Reason == RegCritical
2883 && !BotCand.isRepeat(RegCritical)))
2886 tracePick(BotCand, IsTopNode);
2889 // Check if the top Q has a better candidate.
2890 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2891 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2893 // Choose the queue with the most important (lowest enum) reason.
2894 if (TopCand.Reason < BotCand.Reason) {
2896 tracePick(TopCand, IsTopNode);
2899 // Otherwise prefer the bottom candidate, in node order if all else failed.
2901 tracePick(BotCand, IsTopNode);
2905 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
2906 SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
2907 if (DAG->top() == DAG->bottom()) {
2908 assert(Top.Available.empty() && Top.Pending.empty() &&
2909 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
2914 if (RegionPolicy.OnlyTopDown) {
2915 SU = Top.pickOnlyChoice();
2917 CandPolicy NoPolicy;
2918 SchedCandidate TopCand(NoPolicy);
2919 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2920 assert(TopCand.Reason != NoCand && "failed to find a candidate");
2921 tracePick(TopCand, true);
2926 else if (RegionPolicy.OnlyBottomUp) {
2927 SU = Bot.pickOnlyChoice();
2929 CandPolicy NoPolicy;
2930 SchedCandidate BotCand(NoPolicy);
2931 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2932 assert(BotCand.Reason != NoCand && "failed to find a candidate");
2933 tracePick(BotCand, false);
2939 SU = pickNodeBidirectional(IsTopNode);
2941 } while (SU->isScheduled);
2943 if (SU->isTopReady())
2944 Top.removeReady(SU);
2945 if (SU->isBottomReady())
2946 Bot.removeReady(SU);
2948 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
2952 void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
2954 MachineBasicBlock::iterator InsertPos = SU->getInstr();
2957 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
2959 // Find already scheduled copies with a single physreg dependence and move
2960 // them just above the scheduled instruction.
2961 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
2963 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
2965 SUnit *DepSU = I->getSUnit();
2966 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
2968 MachineInstr *Copy = DepSU->getInstr();
2969 if (!Copy->isCopy())
2971 DEBUG(dbgs() << " Rescheduling physreg copy ";
2972 I->getSUnit()->dump(DAG));
2973 DAG->moveInstruction(Copy, InsertPos);
2977 /// Update the scheduler's state after scheduling a node. This is the same node
2978 /// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
2979 /// update it's state based on the current cycle before MachineSchedStrategy
2982 /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
2983 /// them here. See comments in biasPhysRegCopy.
2984 void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2986 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
2988 if (SU->hasPhysRegUses)
2989 reschedulePhysRegCopies(SU, true);
2992 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
2994 if (SU->hasPhysRegDefs)
2995 reschedulePhysRegCopies(SU, false);
2999 /// Create the standard converging machine scheduler. This will be used as the
3000 /// default scheduler if the target does not set a default.
3001 static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C) {
3002 ScheduleDAGMILive *DAG = new ScheduleDAGMILive(C, new GenericScheduler(C));
3003 // Register DAG post-processors.
3005 // FIXME: extend the mutation API to allow earlier mutations to instantiate
3006 // data and pass it to later mutations. Have a single mutation that gathers
3007 // the interesting nodes in one pass.
3008 DAG->addMutation(new CopyConstrain(DAG->TII, DAG->TRI));
3009 if (EnableLoadCluster && DAG->TII->enableClusterLoads())
3010 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
3011 if (EnableMacroFusion)
3012 DAG->addMutation(new MacroFusion(DAG->TII));
3016 static MachineSchedRegistry
3017 GenericSchedRegistry("converge", "Standard converging scheduler.",
3018 createGenericSchedLive);
3020 //===----------------------------------------------------------------------===//
3021 // PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3022 //===----------------------------------------------------------------------===//
3025 /// PostGenericScheduler - Interface to the scheduling algorithm used by
3028 /// Callbacks from ScheduleDAGMI:
3029 /// initPolicy -> initialize(DAG) -> registerRoots -> pickNode ...
3030 class PostGenericScheduler : public GenericSchedulerBase {
3033 SmallVector<SUnit*, 8> BotRoots;
3035 PostGenericScheduler(const MachineSchedContext *C):
3036 GenericSchedulerBase(C), Top(SchedBoundary::TopQID, "TopQ") {}
3038 virtual ~PostGenericScheduler() {}
3040 void initPolicy(MachineBasicBlock::iterator Begin,
3041 MachineBasicBlock::iterator End,
3042 unsigned NumRegionInstrs) override {
3043 /* no configurable policy */
3046 /// PostRA scheduling does not track pressure.
3047 bool shouldTrackPressure() const override { return false; }
3049 void initialize(ScheduleDAGMI *Dag) override {
3051 SchedModel = DAG->getSchedModel();
3054 Rem.init(DAG, SchedModel);
3055 Top.init(DAG, SchedModel, &Rem);
3058 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3059 // or are disabled, then these HazardRecs will be disabled.
3060 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
3061 const TargetMachine &TM = DAG->MF.getTarget();
3062 if (!Top.HazardRec) {
3064 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
3068 void registerRoots() override;
3070 SUnit *pickNode(bool &IsTopNode) override;
3072 void scheduleTree(unsigned SubtreeID) override {
3073 llvm_unreachable("PostRA scheduler does not support subtree analysis.");
3076 void schedNode(SUnit *SU, bool IsTopNode) override;
3078 void releaseTopNode(SUnit *SU) override {
3079 Top.releaseTopNode(SU);
3082 // Only called for roots.
3083 void releaseBottomNode(SUnit *SU) override {
3084 BotRoots.push_back(SU);
3088 void tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand);
3090 void pickNodeFromQueue(SchedCandidate &Cand);
3094 void PostGenericScheduler::registerRoots() {
3095 Rem.CriticalPath = DAG->ExitSU.getDepth();
3097 // Some roots may not feed into ExitSU. Check all of them in case.
3098 for (SmallVectorImpl<SUnit*>::const_iterator
3099 I = BotRoots.begin(), E = BotRoots.end(); I != E; ++I) {
3100 if ((*I)->getDepth() > Rem.CriticalPath)
3101 Rem.CriticalPath = (*I)->getDepth();
3103 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
3106 /// Apply a set of heursitics to a new candidate for PostRA scheduling.
3108 /// \param Cand provides the policy and current best candidate.
3109 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3110 void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3111 SchedCandidate &TryCand) {
3113 // Initialize the candidate if needed.
3114 if (!Cand.isValid()) {
3115 TryCand.Reason = NodeOrder;
3119 // Prioritize instructions that read unbuffered resources by stall cycles.
3120 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3121 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3124 // Avoid critical resource consumption and balance the schedule.
3125 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3126 TryCand, Cand, ResourceReduce))
3128 if (tryGreater(TryCand.ResDelta.DemandedResources,
3129 Cand.ResDelta.DemandedResources,
3130 TryCand, Cand, ResourceDemand))
3133 // Avoid serializing long latency dependence chains.
3134 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3138 // Fall through to original instruction order.
3139 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3140 TryCand.Reason = NodeOrder;
3143 void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3144 ReadyQueue &Q = Top.Available;
3148 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
3149 SchedCandidate TryCand(Cand.Policy);
3151 TryCand.initResourceDelta(DAG, SchedModel);
3152 tryCandidate(Cand, TryCand);
3153 if (TryCand.Reason != NoCand) {
3154 Cand.setBest(TryCand);
3155 DEBUG(traceCandidate(Cand));
3160 /// Pick the next node to schedule.
3161 SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3162 if (DAG->top() == DAG->bottom()) {
3163 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
3168 SU = Top.pickOnlyChoice();
3170 CandPolicy NoPolicy;
3171 SchedCandidate TopCand(NoPolicy);
3172 // Set the top-down policy based on the state of the current top zone and
3173 // the instructions outside the zone, including the bottom zone.
3174 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, NULL);
3175 pickNodeFromQueue(TopCand);
3176 assert(TopCand.Reason != NoCand && "failed to find a candidate");
3177 tracePick(TopCand, true);
3180 } while (SU->isScheduled);
3183 Top.removeReady(SU);
3185 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
3189 /// Called after ScheduleDAGMI has scheduled an instruction and updated
3190 /// scheduled/remaining flags in the DAG nodes.
3191 void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3192 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3196 /// Create a generic scheduler with no vreg liveness or DAG mutation passes.
3197 static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C) {
3198 return new ScheduleDAGMI(C, new PostGenericScheduler(C), /*IsPostRA=*/true);
3201 //===----------------------------------------------------------------------===//
3202 // ILP Scheduler. Currently for experimental analysis of heuristics.
3203 //===----------------------------------------------------------------------===//
3206 /// \brief Order nodes by the ILP metric.
3208 const SchedDFSResult *DFSResult;
3209 const BitVector *ScheduledTrees;
3212 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
3214 /// \brief Apply a less-than relation on node priority.
3216 /// (Return true if A comes after B in the Q.)
3217 bool operator()(const SUnit *A, const SUnit *B) const {
3218 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3219 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3220 if (SchedTreeA != SchedTreeB) {
3221 // Unscheduled trees have lower priority.
3222 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3223 return ScheduledTrees->test(SchedTreeB);
3225 // Trees with shallower connections have have lower priority.
3226 if (DFSResult->getSubtreeLevel(SchedTreeA)
3227 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3228 return DFSResult->getSubtreeLevel(SchedTreeA)
3229 < DFSResult->getSubtreeLevel(SchedTreeB);
3233 return DFSResult->getILP(A) < DFSResult->getILP(B);
3235 return DFSResult->getILP(A) > DFSResult->getILP(B);
3239 /// \brief Schedule based on the ILP metric.
3240 class ILPScheduler : public MachineSchedStrategy {
3241 ScheduleDAGMILive *DAG;
3244 std::vector<SUnit*> ReadyQ;
3246 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
3248 void initialize(ScheduleDAGMI *dag) override {
3249 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3250 DAG = static_cast<ScheduleDAGMILive*>(dag);
3251 DAG->computeDFSResult();
3252 Cmp.DFSResult = DAG->getDFSResult();
3253 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
3257 void registerRoots() override {
3258 // Restore the heap in ReadyQ with the updated DFS results.
3259 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3262 /// Implement MachineSchedStrategy interface.
3263 /// -----------------------------------------
3265 /// Callback to select the highest priority node from the ready Q.
3266 SUnit *pickNode(bool &IsTopNode) override {
3267 if (ReadyQ.empty()) return NULL;
3268 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3269 SUnit *SU = ReadyQ.back();
3272 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
3273 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3274 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3275 << DAG->getDFSResult()->getSubtreeLevel(
3276 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3277 << "Scheduling " << *SU->getInstr());
3281 /// \brief Scheduler callback to notify that a new subtree is scheduled.
3282 void scheduleTree(unsigned SubtreeID) override {
3283 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3286 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3287 /// DFSResults, and resort the priority Q.
3288 void schedNode(SUnit *SU, bool IsTopNode) override {
3289 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
3292 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
3294 void releaseBottomNode(SUnit *SU) override {
3295 ReadyQ.push_back(SU);
3296 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3301 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
3302 return new ScheduleDAGMILive(C, new ILPScheduler(true));
3304 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
3305 return new ScheduleDAGMILive(C, new ILPScheduler(false));
3307 static MachineSchedRegistry ILPMaxRegistry(
3308 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3309 static MachineSchedRegistry ILPMinRegistry(
3310 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3312 //===----------------------------------------------------------------------===//
3313 // Machine Instruction Shuffler for Correctness Testing
3314 //===----------------------------------------------------------------------===//
3318 /// Apply a less-than relation on the node order, which corresponds to the
3319 /// instruction order prior to scheduling. IsReverse implements greater-than.
3320 template<bool IsReverse>
3322 bool operator()(SUnit *A, SUnit *B) const {
3324 return A->NodeNum > B->NodeNum;
3326 return A->NodeNum < B->NodeNum;
3330 /// Reorder instructions as much as possible.
3331 class InstructionShuffler : public MachineSchedStrategy {
3335 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3336 // gives nodes with a higher number higher priority causing the latest
3337 // instructions to be scheduled first.
3338 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
3340 // When scheduling bottom-up, use greater-than as the queue priority.
3341 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
3344 InstructionShuffler(bool alternate, bool topdown)
3345 : IsAlternating(alternate), IsTopDown(topdown) {}
3347 virtual void initialize(ScheduleDAGMI*) {
3352 /// Implement MachineSchedStrategy interface.
3353 /// -----------------------------------------
3355 virtual SUnit *pickNode(bool &IsTopNode) {
3359 if (TopQ.empty()) return NULL;
3362 } while (SU->isScheduled);
3367 if (BottomQ.empty()) return NULL;
3370 } while (SU->isScheduled);
3374 IsTopDown = !IsTopDown;
3378 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
3380 virtual void releaseTopNode(SUnit *SU) {
3383 virtual void releaseBottomNode(SUnit *SU) {
3389 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
3390 bool Alternate = !ForceTopDown && !ForceBottomUp;
3391 bool TopDown = !ForceBottomUp;
3392 assert((TopDown || !ForceTopDown) &&
3393 "-misched-topdown incompatible with -misched-bottomup");
3394 return new ScheduleDAGMILive(C, new InstructionShuffler(Alternate, TopDown));
3396 static MachineSchedRegistry ShufflerRegistry(
3397 "shuffle", "Shuffle machine instructions alternating directions",
3398 createInstructionShuffler);
3401 //===----------------------------------------------------------------------===//
3402 // GraphWriter support for ScheduleDAGMILive.
3403 //===----------------------------------------------------------------------===//
3408 template<> struct GraphTraits<
3409 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3412 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
3414 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3416 static std::string getGraphName(const ScheduleDAG *G) {
3417 return G->MF.getName();
3420 static bool renderGraphFromBottomUp() {
3424 static bool isNodeHidden(const SUnit *Node) {
3425 return (Node->Preds.size() > 10 || Node->Succs.size() > 10);
3428 static bool hasNodeAddressLabel(const SUnit *Node,
3429 const ScheduleDAG *Graph) {
3433 /// If you want to override the dot attributes printed for a particular
3434 /// edge, override this method.
3435 static std::string getEdgeAttributes(const SUnit *Node,
3437 const ScheduleDAG *Graph) {
3438 if (EI.isArtificialDep())
3439 return "color=cyan,style=dashed";
3441 return "color=blue,style=dashed";
3445 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
3447 raw_string_ostream SS(Str);
3448 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3449 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3450 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : 0;
3451 SS << "SU:" << SU->NodeNum;
3453 SS << " I:" << DFS->getNumInstrs(SU);
3456 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3457 return G->getGraphNodeLabel(SU);
3460 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
3461 std::string Str("shape=Mrecord");
3462 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3463 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3464 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : 0;
3466 Str += ",style=filled,fillcolor=\"#";
3467 Str += DOT::getColorString(DFS->getSubtreeID(N));
3476 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3477 /// rendered using 'dot'.
3479 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3481 ViewGraph(this, Name, false, Title);
3483 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3484 << "systems with Graphviz or gv!\n";
3488 /// Out-of-line implementation with no arguments is handy for gdb.
3489 void ScheduleDAGMI::viewGraph() {
3490 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());