xref: /llvm-project/llvm/lib/CodeGen/MachineScheduler.cpp (revision 94edf029238d6e30d6946c7748b0edc785518607)
1 //===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // MachineScheduler schedules machine instructions after phi elimination. It
11 // preserves LiveIntervals so it can be invoked before register allocation.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/CodeGen/MachineScheduler.h"
16 #include "llvm/ADT/PriorityQueue.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/MachineDominators.h"
20 #include "llvm/CodeGen/MachineLoopInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/RegisterClassInfo.h"
24 #include "llvm/CodeGen/ScheduleDFS.h"
25 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/GraphWriter.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 
34 using namespace llvm;
35 
36 #define DEBUG_TYPE "misched"
37 
38 namespace llvm {
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"));
43 cl::opt<bool>
44 DumpCriticalPathLength("misched-dcpl", cl::Hidden,
45                        cl::desc("Print critical path length to stdout"));
46 }
47 
48 #ifndef NDEBUG
49 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
50   cl::desc("Pop up a window to show MISched dags after they are processed"));
51 
52 /// In some situations a few uninteresting nodes depend on nearly all other
53 /// nodes in the graph, provide a cutoff to hide them.
54 static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden,
55   cl::desc("Hide nodes with more predecessor/successor than cutoff"));
56 
57 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
58   cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
59 
60 static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
61   cl::desc("Only schedule this function"));
62 static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
63   cl::desc("Only schedule this MBB#"));
64 #else
65 static bool ViewMISchedDAGs = false;
66 #endif // NDEBUG
67 
68 /// Avoid quadratic complexity in unusually large basic blocks by limiting the
69 /// size of the ready lists.
70 static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden,
71   cl::desc("Limit ready list to N instructions"), cl::init(256));
72 
73 static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
74   cl::desc("Enable register pressure scheduling."), cl::init(true));
75 
76 static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
77   cl::desc("Enable cyclic critical path analysis."), cl::init(true));
78 
79 static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden,
80                                         cl::desc("Enable memop clustering."),
81                                         cl::init(true));
82 
83 static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
84   cl::desc("Verify machine instrs before and after machine scheduling"));
85 
86 // DAG subtrees must have at least this many nodes.
87 static const unsigned MinSubtreeSize = 8;
88 
89 // Pin the vtables to this file.
90 void MachineSchedStrategy::anchor() {}
91 void ScheduleDAGMutation::anchor() {}
92 
93 //===----------------------------------------------------------------------===//
94 // Machine Instruction Scheduling Pass and Registry
95 //===----------------------------------------------------------------------===//
96 
97 MachineSchedContext::MachineSchedContext():
98     MF(nullptr), MLI(nullptr), MDT(nullptr), PassConfig(nullptr), AA(nullptr), LIS(nullptr) {
99   RegClassInfo = new RegisterClassInfo();
100 }
101 
102 MachineSchedContext::~MachineSchedContext() {
103   delete RegClassInfo;
104 }
105 
106 namespace {
107 /// Base class for a machine scheduler class that can run at any point.
108 class MachineSchedulerBase : public MachineSchedContext,
109                              public MachineFunctionPass {
110 public:
111   MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
112 
113   void print(raw_ostream &O, const Module* = nullptr) const override;
114 
115 protected:
116   void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags);
117 };
118 
119 /// MachineScheduler runs after coalescing and before register allocation.
120 class MachineScheduler : public MachineSchedulerBase {
121 public:
122   MachineScheduler();
123 
124   void getAnalysisUsage(AnalysisUsage &AU) const override;
125 
126   bool runOnMachineFunction(MachineFunction&) override;
127 
128   static char ID; // Class identification, replacement for typeinfo
129 
130 protected:
131   ScheduleDAGInstrs *createMachineScheduler();
132 };
133 
134 /// PostMachineScheduler runs after shortly before code emission.
135 class PostMachineScheduler : public MachineSchedulerBase {
136 public:
137   PostMachineScheduler();
138 
139   void getAnalysisUsage(AnalysisUsage &AU) const override;
140 
141   bool runOnMachineFunction(MachineFunction&) override;
142 
143   static char ID; // Class identification, replacement for typeinfo
144 
145 protected:
146   ScheduleDAGInstrs *createPostMachineScheduler();
147 };
148 } // namespace
149 
150 char MachineScheduler::ID = 0;
151 
152 char &llvm::MachineSchedulerID = MachineScheduler::ID;
153 
154 INITIALIZE_PASS_BEGIN(MachineScheduler, "machine-scheduler",
155                       "Machine Instruction Scheduler", false, false)
156 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
157 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
158 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
159 INITIALIZE_PASS_END(MachineScheduler, "machine-scheduler",
160                     "Machine Instruction Scheduler", false, false)
161 
162 MachineScheduler::MachineScheduler()
163 : MachineSchedulerBase(ID) {
164   initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
165 }
166 
167 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
168   AU.setPreservesCFG();
169   AU.addRequiredID(MachineDominatorsID);
170   AU.addRequired<MachineLoopInfo>();
171   AU.addRequired<AAResultsWrapperPass>();
172   AU.addRequired<TargetPassConfig>();
173   AU.addRequired<SlotIndexes>();
174   AU.addPreserved<SlotIndexes>();
175   AU.addRequired<LiveIntervals>();
176   AU.addPreserved<LiveIntervals>();
177   MachineFunctionPass::getAnalysisUsage(AU);
178 }
179 
180 char PostMachineScheduler::ID = 0;
181 
182 char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
183 
184 INITIALIZE_PASS(PostMachineScheduler, "postmisched",
185                 "PostRA Machine Instruction Scheduler", false, false)
186 
187 PostMachineScheduler::PostMachineScheduler()
188 : MachineSchedulerBase(ID) {
189   initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
190 }
191 
192 void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
193   AU.setPreservesCFG();
194   AU.addRequiredID(MachineDominatorsID);
195   AU.addRequired<MachineLoopInfo>();
196   AU.addRequired<TargetPassConfig>();
197   MachineFunctionPass::getAnalysisUsage(AU);
198 }
199 
200 MachinePassRegistry MachineSchedRegistry::Registry;
201 
202 /// A dummy default scheduler factory indicates whether the scheduler
203 /// is overridden on the command line.
204 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
205   return nullptr;
206 }
207 
208 /// MachineSchedOpt allows command line selection of the scheduler.
209 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
210                RegisterPassParser<MachineSchedRegistry> >
211 MachineSchedOpt("misched",
212                 cl::init(&useDefaultMachineSched), cl::Hidden,
213                 cl::desc("Machine instruction scheduler to use"));
214 
215 static MachineSchedRegistry
216 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
217                      useDefaultMachineSched);
218 
219 static cl::opt<bool> EnableMachineSched(
220     "enable-misched",
221     cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
222     cl::Hidden);
223 
224 static cl::opt<bool> EnablePostRAMachineSched(
225     "enable-post-misched",
226     cl::desc("Enable the post-ra machine instruction scheduling pass."),
227     cl::init(true), cl::Hidden);
228 
229 /// Decrement this iterator until reaching the top or a non-debug instr.
230 static MachineBasicBlock::const_iterator
231 priorNonDebug(MachineBasicBlock::const_iterator I,
232               MachineBasicBlock::const_iterator Beg) {
233   assert(I != Beg && "reached the top of the region, cannot decrement");
234   while (--I != Beg) {
235     if (!I->isDebugValue())
236       break;
237   }
238   return I;
239 }
240 
241 /// Non-const version.
242 static MachineBasicBlock::iterator
243 priorNonDebug(MachineBasicBlock::iterator I,
244               MachineBasicBlock::const_iterator Beg) {
245   return priorNonDebug(MachineBasicBlock::const_iterator(I), Beg)
246       .getNonConstIterator();
247 }
248 
249 /// If this iterator is a debug value, increment until reaching the End or a
250 /// non-debug instruction.
251 static MachineBasicBlock::const_iterator
252 nextIfDebug(MachineBasicBlock::const_iterator I,
253             MachineBasicBlock::const_iterator End) {
254   for(; I != End; ++I) {
255     if (!I->isDebugValue())
256       break;
257   }
258   return I;
259 }
260 
261 /// Non-const version.
262 static MachineBasicBlock::iterator
263 nextIfDebug(MachineBasicBlock::iterator I,
264             MachineBasicBlock::const_iterator End) {
265   return nextIfDebug(MachineBasicBlock::const_iterator(I), End)
266       .getNonConstIterator();
267 }
268 
269 /// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
270 ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
271   // Select the scheduler, or set the default.
272   MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
273   if (Ctor != useDefaultMachineSched)
274     return Ctor(this);
275 
276   // Get the default scheduler set by the target for this function.
277   ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
278   if (Scheduler)
279     return Scheduler;
280 
281   // Default to GenericScheduler.
282   return createGenericSchedLive(this);
283 }
284 
285 /// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
286 /// the caller. We don't have a command line option to override the postRA
287 /// scheduler. The Target must configure it.
288 ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
289   // Get the postRA scheduler set by the target for this function.
290   ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
291   if (Scheduler)
292     return Scheduler;
293 
294   // Default to GenericScheduler.
295   return createGenericSchedPostRA(this);
296 }
297 
298 /// Top-level MachineScheduler pass driver.
299 ///
300 /// Visit blocks in function order. Divide each block into scheduling regions
301 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
302 /// consistent with the DAG builder, which traverses the interior of the
303 /// scheduling regions bottom-up.
304 ///
305 /// This design avoids exposing scheduling boundaries to the DAG builder,
306 /// simplifying the DAG builder's support for "special" target instructions.
307 /// At the same time the design allows target schedulers to operate across
308 /// scheduling boundaries, for example to bundle the boudary instructions
309 /// without reordering them. This creates complexity, because the target
310 /// scheduler must update the RegionBegin and RegionEnd positions cached by
311 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
312 /// design would be to split blocks at scheduling boundaries, but LLVM has a
313 /// general bias against block splitting purely for implementation simplicity.
314 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
315   if (skipFunction(*mf.getFunction()))
316     return false;
317 
318   if (EnableMachineSched.getNumOccurrences()) {
319     if (!EnableMachineSched)
320       return false;
321   } else if (!mf.getSubtarget().enableMachineScheduler())
322     return false;
323 
324   DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
325 
326   // Initialize the context of the pass.
327   MF = &mf;
328   MLI = &getAnalysis<MachineLoopInfo>();
329   MDT = &getAnalysis<MachineDominatorTree>();
330   PassConfig = &getAnalysis<TargetPassConfig>();
331   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
332 
333   LIS = &getAnalysis<LiveIntervals>();
334 
335   if (VerifyScheduling) {
336     DEBUG(LIS->dump());
337     MF->verify(this, "Before machine scheduling.");
338   }
339   RegClassInfo->runOnMachineFunction(*MF);
340 
341   // Instantiate the selected scheduler for this target, function, and
342   // optimization level.
343   std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
344   scheduleRegions(*Scheduler, false);
345 
346   DEBUG(LIS->dump());
347   if (VerifyScheduling)
348     MF->verify(this, "After machine scheduling.");
349   return true;
350 }
351 
352 bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
353   if (skipFunction(*mf.getFunction()))
354     return false;
355 
356   if (EnablePostRAMachineSched.getNumOccurrences()) {
357     if (!EnablePostRAMachineSched)
358       return false;
359   } else if (!mf.getSubtarget().enablePostRAScheduler()) {
360     DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
361     return false;
362   }
363   DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
364 
365   // Initialize the context of the pass.
366   MF = &mf;
367   PassConfig = &getAnalysis<TargetPassConfig>();
368 
369   if (VerifyScheduling)
370     MF->verify(this, "Before post machine scheduling.");
371 
372   // Instantiate the selected scheduler for this target, function, and
373   // optimization level.
374   std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
375   scheduleRegions(*Scheduler, true);
376 
377   if (VerifyScheduling)
378     MF->verify(this, "After post machine scheduling.");
379   return true;
380 }
381 
382 /// Return true of the given instruction should not be included in a scheduling
383 /// region.
384 ///
385 /// MachineScheduler does not currently support scheduling across calls. To
386 /// handle calls, the DAG builder needs to be modified to create register
387 /// anti/output dependencies on the registers clobbered by the call's regmask
388 /// operand. In PreRA scheduling, the stack pointer adjustment already prevents
389 /// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
390 /// the boundary, but there would be no benefit to postRA scheduling across
391 /// calls this late anyway.
392 static bool isSchedBoundary(MachineBasicBlock::iterator MI,
393                             MachineBasicBlock *MBB,
394                             MachineFunction *MF,
395                             const TargetInstrInfo *TII) {
396   return MI->isCall() || TII->isSchedulingBoundary(*MI, MBB, *MF);
397 }
398 
399 /// Main driver for both MachineScheduler and PostMachineScheduler.
400 void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
401                                            bool FixKillFlags) {
402   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
403 
404   // Visit all machine basic blocks.
405   //
406   // TODO: Visit blocks in global postorder or postorder within the bottom-up
407   // loop tree. Then we can optionally compute global RegPressure.
408   for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
409        MBB != MBBEnd; ++MBB) {
410 
411     Scheduler.startBlock(&*MBB);
412 
413 #ifndef NDEBUG
414     if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
415       continue;
416     if (SchedOnlyBlock.getNumOccurrences()
417         && (int)SchedOnlyBlock != MBB->getNumber())
418       continue;
419 #endif
420 
421     // Break the block into scheduling regions [I, RegionEnd), and schedule each
422     // region as soon as it is discovered. RegionEnd points the scheduling
423     // boundary at the bottom of the region. The DAG does not include RegionEnd,
424     // but the region does (i.e. the next RegionEnd is above the previous
425     // RegionBegin). If the current block has no terminator then RegionEnd ==
426     // MBB->end() for the bottom region.
427     //
428     // The Scheduler may insert instructions during either schedule() or
429     // exitRegion(), even for empty regions. So the local iterators 'I' and
430     // 'RegionEnd' are invalid across these calls.
431     //
432     // MBB::size() uses instr_iterator to count. Here we need a bundle to count
433     // as a single instruction.
434     for(MachineBasicBlock::iterator RegionEnd = MBB->end();
435         RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
436 
437       // Avoid decrementing RegionEnd for blocks with no terminator.
438       if (RegionEnd != MBB->end() ||
439           isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
440         --RegionEnd;
441       }
442 
443       // The next region starts above the previous region. Look backward in the
444       // instruction stream until we find the nearest boundary.
445       unsigned NumRegionInstrs = 0;
446       MachineBasicBlock::iterator I = RegionEnd;
447       for (;I != MBB->begin(); --I) {
448         MachineInstr &MI = *std::prev(I);
449         if (isSchedBoundary(&MI, &*MBB, MF, TII))
450           break;
451         if (!MI.isDebugValue())
452           ++NumRegionInstrs;
453       }
454       // Notify the scheduler of the region, even if we may skip scheduling
455       // it. Perhaps it still needs to be bundled.
456       Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
457 
458       // Skip empty scheduling regions (0 or 1 schedulable instructions).
459       if (I == RegionEnd || I == std::prev(RegionEnd)) {
460         // Close the current region. Bundle the terminator if needed.
461         // This invalidates 'RegionEnd' and 'I'.
462         Scheduler.exitRegion();
463         continue;
464       }
465       DEBUG(dbgs() << "********** MI Scheduling **********\n");
466       DEBUG(dbgs() << MF->getName()
467             << ":BB#" << MBB->getNumber() << " " << MBB->getName()
468             << "\n  From: " << *I << "    To: ";
469             if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
470             else dbgs() << "End";
471             dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
472       if (DumpCriticalPathLength) {
473         errs() << MF->getName();
474         errs() << ":BB# " << MBB->getNumber();
475         errs() << " " << MBB->getName() << " \n";
476       }
477 
478       // Schedule a region: possibly reorder instructions.
479       // This invalidates 'RegionEnd' and 'I'.
480       Scheduler.schedule();
481 
482       // Close the current region.
483       Scheduler.exitRegion();
484 
485       // Scheduling has invalidated the current iterator 'I'. Ask the
486       // scheduler for the top of it's scheduled region.
487       RegionEnd = Scheduler.begin();
488     }
489     Scheduler.finishBlock();
490     // FIXME: Ideally, no further passes should rely on kill flags. However,
491     // thumb2 size reduction is currently an exception, so the PostMIScheduler
492     // needs to do this.
493     if (FixKillFlags)
494         Scheduler.fixupKills(&*MBB);
495   }
496   Scheduler.finalizeSchedule();
497 }
498 
499 void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
500   // unimplemented
501 }
502 
503 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
504 LLVM_DUMP_METHOD void ReadyQueue::dump() {
505   dbgs() << "Queue " << Name << ": ";
506   for (unsigned i = 0, e = Queue.size(); i < e; ++i)
507     dbgs() << Queue[i]->NodeNum << " ";
508   dbgs() << "\n";
509 }
510 #endif
511 
512 //===----------------------------------------------------------------------===//
513 // ScheduleDAGMI - Basic machine instruction scheduling. This is
514 // independent of PreRA/PostRA scheduling and involves no extra book-keeping for
515 // virtual registers.
516 // ===----------------------------------------------------------------------===/
517 
518 // Provide a vtable anchor.
519 ScheduleDAGMI::~ScheduleDAGMI() {
520 }
521 
522 bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
523   return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
524 }
525 
526 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
527   if (SuccSU != &ExitSU) {
528     // Do not use WillCreateCycle, it assumes SD scheduling.
529     // If Pred is reachable from Succ, then the edge creates a cycle.
530     if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
531       return false;
532     Topo.AddPred(SuccSU, PredDep.getSUnit());
533   }
534   SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
535   // Return true regardless of whether a new edge needed to be inserted.
536   return true;
537 }
538 
539 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
540 /// NumPredsLeft reaches zero, release the successor node.
541 ///
542 /// FIXME: Adjust SuccSU height based on MinLatency.
543 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
544   SUnit *SuccSU = SuccEdge->getSUnit();
545 
546   if (SuccEdge->isWeak()) {
547     --SuccSU->WeakPredsLeft;
548     if (SuccEdge->isCluster())
549       NextClusterSucc = SuccSU;
550     return;
551   }
552 #ifndef NDEBUG
553   if (SuccSU->NumPredsLeft == 0) {
554     dbgs() << "*** Scheduling failed! ***\n";
555     SuccSU->dump(this);
556     dbgs() << " has been released too many times!\n";
557     llvm_unreachable(nullptr);
558   }
559 #endif
560   // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
561   // CurrCycle may have advanced since then.
562   if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
563     SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
564 
565   --SuccSU->NumPredsLeft;
566   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
567     SchedImpl->releaseTopNode(SuccSU);
568 }
569 
570 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
571 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
572   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
573        I != E; ++I) {
574     releaseSucc(SU, &*I);
575   }
576 }
577 
578 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
579 /// NumSuccsLeft reaches zero, release the predecessor node.
580 ///
581 /// FIXME: Adjust PredSU height based on MinLatency.
582 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
583   SUnit *PredSU = PredEdge->getSUnit();
584 
585   if (PredEdge->isWeak()) {
586     --PredSU->WeakSuccsLeft;
587     if (PredEdge->isCluster())
588       NextClusterPred = PredSU;
589     return;
590   }
591 #ifndef NDEBUG
592   if (PredSU->NumSuccsLeft == 0) {
593     dbgs() << "*** Scheduling failed! ***\n";
594     PredSU->dump(this);
595     dbgs() << " has been released too many times!\n";
596     llvm_unreachable(nullptr);
597   }
598 #endif
599   // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
600   // CurrCycle may have advanced since then.
601   if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
602     PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
603 
604   --PredSU->NumSuccsLeft;
605   if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
606     SchedImpl->releaseBottomNode(PredSU);
607 }
608 
609 /// releasePredecessors - Call releasePred on each of SU's predecessors.
610 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
611   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
612        I != E; ++I) {
613     releasePred(SU, &*I);
614   }
615 }
616 
617 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
618 /// crossing a scheduling boundary. [begin, end) includes all instructions in
619 /// the region, including the boundary itself and single-instruction regions
620 /// that don't get scheduled.
621 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
622                                      MachineBasicBlock::iterator begin,
623                                      MachineBasicBlock::iterator end,
624                                      unsigned regioninstrs)
625 {
626   ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
627 
628   SchedImpl->initPolicy(begin, end, regioninstrs);
629 }
630 
631 /// This is normally called from the main scheduler loop but may also be invoked
632 /// by the scheduling strategy to perform additional code motion.
633 void ScheduleDAGMI::moveInstruction(
634   MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
635   // Advance RegionBegin if the first instruction moves down.
636   if (&*RegionBegin == MI)
637     ++RegionBegin;
638 
639   // Update the instruction stream.
640   BB->splice(InsertPos, BB, MI);
641 
642   // Update LiveIntervals
643   if (LIS)
644     LIS->handleMove(*MI, /*UpdateFlags=*/true);
645 
646   // Recede RegionBegin if an instruction moves above the first.
647   if (RegionBegin == InsertPos)
648     RegionBegin = MI;
649 }
650 
651 bool ScheduleDAGMI::checkSchedLimit() {
652 #ifndef NDEBUG
653   if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
654     CurrentTop = CurrentBottom;
655     return false;
656   }
657   ++NumInstrsScheduled;
658 #endif
659   return true;
660 }
661 
662 /// Per-region scheduling driver, called back from
663 /// MachineScheduler::runOnMachineFunction. This is a simplified driver that
664 /// does not consider liveness or register pressure. It is useful for PostRA
665 /// scheduling and potentially other custom schedulers.
666 void ScheduleDAGMI::schedule() {
667   DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
668   DEBUG(SchedImpl->dumpPolicy());
669 
670   // Build the DAG.
671   buildSchedGraph(AA);
672 
673   Topo.InitDAGTopologicalSorting();
674 
675   postprocessDAG();
676 
677   SmallVector<SUnit*, 8> TopRoots, BotRoots;
678   findRootsAndBiasEdges(TopRoots, BotRoots);
679 
680   // Initialize the strategy before modifying the DAG.
681   // This may initialize a DFSResult to be used for queue priority.
682   SchedImpl->initialize(this);
683 
684   DEBUG(
685     if (EntrySU.getInstr() != nullptr)
686       EntrySU.dumpAll(this);
687     for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
688       SUnits[su].dumpAll(this);
689     if (ExitSU.getInstr() != nullptr)
690       ExitSU.dumpAll(this);
691   );
692   if (ViewMISchedDAGs) viewGraph();
693 
694   // Initialize ready queues now that the DAG and priority data are finalized.
695   initQueues(TopRoots, BotRoots);
696 
697   bool IsTopNode = false;
698   while (true) {
699     DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
700     SUnit *SU = SchedImpl->pickNode(IsTopNode);
701     if (!SU) break;
702 
703     assert(!SU->isScheduled && "Node already scheduled");
704     if (!checkSchedLimit())
705       break;
706 
707     MachineInstr *MI = SU->getInstr();
708     if (IsTopNode) {
709       assert(SU->isTopReady() && "node still has unscheduled dependencies");
710       if (&*CurrentTop == MI)
711         CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
712       else
713         moveInstruction(MI, CurrentTop);
714     } else {
715       assert(SU->isBottomReady() && "node still has unscheduled dependencies");
716       MachineBasicBlock::iterator priorII =
717         priorNonDebug(CurrentBottom, CurrentTop);
718       if (&*priorII == MI)
719         CurrentBottom = priorII;
720       else {
721         if (&*CurrentTop == MI)
722           CurrentTop = nextIfDebug(++CurrentTop, priorII);
723         moveInstruction(MI, CurrentBottom);
724         CurrentBottom = MI;
725       }
726     }
727     // Notify the scheduling strategy before updating the DAG.
728     // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
729     // runs, it can then use the accurate ReadyCycle time to determine whether
730     // newly released nodes can move to the readyQ.
731     SchedImpl->schedNode(SU, IsTopNode);
732 
733     updateQueues(SU, IsTopNode);
734   }
735   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
736 
737   placeDebugValues();
738 
739   DEBUG({
740       unsigned BBNum = begin()->getParent()->getNumber();
741       dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
742       dumpSchedule();
743       dbgs() << '\n';
744     });
745 }
746 
747 /// Apply each ScheduleDAGMutation step in order.
748 void ScheduleDAGMI::postprocessDAG() {
749   for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
750     Mutations[i]->apply(this);
751   }
752 }
753 
754 void ScheduleDAGMI::
755 findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
756                       SmallVectorImpl<SUnit*> &BotRoots) {
757   for (std::vector<SUnit>::iterator
758          I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
759     SUnit *SU = &(*I);
760     assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
761 
762     // Order predecessors so DFSResult follows the critical path.
763     SU->biasCriticalPath();
764 
765     // A SUnit is ready to top schedule if it has no predecessors.
766     if (!I->NumPredsLeft)
767       TopRoots.push_back(SU);
768     // A SUnit is ready to bottom schedule if it has no successors.
769     if (!I->NumSuccsLeft)
770       BotRoots.push_back(SU);
771   }
772   ExitSU.biasCriticalPath();
773 }
774 
775 /// Identify DAG roots and setup scheduler queues.
776 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
777                                ArrayRef<SUnit*> BotRoots) {
778   NextClusterSucc = nullptr;
779   NextClusterPred = nullptr;
780 
781   // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
782   //
783   // Nodes with unreleased weak edges can still be roots.
784   // Release top roots in forward order.
785   for (SmallVectorImpl<SUnit*>::const_iterator
786          I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
787     SchedImpl->releaseTopNode(*I);
788   }
789   // Release bottom roots in reverse order so the higher priority nodes appear
790   // first. This is more natural and slightly more efficient.
791   for (SmallVectorImpl<SUnit*>::const_reverse_iterator
792          I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
793     SchedImpl->releaseBottomNode(*I);
794   }
795 
796   releaseSuccessors(&EntrySU);
797   releasePredecessors(&ExitSU);
798 
799   SchedImpl->registerRoots();
800 
801   // Advance past initial DebugValues.
802   CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
803   CurrentBottom = RegionEnd;
804 }
805 
806 /// Update scheduler queues after scheduling an instruction.
807 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
808   // Release dependent instructions for scheduling.
809   if (IsTopNode)
810     releaseSuccessors(SU);
811   else
812     releasePredecessors(SU);
813 
814   SU->isScheduled = true;
815 }
816 
817 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
818 void ScheduleDAGMI::placeDebugValues() {
819   // If first instruction was a DBG_VALUE then put it back.
820   if (FirstDbgValue) {
821     BB->splice(RegionBegin, BB, FirstDbgValue);
822     RegionBegin = FirstDbgValue;
823   }
824 
825   for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
826          DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
827     std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
828     MachineInstr *DbgValue = P.first;
829     MachineBasicBlock::iterator OrigPrevMI = P.second;
830     if (&*RegionBegin == DbgValue)
831       ++RegionBegin;
832     BB->splice(++OrigPrevMI, BB, DbgValue);
833     if (OrigPrevMI == std::prev(RegionEnd))
834       RegionEnd = DbgValue;
835   }
836   DbgValues.clear();
837   FirstDbgValue = nullptr;
838 }
839 
840 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
841 LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
842   for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
843     if (SUnit *SU = getSUnit(&(*MI)))
844       SU->dump(this);
845     else
846       dbgs() << "Missing SUnit\n";
847   }
848 }
849 #endif
850 
851 //===----------------------------------------------------------------------===//
852 // ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
853 // preservation.
854 //===----------------------------------------------------------------------===//
855 
856 ScheduleDAGMILive::~ScheduleDAGMILive() {
857   delete DFSResult;
858 }
859 
860 void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
861   const MachineInstr &MI = *SU.getInstr();
862   for (const MachineOperand &MO : MI.operands()) {
863     if (!MO.isReg())
864       continue;
865     if (!MO.readsReg())
866       continue;
867     if (TrackLaneMasks && !MO.isUse())
868       continue;
869 
870     unsigned Reg = MO.getReg();
871     if (!TargetRegisterInfo::isVirtualRegister(Reg))
872       continue;
873 
874     // Ignore re-defs.
875     if (TrackLaneMasks) {
876       bool FoundDef = false;
877       for (const MachineOperand &MO2 : MI.operands()) {
878         if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
879           FoundDef = true;
880           break;
881         }
882       }
883       if (FoundDef)
884         continue;
885     }
886 
887     // Record this local VReg use.
888     VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
889     for (; UI != VRegUses.end(); ++UI) {
890       if (UI->SU == &SU)
891         break;
892     }
893     if (UI == VRegUses.end())
894       VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
895   }
896 }
897 
898 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
899 /// crossing a scheduling boundary. [begin, end) includes all instructions in
900 /// the region, including the boundary itself and single-instruction regions
901 /// that don't get scheduled.
902 void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
903                                 MachineBasicBlock::iterator begin,
904                                 MachineBasicBlock::iterator end,
905                                 unsigned regioninstrs)
906 {
907   // ScheduleDAGMI initializes SchedImpl's per-region policy.
908   ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
909 
910   // For convenience remember the end of the liveness region.
911   LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
912 
913   SUPressureDiffs.clear();
914 
915   ShouldTrackPressure = SchedImpl->shouldTrackPressure();
916   ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
917 
918   assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
919          "ShouldTrackLaneMasks requires ShouldTrackPressure");
920 }
921 
922 // Setup the register pressure trackers for the top scheduled top and bottom
923 // scheduled regions.
924 void ScheduleDAGMILive::initRegPressure() {
925   VRegUses.clear();
926   VRegUses.setUniverse(MRI.getNumVirtRegs());
927   for (SUnit &SU : SUnits)
928     collectVRegUses(SU);
929 
930   TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
931                     ShouldTrackLaneMasks, false);
932   BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
933                     ShouldTrackLaneMasks, false);
934 
935   // Close the RPTracker to finalize live ins.
936   RPTracker.closeRegion();
937 
938   DEBUG(RPTracker.dump());
939 
940   // Initialize the live ins and live outs.
941   TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
942   BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
943 
944   // Close one end of the tracker so we can call
945   // getMaxUpward/DownwardPressureDelta before advancing across any
946   // instructions. This converts currently live regs into live ins/outs.
947   TopRPTracker.closeTop();
948   BotRPTracker.closeBottom();
949 
950   BotRPTracker.initLiveThru(RPTracker);
951   if (!BotRPTracker.getLiveThru().empty()) {
952     TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
953     DEBUG(dbgs() << "Live Thru: ";
954           dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
955   };
956 
957   // For each live out vreg reduce the pressure change associated with other
958   // uses of the same vreg below the live-out reaching def.
959   updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
960 
961   // Account for liveness generated by the region boundary.
962   if (LiveRegionEnd != RegionEnd) {
963     SmallVector<RegisterMaskPair, 8> LiveUses;
964     BotRPTracker.recede(&LiveUses);
965     updatePressureDiffs(LiveUses);
966   }
967 
968   DEBUG(
969     dbgs() << "Top Pressure:\n";
970     dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
971     dbgs() << "Bottom Pressure:\n";
972     dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
973   );
974 
975   assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
976 
977   // Cache the list of excess pressure sets in this region. This will also track
978   // the max pressure in the scheduled code for these sets.
979   RegionCriticalPSets.clear();
980   const std::vector<unsigned> &RegionPressure =
981     RPTracker.getPressure().MaxSetPressure;
982   for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
983     unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
984     if (RegionPressure[i] > Limit) {
985       DEBUG(dbgs() << TRI->getRegPressureSetName(i)
986             << " Limit " << Limit
987             << " Actual " << RegionPressure[i] << "\n");
988       RegionCriticalPSets.push_back(PressureChange(i));
989     }
990   }
991   DEBUG(dbgs() << "Excess PSets: ";
992         for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
993           dbgs() << TRI->getRegPressureSetName(
994             RegionCriticalPSets[i].getPSet()) << " ";
995         dbgs() << "\n");
996 }
997 
998 void ScheduleDAGMILive::
999 updateScheduledPressure(const SUnit *SU,
1000                         const std::vector<unsigned> &NewMaxPressure) {
1001   const PressureDiff &PDiff = getPressureDiff(SU);
1002   unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
1003   for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
1004        I != E; ++I) {
1005     if (!I->isValid())
1006       break;
1007     unsigned ID = I->getPSet();
1008     while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
1009       ++CritIdx;
1010     if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
1011       if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
1012           && NewMaxPressure[ID] <= INT16_MAX)
1013         RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
1014     }
1015     unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1016     if (NewMaxPressure[ID] >= Limit - 2) {
1017       DEBUG(dbgs() << "  " << TRI->getRegPressureSetName(ID) << ": "
1018             << NewMaxPressure[ID]
1019             << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ") << Limit
1020             << "(+ " << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
1021     }
1022   }
1023 }
1024 
1025 /// Update the PressureDiff array for liveness after scheduling this
1026 /// instruction.
1027 void ScheduleDAGMILive::updatePressureDiffs(
1028     ArrayRef<RegisterMaskPair> LiveUses) {
1029   for (const RegisterMaskPair &P : LiveUses) {
1030     unsigned Reg = P.RegUnit;
1031     /// FIXME: Currently assuming single-use physregs.
1032     if (!TRI->isVirtualRegister(Reg))
1033       continue;
1034 
1035     if (ShouldTrackLaneMasks) {
1036       // If the register has just become live then other uses won't change
1037       // this fact anymore => decrement pressure.
1038       // If the register has just become dead then other uses make it come
1039       // back to life => increment pressure.
1040       bool Decrement = P.LaneMask.any();
1041 
1042       for (const VReg2SUnit &V2SU
1043            : make_range(VRegUses.find(Reg), VRegUses.end())) {
1044         SUnit &SU = *V2SU.SU;
1045         if (SU.isScheduled || &SU == &ExitSU)
1046           continue;
1047 
1048         PressureDiff &PDiff = getPressureDiff(&SU);
1049         PDiff.addPressureChange(Reg, Decrement, &MRI);
1050         DEBUG(
1051           dbgs() << "  UpdateRegP: SU(" << SU.NodeNum << ") "
1052                  << PrintReg(Reg, TRI) << ':' << PrintLaneMask(P.LaneMask)
1053                  << ' ' << *SU.getInstr();
1054           dbgs() << "              to ";
1055           PDiff.dump(*TRI);
1056         );
1057       }
1058     } else {
1059       assert(P.LaneMask.any());
1060       DEBUG(dbgs() << "  LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
1061       // This may be called before CurrentBottom has been initialized. However,
1062       // BotRPTracker must have a valid position. We want the value live into the
1063       // instruction or live out of the block, so ask for the previous
1064       // instruction's live-out.
1065       const LiveInterval &LI = LIS->getInterval(Reg);
1066       VNInfo *VNI;
1067       MachineBasicBlock::const_iterator I =
1068         nextIfDebug(BotRPTracker.getPos(), BB->end());
1069       if (I == BB->end())
1070         VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1071       else {
1072         LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
1073         VNI = LRQ.valueIn();
1074       }
1075       // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1076       assert(VNI && "No live value at use.");
1077       for (const VReg2SUnit &V2SU
1078            : make_range(VRegUses.find(Reg), VRegUses.end())) {
1079         SUnit *SU = V2SU.SU;
1080         // If this use comes before the reaching def, it cannot be a last use,
1081         // so decrease its pressure change.
1082         if (!SU->isScheduled && SU != &ExitSU) {
1083           LiveQueryResult LRQ =
1084               LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
1085           if (LRQ.valueIn() == VNI) {
1086             PressureDiff &PDiff = getPressureDiff(SU);
1087             PDiff.addPressureChange(Reg, true, &MRI);
1088             DEBUG(
1089               dbgs() << "  UpdateRegP: SU(" << SU->NodeNum << ") "
1090                      << *SU->getInstr();
1091               dbgs() << "              to ";
1092               PDiff.dump(*TRI);
1093             );
1094           }
1095         }
1096       }
1097     }
1098   }
1099 }
1100 
1101 /// schedule - Called back from MachineScheduler::runOnMachineFunction
1102 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
1103 /// only includes instructions that have DAG nodes, not scheduling boundaries.
1104 ///
1105 /// This is a skeletal driver, with all the functionality pushed into helpers,
1106 /// so that it can be easily extended by experimental schedulers. Generally,
1107 /// implementing MachineSchedStrategy should be sufficient to implement a new
1108 /// scheduling algorithm. However, if a scheduler further subclasses
1109 /// ScheduleDAGMILive then it will want to override this virtual method in order
1110 /// to update any specialized state.
1111 void ScheduleDAGMILive::schedule() {
1112   DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
1113   DEBUG(SchedImpl->dumpPolicy());
1114   buildDAGWithRegPressure();
1115 
1116   Topo.InitDAGTopologicalSorting();
1117 
1118   postprocessDAG();
1119 
1120   SmallVector<SUnit*, 8> TopRoots, BotRoots;
1121   findRootsAndBiasEdges(TopRoots, BotRoots);
1122 
1123   // Initialize the strategy before modifying the DAG.
1124   // This may initialize a DFSResult to be used for queue priority.
1125   SchedImpl->initialize(this);
1126 
1127   DEBUG(
1128     if (EntrySU.getInstr() != nullptr)
1129       EntrySU.dumpAll(this);
1130     for (const SUnit &SU : SUnits) {
1131       SU.dumpAll(this);
1132       if (ShouldTrackPressure) {
1133         dbgs() << "  Pressure Diff      : ";
1134         getPressureDiff(&SU).dump(*TRI);
1135       }
1136       dbgs() << '\n';
1137     }
1138     if (ExitSU.getInstr() != nullptr)
1139       ExitSU.dumpAll(this);
1140   );
1141   if (ViewMISchedDAGs) viewGraph();
1142 
1143   // Initialize ready queues now that the DAG and priority data are finalized.
1144   initQueues(TopRoots, BotRoots);
1145 
1146   bool IsTopNode = false;
1147   while (true) {
1148     DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
1149     SUnit *SU = SchedImpl->pickNode(IsTopNode);
1150     if (!SU) break;
1151 
1152     assert(!SU->isScheduled && "Node already scheduled");
1153     if (!checkSchedLimit())
1154       break;
1155 
1156     scheduleMI(SU, IsTopNode);
1157 
1158     if (DFSResult) {
1159       unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1160       if (!ScheduledTrees.test(SubtreeID)) {
1161         ScheduledTrees.set(SubtreeID);
1162         DFSResult->scheduleTree(SubtreeID);
1163         SchedImpl->scheduleTree(SubtreeID);
1164       }
1165     }
1166 
1167     // Notify the scheduling strategy after updating the DAG.
1168     SchedImpl->schedNode(SU, IsTopNode);
1169 
1170     updateQueues(SU, IsTopNode);
1171   }
1172   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1173 
1174   placeDebugValues();
1175 
1176   DEBUG({
1177       unsigned BBNum = begin()->getParent()->getNumber();
1178       dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1179       dumpSchedule();
1180       dbgs() << '\n';
1181     });
1182 }
1183 
1184 /// Build the DAG and setup three register pressure trackers.
1185 void ScheduleDAGMILive::buildDAGWithRegPressure() {
1186   if (!ShouldTrackPressure) {
1187     RPTracker.reset();
1188     RegionCriticalPSets.clear();
1189     buildSchedGraph(AA);
1190     return;
1191   }
1192 
1193   // Initialize the register pressure tracker used by buildSchedGraph.
1194   RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1195                  ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
1196 
1197   // Account for liveness generate by the region boundary.
1198   if (LiveRegionEnd != RegionEnd)
1199     RPTracker.recede();
1200 
1201   // Build the DAG, and compute current register pressure.
1202   buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
1203 
1204   // Initialize top/bottom trackers after computing region pressure.
1205   initRegPressure();
1206 }
1207 
1208 void ScheduleDAGMILive::computeDFSResult() {
1209   if (!DFSResult)
1210     DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1211   DFSResult->clear();
1212   ScheduledTrees.clear();
1213   DFSResult->resize(SUnits.size());
1214   DFSResult->compute(SUnits);
1215   ScheduledTrees.resize(DFSResult->getNumSubtrees());
1216 }
1217 
1218 /// Compute the max cyclic critical path through the DAG. The scheduling DAG
1219 /// only provides the critical path for single block loops. To handle loops that
1220 /// span blocks, we could use the vreg path latencies provided by
1221 /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1222 /// available for use in the scheduler.
1223 ///
1224 /// The cyclic path estimation identifies a def-use pair that crosses the back
1225 /// edge and considers the depth and height of the nodes. For example, consider
1226 /// the following instruction sequence where each instruction has unit latency
1227 /// and defines an epomymous virtual register:
1228 ///
1229 /// a->b(a,c)->c(b)->d(c)->exit
1230 ///
1231 /// The cyclic critical path is a two cycles: b->c->b
1232 /// The acyclic critical path is four cycles: a->b->c->d->exit
1233 /// LiveOutHeight = height(c) = len(c->d->exit) = 2
1234 /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1235 /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1236 /// LiveInDepth = depth(b) = len(a->b) = 1
1237 ///
1238 /// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1239 /// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1240 /// CyclicCriticalPath = min(2, 2) = 2
1241 ///
1242 /// This could be relevant to PostRA scheduling, but is currently implemented
1243 /// assuming LiveIntervals.
1244 unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
1245   // This only applies to single block loop.
1246   if (!BB->isSuccessor(BB))
1247     return 0;
1248 
1249   unsigned MaxCyclicLatency = 0;
1250   // Visit each live out vreg def to find def/use pairs that cross iterations.
1251   for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
1252     unsigned Reg = P.RegUnit;
1253     if (!TRI->isVirtualRegister(Reg))
1254         continue;
1255     const LiveInterval &LI = LIS->getInterval(Reg);
1256     const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1257     if (!DefVNI)
1258       continue;
1259 
1260     MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1261     const SUnit *DefSU = getSUnit(DefMI);
1262     if (!DefSU)
1263       continue;
1264 
1265     unsigned LiveOutHeight = DefSU->getHeight();
1266     unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1267     // Visit all local users of the vreg def.
1268     for (const VReg2SUnit &V2SU
1269          : make_range(VRegUses.find(Reg), VRegUses.end())) {
1270       SUnit *SU = V2SU.SU;
1271       if (SU == &ExitSU)
1272         continue;
1273 
1274       // Only consider uses of the phi.
1275       LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
1276       if (!LRQ.valueIn()->isPHIDef())
1277         continue;
1278 
1279       // Assume that a path spanning two iterations is a cycle, which could
1280       // overestimate in strange cases. This allows cyclic latency to be
1281       // estimated as the minimum slack of the vreg's depth or height.
1282       unsigned CyclicLatency = 0;
1283       if (LiveOutDepth > SU->getDepth())
1284         CyclicLatency = LiveOutDepth - SU->getDepth();
1285 
1286       unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
1287       if (LiveInHeight > LiveOutHeight) {
1288         if (LiveInHeight - LiveOutHeight < CyclicLatency)
1289           CyclicLatency = LiveInHeight - LiveOutHeight;
1290       } else
1291         CyclicLatency = 0;
1292 
1293       DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1294             << SU->NodeNum << ") = " << CyclicLatency << "c\n");
1295       if (CyclicLatency > MaxCyclicLatency)
1296         MaxCyclicLatency = CyclicLatency;
1297     }
1298   }
1299   DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1300   return MaxCyclicLatency;
1301 }
1302 
1303 /// Release ExitSU predecessors and setup scheduler queues. Re-position
1304 /// the Top RP tracker in case the region beginning has changed.
1305 void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
1306                                    ArrayRef<SUnit*> BotRoots) {
1307   ScheduleDAGMI::initQueues(TopRoots, BotRoots);
1308   if (ShouldTrackPressure) {
1309     assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1310     TopRPTracker.setPos(CurrentTop);
1311   }
1312 }
1313 
1314 /// Move an instruction and update register pressure.
1315 void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
1316   // Move the instruction to its new location in the instruction stream.
1317   MachineInstr *MI = SU->getInstr();
1318 
1319   if (IsTopNode) {
1320     assert(SU->isTopReady() && "node still has unscheduled dependencies");
1321     if (&*CurrentTop == MI)
1322       CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
1323     else {
1324       moveInstruction(MI, CurrentTop);
1325       TopRPTracker.setPos(MI);
1326     }
1327 
1328     if (ShouldTrackPressure) {
1329       // Update top scheduled pressure.
1330       RegisterOperands RegOpers;
1331       RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1332       if (ShouldTrackLaneMasks) {
1333         // Adjust liveness and add missing dead+read-undef flags.
1334         SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
1335         RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1336       } else {
1337         // Adjust for missing dead-def flags.
1338         RegOpers.detectDeadDefs(*MI, *LIS);
1339       }
1340 
1341       TopRPTracker.advance(RegOpers);
1342       assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
1343       DEBUG(
1344         dbgs() << "Top Pressure:\n";
1345         dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1346       );
1347 
1348       updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
1349     }
1350   } else {
1351     assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1352     MachineBasicBlock::iterator priorII =
1353       priorNonDebug(CurrentBottom, CurrentTop);
1354     if (&*priorII == MI)
1355       CurrentBottom = priorII;
1356     else {
1357       if (&*CurrentTop == MI) {
1358         CurrentTop = nextIfDebug(++CurrentTop, priorII);
1359         TopRPTracker.setPos(CurrentTop);
1360       }
1361       moveInstruction(MI, CurrentBottom);
1362       CurrentBottom = MI;
1363     }
1364     if (ShouldTrackPressure) {
1365       RegisterOperands RegOpers;
1366       RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1367       if (ShouldTrackLaneMasks) {
1368         // Adjust liveness and add missing dead+read-undef flags.
1369         SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
1370         RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1371       } else {
1372         // Adjust for missing dead-def flags.
1373         RegOpers.detectDeadDefs(*MI, *LIS);
1374       }
1375 
1376       BotRPTracker.recedeSkipDebugValues();
1377       SmallVector<RegisterMaskPair, 8> LiveUses;
1378       BotRPTracker.recede(RegOpers, &LiveUses);
1379       assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
1380       DEBUG(
1381         dbgs() << "Bottom Pressure:\n";
1382         dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
1383       );
1384 
1385       updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
1386       updatePressureDiffs(LiveUses);
1387     }
1388   }
1389 }
1390 
1391 //===----------------------------------------------------------------------===//
1392 // BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
1393 //===----------------------------------------------------------------------===//
1394 
1395 namespace {
1396 /// \brief Post-process the DAG to create cluster edges between neighboring
1397 /// loads or between neighboring stores.
1398 class BaseMemOpClusterMutation : public ScheduleDAGMutation {
1399   struct MemOpInfo {
1400     SUnit *SU;
1401     unsigned BaseReg;
1402     int64_t Offset;
1403     MemOpInfo(SUnit *su, unsigned reg, int64_t ofs)
1404         : SU(su), BaseReg(reg), Offset(ofs) {}
1405 
1406     bool operator<(const MemOpInfo&RHS) const {
1407       return std::tie(BaseReg, Offset, SU->NodeNum) <
1408              std::tie(RHS.BaseReg, RHS.Offset, RHS.SU->NodeNum);
1409     }
1410   };
1411 
1412   const TargetInstrInfo *TII;
1413   const TargetRegisterInfo *TRI;
1414   bool IsLoad;
1415 
1416 public:
1417   BaseMemOpClusterMutation(const TargetInstrInfo *tii,
1418                            const TargetRegisterInfo *tri, bool IsLoad)
1419       : TII(tii), TRI(tri), IsLoad(IsLoad) {}
1420 
1421   void apply(ScheduleDAGInstrs *DAGInstrs) override;
1422 
1423 protected:
1424   void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG);
1425 };
1426 
1427 class StoreClusterMutation : public BaseMemOpClusterMutation {
1428 public:
1429   StoreClusterMutation(const TargetInstrInfo *tii,
1430                        const TargetRegisterInfo *tri)
1431       : BaseMemOpClusterMutation(tii, tri, false) {}
1432 };
1433 
1434 class LoadClusterMutation : public BaseMemOpClusterMutation {
1435 public:
1436   LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
1437       : BaseMemOpClusterMutation(tii, tri, true) {}
1438 };
1439 } // anonymous
1440 
1441 namespace llvm {
1442 
1443 std::unique_ptr<ScheduleDAGMutation>
1444 createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1445                              const TargetRegisterInfo *TRI) {
1446   return EnableMemOpCluster ? make_unique<LoadClusterMutation>(TII, TRI)
1447                             : nullptr;
1448 }
1449 
1450 std::unique_ptr<ScheduleDAGMutation>
1451 createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1452                               const TargetRegisterInfo *TRI) {
1453   return EnableMemOpCluster ? make_unique<StoreClusterMutation>(TII, TRI)
1454                             : nullptr;
1455 }
1456 
1457 } // namespace llvm
1458 
1459 void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1460     ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG) {
1461   SmallVector<MemOpInfo, 32> MemOpRecords;
1462   for (unsigned Idx = 0, End = MemOps.size(); Idx != End; ++Idx) {
1463     SUnit *SU = MemOps[Idx];
1464     unsigned BaseReg;
1465     int64_t Offset;
1466     if (TII->getMemOpBaseRegImmOfs(*SU->getInstr(), BaseReg, Offset, TRI))
1467       MemOpRecords.push_back(MemOpInfo(SU, BaseReg, Offset));
1468   }
1469   if (MemOpRecords.size() < 2)
1470     return;
1471 
1472   std::sort(MemOpRecords.begin(), MemOpRecords.end());
1473   unsigned ClusterLength = 1;
1474   for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
1475     if (MemOpRecords[Idx].BaseReg != MemOpRecords[Idx+1].BaseReg) {
1476       ClusterLength = 1;
1477       continue;
1478     }
1479 
1480     SUnit *SUa = MemOpRecords[Idx].SU;
1481     SUnit *SUb = MemOpRecords[Idx+1].SU;
1482     if (TII->shouldClusterMemOps(*SUa->getInstr(), *SUb->getInstr(),
1483                                  ClusterLength) &&
1484         DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
1485       DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
1486             << SUb->NodeNum << ")\n");
1487       // Copy successor edges from SUa to SUb. Interleaving computation
1488       // dependent on SUa can prevent load combining due to register reuse.
1489       // Predecessor edges do not need to be copied from SUb to SUa since nearby
1490       // loads should have effectively the same inputs.
1491       for (SUnit::const_succ_iterator
1492              SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
1493         if (SI->getSUnit() == SUb)
1494           continue;
1495         DEBUG(dbgs() << "  Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
1496         DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
1497       }
1498       ++ClusterLength;
1499     } else
1500       ClusterLength = 1;
1501   }
1502 }
1503 
1504 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
1505 void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
1506 
1507   ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1508 
1509   // Map DAG NodeNum to store chain ID.
1510   DenseMap<unsigned, unsigned> StoreChainIDs;
1511   // Map each store chain to a set of dependent MemOps.
1512   SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1513   for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1514     SUnit *SU = &DAG->SUnits[Idx];
1515     if ((IsLoad && !SU->getInstr()->mayLoad()) ||
1516         (!IsLoad && !SU->getInstr()->mayStore()))
1517       continue;
1518 
1519     unsigned ChainPredID = DAG->SUnits.size();
1520     for (SUnit::const_pred_iterator
1521            PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1522       if (PI->isCtrl()) {
1523         ChainPredID = PI->getSUnit()->NodeNum;
1524         break;
1525       }
1526     }
1527     // Check if this chain-like pred has been seen
1528     // before. ChainPredID==MaxNodeID at the top of the schedule.
1529     unsigned NumChains = StoreChainDependents.size();
1530     std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1531       StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1532     if (Result.second)
1533       StoreChainDependents.resize(NumChains + 1);
1534     StoreChainDependents[Result.first->second].push_back(SU);
1535   }
1536 
1537   // Iterate over the store chains.
1538   for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
1539     clusterNeighboringMemOps(StoreChainDependents[Idx], DAG);
1540 }
1541 
1542 //===----------------------------------------------------------------------===//
1543 // CopyConstrain - DAG post-processing to encourage copy elimination.
1544 //===----------------------------------------------------------------------===//
1545 
1546 namespace {
1547 /// \brief Post-process the DAG to create weak edges from all uses of a copy to
1548 /// the one use that defines the copy's source vreg, most likely an induction
1549 /// variable increment.
1550 class CopyConstrain : public ScheduleDAGMutation {
1551   // Transient state.
1552   SlotIndex RegionBeginIdx;
1553   // RegionEndIdx is the slot index of the last non-debug instruction in the
1554   // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
1555   SlotIndex RegionEndIdx;
1556 public:
1557   CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1558 
1559   void apply(ScheduleDAGInstrs *DAGInstrs) override;
1560 
1561 protected:
1562   void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
1563 };
1564 } // anonymous
1565 
1566 namespace llvm {
1567 
1568 std::unique_ptr<ScheduleDAGMutation>
1569 createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
1570                              const TargetRegisterInfo *TRI) {
1571   return make_unique<CopyConstrain>(TII, TRI);
1572 }
1573 
1574 } // namespace llvm
1575 
1576 /// constrainLocalCopy handles two possibilities:
1577 /// 1) Local src:
1578 /// I0:     = dst
1579 /// I1: src = ...
1580 /// I2:     = dst
1581 /// I3: dst = src (copy)
1582 /// (create pred->succ edges I0->I1, I2->I1)
1583 ///
1584 /// 2) Local copy:
1585 /// I0: dst = src (copy)
1586 /// I1:     = dst
1587 /// I2: src = ...
1588 /// I3:     = dst
1589 /// (create pred->succ edges I1->I2, I3->I2)
1590 ///
1591 /// Although the MachineScheduler is currently constrained to single blocks,
1592 /// this algorithm should handle extended blocks. An EBB is a set of
1593 /// contiguously numbered blocks such that the previous block in the EBB is
1594 /// always the single predecessor.
1595 void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
1596   LiveIntervals *LIS = DAG->getLIS();
1597   MachineInstr *Copy = CopySU->getInstr();
1598 
1599   // Check for pure vreg copies.
1600   const MachineOperand &SrcOp = Copy->getOperand(1);
1601   unsigned SrcReg = SrcOp.getReg();
1602   if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
1603     return;
1604 
1605   const MachineOperand &DstOp = Copy->getOperand(0);
1606   unsigned DstReg = DstOp.getReg();
1607   if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead())
1608     return;
1609 
1610   // Check if either the dest or source is local. If it's live across a back
1611   // edge, it's not local. Note that if both vregs are live across the back
1612   // edge, we cannot successfully contrain the copy without cyclic scheduling.
1613   // If both the copy's source and dest are local live intervals, then we
1614   // should treat the dest as the global for the purpose of adding
1615   // constraints. This adds edges from source's other uses to the copy.
1616   unsigned LocalReg = SrcReg;
1617   unsigned GlobalReg = DstReg;
1618   LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1619   if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
1620     LocalReg = DstReg;
1621     GlobalReg = SrcReg;
1622     LocalLI = &LIS->getInterval(LocalReg);
1623     if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1624       return;
1625   }
1626   LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1627 
1628   // Find the global segment after the start of the local LI.
1629   LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1630   // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1631   // local live range. We could create edges from other global uses to the local
1632   // start, but the coalescer should have already eliminated these cases, so
1633   // don't bother dealing with it.
1634   if (GlobalSegment == GlobalLI->end())
1635     return;
1636 
1637   // If GlobalSegment is killed at the LocalLI->start, the call to find()
1638   // returned the next global segment. But if GlobalSegment overlaps with
1639   // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1640   // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1641   if (GlobalSegment->contains(LocalLI->beginIndex()))
1642     ++GlobalSegment;
1643 
1644   if (GlobalSegment == GlobalLI->end())
1645     return;
1646 
1647   // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1648   if (GlobalSegment != GlobalLI->begin()) {
1649     // Two address defs have no hole.
1650     if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
1651                                GlobalSegment->start)) {
1652       return;
1653     }
1654     // If the prior global segment may be defined by the same two-address
1655     // instruction that also defines LocalLI, then can't make a hole here.
1656     if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
1657                                LocalLI->beginIndex())) {
1658       return;
1659     }
1660     // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1661     // it would be a disconnected component in the live range.
1662     assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
1663            "Disconnected LRG within the scheduling region.");
1664   }
1665   MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1666   if (!GlobalDef)
1667     return;
1668 
1669   SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1670   if (!GlobalSU)
1671     return;
1672 
1673   // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1674   // constraining the uses of the last local def to precede GlobalDef.
1675   SmallVector<SUnit*,8> LocalUses;
1676   const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1677   MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1678   SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1679   for (SUnit::const_succ_iterator
1680          I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1681        I != E; ++I) {
1682     if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1683       continue;
1684     if (I->getSUnit() == GlobalSU)
1685       continue;
1686     if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1687       return;
1688     LocalUses.push_back(I->getSUnit());
1689   }
1690   // Open the top of the GlobalLI hole by constraining any earlier global uses
1691   // to precede the start of LocalLI.
1692   SmallVector<SUnit*,8> GlobalUses;
1693   MachineInstr *FirstLocalDef =
1694     LIS->getInstructionFromIndex(LocalLI->beginIndex());
1695   SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1696   for (SUnit::const_pred_iterator
1697          I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1698     if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1699       continue;
1700     if (I->getSUnit() == FirstLocalSU)
1701       continue;
1702     if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1703       return;
1704     GlobalUses.push_back(I->getSUnit());
1705   }
1706   DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1707   // Add the weak edges.
1708   for (SmallVectorImpl<SUnit*>::const_iterator
1709          I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1710     DEBUG(dbgs() << "  Local use SU(" << (*I)->NodeNum << ") -> SU("
1711           << GlobalSU->NodeNum << ")\n");
1712     DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1713   }
1714   for (SmallVectorImpl<SUnit*>::const_iterator
1715          I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1716     DEBUG(dbgs() << "  Global use SU(" << (*I)->NodeNum << ") -> SU("
1717           << FirstLocalSU->NodeNum << ")\n");
1718     DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1719   }
1720 }
1721 
1722 /// \brief Callback from DAG postProcessing to create weak edges to encourage
1723 /// copy elimination.
1724 void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
1725   ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1726   assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1727 
1728   MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1729   if (FirstPos == DAG->end())
1730     return;
1731   RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
1732   RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1733       *priorNonDebug(DAG->end(), DAG->begin()));
1734 
1735   for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1736     SUnit *SU = &DAG->SUnits[Idx];
1737     if (!SU->getInstr()->isCopy())
1738       continue;
1739 
1740     constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
1741   }
1742 }
1743 
1744 //===----------------------------------------------------------------------===//
1745 // MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1746 // and possibly other custom schedulers.
1747 //===----------------------------------------------------------------------===//
1748 
1749 static const unsigned InvalidCycle = ~0U;
1750 
1751 SchedBoundary::~SchedBoundary() { delete HazardRec; }
1752 
1753 void SchedBoundary::reset() {
1754   // A new HazardRec is created for each DAG and owned by SchedBoundary.
1755   // Destroying and reconstructing it is very expensive though. So keep
1756   // invalid, placeholder HazardRecs.
1757   if (HazardRec && HazardRec->isEnabled()) {
1758     delete HazardRec;
1759     HazardRec = nullptr;
1760   }
1761   Available.clear();
1762   Pending.clear();
1763   CheckPending = false;
1764   CurrCycle = 0;
1765   CurrMOps = 0;
1766   MinReadyCycle = UINT_MAX;
1767   ExpectedLatency = 0;
1768   DependentLatency = 0;
1769   RetiredMOps = 0;
1770   MaxExecutedResCount = 0;
1771   ZoneCritResIdx = 0;
1772   IsResourceLimited = false;
1773   ReservedCycles.clear();
1774 #ifndef NDEBUG
1775   // Track the maximum number of stall cycles that could arise either from the
1776   // latency of a DAG edge or the number of cycles that a processor resource is
1777   // reserved (SchedBoundary::ReservedCycles).
1778   MaxObservedStall = 0;
1779 #endif
1780   // Reserve a zero-count for invalid CritResIdx.
1781   ExecutedResCounts.resize(1);
1782   assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1783 }
1784 
1785 void SchedRemainder::
1786 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1787   reset();
1788   if (!SchedModel->hasInstrSchedModel())
1789     return;
1790   RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1791   for (std::vector<SUnit>::iterator
1792          I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1793     const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1794     RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1795       * SchedModel->getMicroOpFactor();
1796     for (TargetSchedModel::ProcResIter
1797            PI = SchedModel->getWriteProcResBegin(SC),
1798            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1799       unsigned PIdx = PI->ProcResourceIdx;
1800       unsigned Factor = SchedModel->getResourceFactor(PIdx);
1801       RemainingCounts[PIdx] += (Factor * PI->Cycles);
1802     }
1803   }
1804 }
1805 
1806 void SchedBoundary::
1807 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1808   reset();
1809   DAG = dag;
1810   SchedModel = smodel;
1811   Rem = rem;
1812   if (SchedModel->hasInstrSchedModel()) {
1813     ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
1814     ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1815   }
1816 }
1817 
1818 /// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1819 /// these "soft stalls" differently than the hard stall cycles based on CPU
1820 /// resources and computed by checkHazard(). A fully in-order model
1821 /// (MicroOpBufferSize==0) will not make use of this since instructions are not
1822 /// available for scheduling until they are ready. However, a weaker in-order
1823 /// model may use this for heuristics. For example, if a processor has in-order
1824 /// behavior when reading certain resources, this may come into play.
1825 unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
1826   if (!SU->isUnbuffered)
1827     return 0;
1828 
1829   unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1830   if (ReadyCycle > CurrCycle)
1831     return ReadyCycle - CurrCycle;
1832   return 0;
1833 }
1834 
1835 /// Compute the next cycle at which the given processor resource can be
1836 /// scheduled.
1837 unsigned SchedBoundary::
1838 getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1839   unsigned NextUnreserved = ReservedCycles[PIdx];
1840   // If this resource has never been used, always return cycle zero.
1841   if (NextUnreserved == InvalidCycle)
1842     return 0;
1843   // For bottom-up scheduling add the cycles needed for the current operation.
1844   if (!isTop())
1845     NextUnreserved += Cycles;
1846   return NextUnreserved;
1847 }
1848 
1849 /// Does this SU have a hazard within the current instruction group.
1850 ///
1851 /// The scheduler supports two modes of hazard recognition. The first is the
1852 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1853 /// supports highly complicated in-order reservation tables
1854 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1855 ///
1856 /// The second is a streamlined mechanism that checks for hazards based on
1857 /// simple counters that the scheduler itself maintains. It explicitly checks
1858 /// for instruction dispatch limitations, including the number of micro-ops that
1859 /// can dispatch per cycle.
1860 ///
1861 /// TODO: Also check whether the SU must start a new group.
1862 bool SchedBoundary::checkHazard(SUnit *SU) {
1863   if (HazardRec->isEnabled()
1864       && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1865     return true;
1866   }
1867   unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1868   if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
1869     DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") uops="
1870           << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1871     return true;
1872   }
1873   if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1874     const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1875     for (TargetSchedModel::ProcResIter
1876            PI = SchedModel->getWriteProcResBegin(SC),
1877            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1878       unsigned NRCycle = getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles);
1879       if (NRCycle > CurrCycle) {
1880 #ifndef NDEBUG
1881         MaxObservedStall = std::max(PI->Cycles, MaxObservedStall);
1882 #endif
1883         DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") "
1884               << SchedModel->getResourceName(PI->ProcResourceIdx)
1885               << "=" << NRCycle << "c\n");
1886         return true;
1887       }
1888     }
1889   }
1890   return false;
1891 }
1892 
1893 // Find the unscheduled node in ReadySUs with the highest latency.
1894 unsigned SchedBoundary::
1895 findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
1896   SUnit *LateSU = nullptr;
1897   unsigned RemLatency = 0;
1898   for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
1899        I != E; ++I) {
1900     unsigned L = getUnscheduledLatency(*I);
1901     if (L > RemLatency) {
1902       RemLatency = L;
1903       LateSU = *I;
1904     }
1905   }
1906   if (LateSU) {
1907     DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1908           << LateSU->NodeNum << ") " << RemLatency << "c\n");
1909   }
1910   return RemLatency;
1911 }
1912 
1913 // Count resources in this zone and the remaining unscheduled
1914 // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1915 // resource index, or zero if the zone is issue limited.
1916 unsigned SchedBoundary::
1917 getOtherResourceCount(unsigned &OtherCritIdx) {
1918   OtherCritIdx = 0;
1919   if (!SchedModel->hasInstrSchedModel())
1920     return 0;
1921 
1922   unsigned OtherCritCount = Rem->RemIssueCount
1923     + (RetiredMOps * SchedModel->getMicroOpFactor());
1924   DEBUG(dbgs() << "  " << Available.getName() << " + Remain MOps: "
1925         << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
1926   for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1927        PIdx != PEnd; ++PIdx) {
1928     unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1929     if (OtherCount > OtherCritCount) {
1930       OtherCritCount = OtherCount;
1931       OtherCritIdx = PIdx;
1932     }
1933   }
1934   if (OtherCritIdx) {
1935     DEBUG(dbgs() << "  " << Available.getName() << " + Remain CritRes: "
1936           << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
1937           << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
1938   }
1939   return OtherCritCount;
1940 }
1941 
1942 void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
1943   assert(SU->getInstr() && "Scheduled SUnit must have instr");
1944 
1945 #ifndef NDEBUG
1946   // ReadyCycle was been bumped up to the CurrCycle when this node was
1947   // scheduled, but CurrCycle may have been eagerly advanced immediately after
1948   // scheduling, so may now be greater than ReadyCycle.
1949   if (ReadyCycle > CurrCycle)
1950     MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
1951 #endif
1952 
1953   if (ReadyCycle < MinReadyCycle)
1954     MinReadyCycle = ReadyCycle;
1955 
1956   // Check for interlocks first. For the purpose of other heuristics, an
1957   // instruction that cannot issue appears as if it's not in the ReadyQueue.
1958   bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1959   if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
1960       Available.size() >= ReadyListLimit)
1961     Pending.push(SU);
1962   else
1963     Available.push(SU);
1964 }
1965 
1966 /// Move the boundary of scheduled code by one cycle.
1967 void SchedBoundary::bumpCycle(unsigned NextCycle) {
1968   if (SchedModel->getMicroOpBufferSize() == 0) {
1969     assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1970     if (MinReadyCycle > NextCycle)
1971       NextCycle = MinReadyCycle;
1972   }
1973   // Update the current micro-ops, which will issue in the next cycle.
1974   unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1975   CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1976 
1977   // Decrement DependentLatency based on the next cycle.
1978   if ((NextCycle - CurrCycle) > DependentLatency)
1979     DependentLatency = 0;
1980   else
1981     DependentLatency -= (NextCycle - CurrCycle);
1982 
1983   if (!HazardRec->isEnabled()) {
1984     // Bypass HazardRec virtual calls.
1985     CurrCycle = NextCycle;
1986   } else {
1987     // Bypass getHazardType calls in case of long latency.
1988     for (; CurrCycle != NextCycle; ++CurrCycle) {
1989       if (isTop())
1990         HazardRec->AdvanceCycle();
1991       else
1992         HazardRec->RecedeCycle();
1993     }
1994   }
1995   CheckPending = true;
1996   unsigned LFactor = SchedModel->getLatencyFactor();
1997   IsResourceLimited =
1998     (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1999     > (int)LFactor;
2000 
2001   DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
2002 }
2003 
2004 void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
2005   ExecutedResCounts[PIdx] += Count;
2006   if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2007     MaxExecutedResCount = ExecutedResCounts[PIdx];
2008 }
2009 
2010 /// Add the given processor resource to this scheduled zone.
2011 ///
2012 /// \param Cycles indicates the number of consecutive (non-pipelined) cycles
2013 /// during which this resource is consumed.
2014 ///
2015 /// \return the next cycle at which the instruction may execute without
2016 /// oversubscribing resources.
2017 unsigned SchedBoundary::
2018 countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
2019   unsigned Factor = SchedModel->getResourceFactor(PIdx);
2020   unsigned Count = Factor * Cycles;
2021   DEBUG(dbgs() << "  " << SchedModel->getResourceName(PIdx)
2022         << " +" << Cycles << "x" << Factor << "u\n");
2023 
2024   // Update Executed resources counts.
2025   incExecutedResources(PIdx, Count);
2026   assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
2027   Rem->RemainingCounts[PIdx] -= Count;
2028 
2029   // Check if this resource exceeds the current critical resource. If so, it
2030   // becomes the critical resource.
2031   if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
2032     ZoneCritResIdx = PIdx;
2033     DEBUG(dbgs() << "  *** Critical resource "
2034           << SchedModel->getResourceName(PIdx) << ": "
2035           << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
2036   }
2037   // For reserved resources, record the highest cycle using the resource.
2038   unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
2039   if (NextAvailable > CurrCycle) {
2040     DEBUG(dbgs() << "  Resource conflict: "
2041           << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
2042           << NextAvailable << "\n");
2043   }
2044   return NextAvailable;
2045 }
2046 
2047 /// Move the boundary of scheduled code by one SUnit.
2048 void SchedBoundary::bumpNode(SUnit *SU) {
2049   // Update the reservation table.
2050   if (HazardRec->isEnabled()) {
2051     if (!isTop() && SU->isCall) {
2052       // Calls are scheduled with their preceding instructions. For bottom-up
2053       // scheduling, clear the pipeline state before emitting.
2054       HazardRec->Reset();
2055     }
2056     HazardRec->EmitInstruction(SU);
2057   }
2058   // checkHazard should prevent scheduling multiple instructions per cycle that
2059   // exceed the issue width.
2060   const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2061   unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
2062   assert(
2063       (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
2064       "Cannot schedule this instruction's MicroOps in the current cycle.");
2065 
2066   unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
2067   DEBUG(dbgs() << "  Ready @" << ReadyCycle << "c\n");
2068 
2069   unsigned NextCycle = CurrCycle;
2070   switch (SchedModel->getMicroOpBufferSize()) {
2071   case 0:
2072     assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2073     break;
2074   case 1:
2075     if (ReadyCycle > NextCycle) {
2076       NextCycle = ReadyCycle;
2077       DEBUG(dbgs() << "  *** Stall until: " << ReadyCycle << "\n");
2078     }
2079     break;
2080   default:
2081     // We don't currently model the OOO reorder buffer, so consider all
2082     // scheduled MOps to be "retired". We do loosely model in-order resource
2083     // latency. If this instruction uses an in-order resource, account for any
2084     // likely stall cycles.
2085     if (SU->isUnbuffered && ReadyCycle > NextCycle)
2086       NextCycle = ReadyCycle;
2087     break;
2088   }
2089   RetiredMOps += IncMOps;
2090 
2091   // Update resource counts and critical resource.
2092   if (SchedModel->hasInstrSchedModel()) {
2093     unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2094     assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2095     Rem->RemIssueCount -= DecRemIssue;
2096     if (ZoneCritResIdx) {
2097       // Scale scheduled micro-ops for comparing with the critical resource.
2098       unsigned ScaledMOps =
2099         RetiredMOps * SchedModel->getMicroOpFactor();
2100 
2101       // If scaled micro-ops are now more than the previous critical resource by
2102       // a full cycle, then micro-ops issue becomes critical.
2103       if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2104           >= (int)SchedModel->getLatencyFactor()) {
2105         ZoneCritResIdx = 0;
2106         DEBUG(dbgs() << "  *** Critical resource NumMicroOps: "
2107               << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
2108       }
2109     }
2110     for (TargetSchedModel::ProcResIter
2111            PI = SchedModel->getWriteProcResBegin(SC),
2112            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2113       unsigned RCycle =
2114         countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
2115       if (RCycle > NextCycle)
2116         NextCycle = RCycle;
2117     }
2118     if (SU->hasReservedResource) {
2119       // For reserved resources, record the highest cycle using the resource.
2120       // For top-down scheduling, this is the cycle in which we schedule this
2121       // instruction plus the number of cycles the operations reserves the
2122       // resource. For bottom-up is it simply the instruction's cycle.
2123       for (TargetSchedModel::ProcResIter
2124              PI = SchedModel->getWriteProcResBegin(SC),
2125              PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2126         unsigned PIdx = PI->ProcResourceIdx;
2127         if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
2128           if (isTop()) {
2129             ReservedCycles[PIdx] =
2130               std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles);
2131           }
2132           else
2133             ReservedCycles[PIdx] = NextCycle;
2134         }
2135       }
2136     }
2137   }
2138   // Update ExpectedLatency and DependentLatency.
2139   unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2140   unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2141   if (SU->getDepth() > TopLatency) {
2142     TopLatency = SU->getDepth();
2143     DEBUG(dbgs() << "  " << Available.getName()
2144           << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
2145   }
2146   if (SU->getHeight() > BotLatency) {
2147     BotLatency = SU->getHeight();
2148     DEBUG(dbgs() << "  " << Available.getName()
2149           << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
2150   }
2151   // If we stall for any reason, bump the cycle.
2152   if (NextCycle > CurrCycle) {
2153     bumpCycle(NextCycle);
2154   } else {
2155     // After updating ZoneCritResIdx and ExpectedLatency, check if we're
2156     // resource limited. If a stall occurred, bumpCycle does this.
2157     unsigned LFactor = SchedModel->getLatencyFactor();
2158     IsResourceLimited =
2159       (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
2160       > (int)LFactor;
2161   }
2162   // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
2163   // resets CurrMOps. Loop to handle instructions with more MOps than issue in
2164   // one cycle.  Since we commonly reach the max MOps here, opportunistically
2165   // bump the cycle to avoid uselessly checking everything in the readyQ.
2166   CurrMOps += IncMOps;
2167   while (CurrMOps >= SchedModel->getIssueWidth()) {
2168     DEBUG(dbgs() << "  *** Max MOps " << CurrMOps
2169           << " at cycle " << CurrCycle << '\n');
2170     bumpCycle(++NextCycle);
2171   }
2172   DEBUG(dumpScheduledState());
2173 }
2174 
2175 /// Release pending ready nodes in to the available queue. This makes them
2176 /// visible to heuristics.
2177 void SchedBoundary::releasePending() {
2178   // If the available queue is empty, it is safe to reset MinReadyCycle.
2179   if (Available.empty())
2180     MinReadyCycle = UINT_MAX;
2181 
2182   // Check to see if any of the pending instructions are ready to issue.  If
2183   // so, add them to the available queue.
2184   bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
2185   for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2186     SUnit *SU = *(Pending.begin()+i);
2187     unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
2188 
2189     if (ReadyCycle < MinReadyCycle)
2190       MinReadyCycle = ReadyCycle;
2191 
2192     if (!IsBuffered && ReadyCycle > CurrCycle)
2193       continue;
2194 
2195     if (checkHazard(SU))
2196       continue;
2197 
2198     if (Available.size() >= ReadyListLimit)
2199       break;
2200 
2201     Available.push(SU);
2202     Pending.remove(Pending.begin()+i);
2203     --i; --e;
2204   }
2205   CheckPending = false;
2206 }
2207 
2208 /// Remove SU from the ready set for this boundary.
2209 void SchedBoundary::removeReady(SUnit *SU) {
2210   if (Available.isInQueue(SU))
2211     Available.remove(Available.find(SU));
2212   else {
2213     assert(Pending.isInQueue(SU) && "bad ready count");
2214     Pending.remove(Pending.find(SU));
2215   }
2216 }
2217 
2218 /// If this queue only has one ready candidate, return it. As a side effect,
2219 /// defer any nodes that now hit a hazard, and advance the cycle until at least
2220 /// one node is ready. If multiple instructions are ready, return NULL.
2221 SUnit *SchedBoundary::pickOnlyChoice() {
2222   if (CheckPending)
2223     releasePending();
2224 
2225   if (CurrMOps > 0) {
2226     // Defer any ready instrs that now have a hazard.
2227     for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2228       if (checkHazard(*I)) {
2229         Pending.push(*I);
2230         I = Available.remove(I);
2231         continue;
2232       }
2233       ++I;
2234     }
2235   }
2236   for (unsigned i = 0; Available.empty(); ++i) {
2237 //  FIXME: Re-enable assert once PR20057 is resolved.
2238 //    assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
2239 //           "permanent hazard");
2240     (void)i;
2241     bumpCycle(CurrCycle + 1);
2242     releasePending();
2243   }
2244 
2245   DEBUG(Pending.dump());
2246   DEBUG(Available.dump());
2247 
2248   if (Available.size() == 1)
2249     return *Available.begin();
2250   return nullptr;
2251 }
2252 
2253 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2254 // This is useful information to dump after bumpNode.
2255 // Note that the Queue contents are more useful before pickNodeFromQueue.
2256 LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() {
2257   unsigned ResFactor;
2258   unsigned ResCount;
2259   if (ZoneCritResIdx) {
2260     ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2261     ResCount = getResourceCount(ZoneCritResIdx);
2262   } else {
2263     ResFactor = SchedModel->getMicroOpFactor();
2264     ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
2265   }
2266   unsigned LFactor = SchedModel->getLatencyFactor();
2267   dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2268          << "  Retired: " << RetiredMOps;
2269   dbgs() << "\n  Executed: " << getExecutedCount() / LFactor << "c";
2270   dbgs() << "\n  Critical: " << ResCount / LFactor << "c, "
2271          << ResCount / ResFactor << " "
2272          << SchedModel->getResourceName(ZoneCritResIdx)
2273          << "\n  ExpectedLatency: " << ExpectedLatency << "c\n"
2274          << (IsResourceLimited ? "  - Resource" : "  - Latency")
2275          << " limited.\n";
2276 }
2277 #endif
2278 
2279 //===----------------------------------------------------------------------===//
2280 // GenericScheduler - Generic implementation of MachineSchedStrategy.
2281 //===----------------------------------------------------------------------===//
2282 
2283 void GenericSchedulerBase::SchedCandidate::
2284 initResourceDelta(const ScheduleDAGMI *DAG,
2285                   const TargetSchedModel *SchedModel) {
2286   if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2287     return;
2288 
2289   const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2290   for (TargetSchedModel::ProcResIter
2291          PI = SchedModel->getWriteProcResBegin(SC),
2292          PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2293     if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2294       ResDelta.CritResources += PI->Cycles;
2295     if (PI->ProcResourceIdx == Policy.DemandResIdx)
2296       ResDelta.DemandedResources += PI->Cycles;
2297   }
2298 }
2299 
2300 /// Set the CandPolicy given a scheduling zone given the current resources and
2301 /// latencies inside and outside the zone.
2302 void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
2303                                      SchedBoundary &CurrZone,
2304                                      SchedBoundary *OtherZone) {
2305   // Apply preemptive heuristics based on the total latency and resources
2306   // inside and outside this zone. Potential stalls should be considered before
2307   // following this policy.
2308 
2309   // Compute remaining latency. We need this both to determine whether the
2310   // overall schedule has become latency-limited and whether the instructions
2311   // outside this zone are resource or latency limited.
2312   //
2313   // The "dependent" latency is updated incrementally during scheduling as the
2314   // max height/depth of scheduled nodes minus the cycles since it was
2315   // scheduled:
2316   //   DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2317   //
2318   // The "independent" latency is the max ready queue depth:
2319   //   ILat = max N.depth for N in Available|Pending
2320   //
2321   // RemainingLatency is the greater of independent and dependent latency.
2322   unsigned RemLatency = CurrZone.getDependentLatency();
2323   RemLatency = std::max(RemLatency,
2324                         CurrZone.findMaxLatency(CurrZone.Available.elements()));
2325   RemLatency = std::max(RemLatency,
2326                         CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2327 
2328   // Compute the critical resource outside the zone.
2329   unsigned OtherCritIdx = 0;
2330   unsigned OtherCount =
2331     OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2332 
2333   bool OtherResLimited = false;
2334   if (SchedModel->hasInstrSchedModel()) {
2335     unsigned LFactor = SchedModel->getLatencyFactor();
2336     OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2337   }
2338   // Schedule aggressively for latency in PostRA mode. We don't check for
2339   // acyclic latency during PostRA, and highly out-of-order processors will
2340   // skip PostRA scheduling.
2341   if (!OtherResLimited) {
2342     if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2343       Policy.ReduceLatency |= true;
2344       DEBUG(dbgs() << "  " << CurrZone.Available.getName()
2345             << " RemainingLatency " << RemLatency << " + "
2346             << CurrZone.getCurrCycle() << "c > CritPath "
2347             << Rem.CriticalPath << "\n");
2348     }
2349   }
2350   // If the same resource is limiting inside and outside the zone, do nothing.
2351   if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2352     return;
2353 
2354   DEBUG(
2355     if (CurrZone.isResourceLimited()) {
2356       dbgs() << "  " << CurrZone.Available.getName() << " ResourceLimited: "
2357              << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2358              << "\n";
2359     }
2360     if (OtherResLimited)
2361       dbgs() << "  RemainingLimit: "
2362              << SchedModel->getResourceName(OtherCritIdx) << "\n";
2363     if (!CurrZone.isResourceLimited() && !OtherResLimited)
2364       dbgs() << "  Latency limited both directions.\n");
2365 
2366   if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2367     Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2368 
2369   if (OtherResLimited)
2370     Policy.DemandResIdx = OtherCritIdx;
2371 }
2372 
2373 #ifndef NDEBUG
2374 const char *GenericSchedulerBase::getReasonStr(
2375   GenericSchedulerBase::CandReason Reason) {
2376   switch (Reason) {
2377   case NoCand:         return "NOCAND    ";
2378   case Only1:          return "ONLY1     ";
2379   case PhysRegCopy:    return "PREG-COPY ";
2380   case RegExcess:      return "REG-EXCESS";
2381   case RegCritical:    return "REG-CRIT  ";
2382   case Stall:          return "STALL     ";
2383   case Cluster:        return "CLUSTER   ";
2384   case Weak:           return "WEAK      ";
2385   case RegMax:         return "REG-MAX   ";
2386   case ResourceReduce: return "RES-REDUCE";
2387   case ResourceDemand: return "RES-DEMAND";
2388   case TopDepthReduce: return "TOP-DEPTH ";
2389   case TopPathReduce:  return "TOP-PATH  ";
2390   case BotHeightReduce:return "BOT-HEIGHT";
2391   case BotPathReduce:  return "BOT-PATH  ";
2392   case NextDefUse:     return "DEF-USE   ";
2393   case NodeOrder:      return "ORDER     ";
2394   };
2395   llvm_unreachable("Unknown reason!");
2396 }
2397 
2398 void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2399   PressureChange P;
2400   unsigned ResIdx = 0;
2401   unsigned Latency = 0;
2402   switch (Cand.Reason) {
2403   default:
2404     break;
2405   case RegExcess:
2406     P = Cand.RPDelta.Excess;
2407     break;
2408   case RegCritical:
2409     P = Cand.RPDelta.CriticalMax;
2410     break;
2411   case RegMax:
2412     P = Cand.RPDelta.CurrentMax;
2413     break;
2414   case ResourceReduce:
2415     ResIdx = Cand.Policy.ReduceResIdx;
2416     break;
2417   case ResourceDemand:
2418     ResIdx = Cand.Policy.DemandResIdx;
2419     break;
2420   case TopDepthReduce:
2421     Latency = Cand.SU->getDepth();
2422     break;
2423   case TopPathReduce:
2424     Latency = Cand.SU->getHeight();
2425     break;
2426   case BotHeightReduce:
2427     Latency = Cand.SU->getHeight();
2428     break;
2429   case BotPathReduce:
2430     Latency = Cand.SU->getDepth();
2431     break;
2432   }
2433   dbgs() << "  Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
2434   if (P.isValid())
2435     dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2436            << ":" << P.getUnitInc() << " ";
2437   else
2438     dbgs() << "      ";
2439   if (ResIdx)
2440     dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2441   else
2442     dbgs() << "         ";
2443   if (Latency)
2444     dbgs() << " " << Latency << " cycles ";
2445   else
2446     dbgs() << "          ";
2447   dbgs() << '\n';
2448 }
2449 #endif
2450 
2451 /// Return true if this heuristic determines order.
2452 static bool tryLess(int TryVal, int CandVal,
2453                     GenericSchedulerBase::SchedCandidate &TryCand,
2454                     GenericSchedulerBase::SchedCandidate &Cand,
2455                     GenericSchedulerBase::CandReason Reason) {
2456   if (TryVal < CandVal) {
2457     TryCand.Reason = Reason;
2458     return true;
2459   }
2460   if (TryVal > CandVal) {
2461     if (Cand.Reason > Reason)
2462       Cand.Reason = Reason;
2463     return true;
2464   }
2465   return false;
2466 }
2467 
2468 static bool tryGreater(int TryVal, int CandVal,
2469                        GenericSchedulerBase::SchedCandidate &TryCand,
2470                        GenericSchedulerBase::SchedCandidate &Cand,
2471                        GenericSchedulerBase::CandReason Reason) {
2472   if (TryVal > CandVal) {
2473     TryCand.Reason = Reason;
2474     return true;
2475   }
2476   if (TryVal < CandVal) {
2477     if (Cand.Reason > Reason)
2478       Cand.Reason = Reason;
2479     return true;
2480   }
2481   return false;
2482 }
2483 
2484 static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2485                        GenericSchedulerBase::SchedCandidate &Cand,
2486                        SchedBoundary &Zone) {
2487   if (Zone.isTop()) {
2488     if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2489       if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2490                   TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2491         return true;
2492     }
2493     if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2494                    TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2495       return true;
2496   } else {
2497     if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2498       if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2499                   TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2500         return true;
2501     }
2502     if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2503                    TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2504       return true;
2505   }
2506   return false;
2507 }
2508 
2509 static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
2510   DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2511         << GenericSchedulerBase::getReasonStr(Reason) << '\n');
2512 }
2513 
2514 static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
2515   tracePick(Cand.Reason, Cand.AtTop);
2516 }
2517 
2518 void GenericScheduler::initialize(ScheduleDAGMI *dag) {
2519   assert(dag->hasVRegLiveness() &&
2520          "(PreRA)GenericScheduler needs vreg liveness");
2521   DAG = static_cast<ScheduleDAGMILive*>(dag);
2522   SchedModel = DAG->getSchedModel();
2523   TRI = DAG->TRI;
2524 
2525   Rem.init(DAG, SchedModel);
2526   Top.init(DAG, SchedModel, &Rem);
2527   Bot.init(DAG, SchedModel, &Rem);
2528 
2529   // Initialize resource counts.
2530 
2531   // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2532   // are disabled, then these HazardRecs will be disabled.
2533   const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
2534   if (!Top.HazardRec) {
2535     Top.HazardRec =
2536         DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
2537             Itin, DAG);
2538   }
2539   if (!Bot.HazardRec) {
2540     Bot.HazardRec =
2541         DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
2542             Itin, DAG);
2543   }
2544   TopCand.SU = nullptr;
2545   BotCand.SU = nullptr;
2546 }
2547 
2548 /// Initialize the per-region scheduling policy.
2549 void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2550                                   MachineBasicBlock::iterator End,
2551                                   unsigned NumRegionInstrs) {
2552   const MachineFunction &MF = *Begin->getParent()->getParent();
2553   const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
2554 
2555   // Avoid setting up the register pressure tracker for small regions to save
2556   // compile time. As a rough heuristic, only track pressure when the number of
2557   // schedulable instructions exceeds half the integer register file.
2558   RegionPolicy.ShouldTrackPressure = true;
2559   for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2560     MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2561     if (TLI->isTypeLegal(LegalIntVT)) {
2562       unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
2563         TLI->getRegClassFor(LegalIntVT));
2564       RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2565     }
2566   }
2567 
2568   // For generic targets, we default to bottom-up, because it's simpler and more
2569   // compile-time optimizations have been implemented in that direction.
2570   RegionPolicy.OnlyBottomUp = true;
2571 
2572   // Allow the subtarget to override default policy.
2573   MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
2574 
2575   // After subtarget overrides, apply command line options.
2576   if (!EnableRegPressure)
2577     RegionPolicy.ShouldTrackPressure = false;
2578 
2579   // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2580   // e.g. -misched-bottomup=false allows scheduling in both directions.
2581   assert((!ForceTopDown || !ForceBottomUp) &&
2582          "-misched-topdown incompatible with -misched-bottomup");
2583   if (ForceBottomUp.getNumOccurrences() > 0) {
2584     RegionPolicy.OnlyBottomUp = ForceBottomUp;
2585     if (RegionPolicy.OnlyBottomUp)
2586       RegionPolicy.OnlyTopDown = false;
2587   }
2588   if (ForceTopDown.getNumOccurrences() > 0) {
2589     RegionPolicy.OnlyTopDown = ForceTopDown;
2590     if (RegionPolicy.OnlyTopDown)
2591       RegionPolicy.OnlyBottomUp = false;
2592   }
2593 }
2594 
2595 void GenericScheduler::dumpPolicy() {
2596   // Cannot completely remove virtual function even in release mode.
2597 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2598   dbgs() << "GenericScheduler RegionPolicy: "
2599          << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2600          << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
2601          << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2602          << "\n";
2603 #endif
2604 }
2605 
2606 /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2607 /// critical path by more cycles than it takes to drain the instruction buffer.
2608 /// We estimate an upper bounds on in-flight instructions as:
2609 ///
2610 /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2611 /// InFlightIterations = AcyclicPath / CyclesPerIteration
2612 /// InFlightResources = InFlightIterations * LoopResources
2613 ///
2614 /// TODO: Check execution resources in addition to IssueCount.
2615 void GenericScheduler::checkAcyclicLatency() {
2616   if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2617     return;
2618 
2619   // Scaled number of cycles per loop iteration.
2620   unsigned IterCount =
2621     std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2622              Rem.RemIssueCount);
2623   // Scaled acyclic critical path.
2624   unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2625   // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2626   unsigned InFlightCount =
2627     (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2628   unsigned BufferLimit =
2629     SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2630 
2631   Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2632 
2633   DEBUG(dbgs() << "IssueCycles="
2634         << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2635         << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2636         << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2637         << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2638         << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2639         if (Rem.IsAcyclicLatencyLimited)
2640           dbgs() << "  ACYCLIC LATENCY LIMIT\n");
2641 }
2642 
2643 void GenericScheduler::registerRoots() {
2644   Rem.CriticalPath = DAG->ExitSU.getDepth();
2645 
2646   // Some roots may not feed into ExitSU. Check all of them in case.
2647   for (std::vector<SUnit*>::const_iterator
2648          I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
2649     if ((*I)->getDepth() > Rem.CriticalPath)
2650       Rem.CriticalPath = (*I)->getDepth();
2651   }
2652   DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
2653   if (DumpCriticalPathLength) {
2654     errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
2655   }
2656 
2657   if (EnableCyclicPath) {
2658     Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2659     checkAcyclicLatency();
2660   }
2661 }
2662 
2663 static bool tryPressure(const PressureChange &TryP,
2664                         const PressureChange &CandP,
2665                         GenericSchedulerBase::SchedCandidate &TryCand,
2666                         GenericSchedulerBase::SchedCandidate &Cand,
2667                         GenericSchedulerBase::CandReason Reason,
2668                         const TargetRegisterInfo *TRI,
2669                         const MachineFunction &MF) {
2670   // If one candidate decreases and the other increases, go with it.
2671   // Invalid candidates have UnitInc==0.
2672   if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2673                  Reason)) {
2674     return true;
2675   }
2676   // Do not compare the magnitude of pressure changes between top and bottom
2677   // boundary.
2678   if (Cand.AtTop != TryCand.AtTop)
2679     return false;
2680 
2681   // If both candidates affect the same set in the same boundary, go with the
2682   // smallest increase.
2683   unsigned TryPSet = TryP.getPSetOrMax();
2684   unsigned CandPSet = CandP.getPSetOrMax();
2685   if (TryPSet == CandPSet) {
2686     return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2687                    Reason);
2688   }
2689 
2690   int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
2691                                  std::numeric_limits<int>::max();
2692 
2693   int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
2694                                    std::numeric_limits<int>::max();
2695 
2696   // If the candidates are decreasing pressure, reverse priority.
2697   if (TryP.getUnitInc() < 0)
2698     std::swap(TryRank, CandRank);
2699   return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2700 }
2701 
2702 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2703   return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2704 }
2705 
2706 /// Minimize physical register live ranges. Regalloc wants them adjacent to
2707 /// their physreg def/use.
2708 ///
2709 /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2710 /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2711 /// with the operation that produces or consumes the physreg. We'll do this when
2712 /// regalloc has support for parallel copies.
2713 static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2714   const MachineInstr *MI = SU->getInstr();
2715   if (!MI->isCopy())
2716     return 0;
2717 
2718   unsigned ScheduledOper = isTop ? 1 : 0;
2719   unsigned UnscheduledOper = isTop ? 0 : 1;
2720   // If we have already scheduled the physreg produce/consumer, immediately
2721   // schedule the copy.
2722   if (TargetRegisterInfo::isPhysicalRegister(
2723         MI->getOperand(ScheduledOper).getReg()))
2724     return 1;
2725   // If the physreg is at the boundary, defer it. Otherwise schedule it
2726   // immediately to free the dependent. We can hoist the copy later.
2727   bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2728   if (TargetRegisterInfo::isPhysicalRegister(
2729         MI->getOperand(UnscheduledOper).getReg()))
2730     return AtBoundary ? -1 : 1;
2731   return 0;
2732 }
2733 
2734 void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
2735                                      bool AtTop,
2736                                      const RegPressureTracker &RPTracker,
2737                                      RegPressureTracker &TempTracker) {
2738   Cand.SU = SU;
2739   Cand.AtTop = AtTop;
2740   if (DAG->isTrackingPressure()) {
2741     if (AtTop) {
2742       TempTracker.getMaxDownwardPressureDelta(
2743         Cand.SU->getInstr(),
2744         Cand.RPDelta,
2745         DAG->getRegionCriticalPSets(),
2746         DAG->getRegPressure().MaxSetPressure);
2747     } else {
2748       if (VerifyScheduling) {
2749         TempTracker.getMaxUpwardPressureDelta(
2750           Cand.SU->getInstr(),
2751           &DAG->getPressureDiff(Cand.SU),
2752           Cand.RPDelta,
2753           DAG->getRegionCriticalPSets(),
2754           DAG->getRegPressure().MaxSetPressure);
2755       } else {
2756         RPTracker.getUpwardPressureDelta(
2757           Cand.SU->getInstr(),
2758           DAG->getPressureDiff(Cand.SU),
2759           Cand.RPDelta,
2760           DAG->getRegionCriticalPSets(),
2761           DAG->getRegPressure().MaxSetPressure);
2762       }
2763     }
2764   }
2765   DEBUG(if (Cand.RPDelta.Excess.isValid())
2766           dbgs() << "  Try  SU(" << Cand.SU->NodeNum << ") "
2767                  << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet())
2768                  << ":" << Cand.RPDelta.Excess.getUnitInc() << "\n");
2769 }
2770 
2771 /// Apply a set of heursitics to a new candidate. Heuristics are currently
2772 /// hierarchical. This may be more efficient than a graduated cost model because
2773 /// we don't need to evaluate all aspects of the model for each node in the
2774 /// queue. But it's really done to make the heuristics easier to debug and
2775 /// statistically analyze.
2776 ///
2777 /// \param Cand provides the policy and current best candidate.
2778 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2779 /// \param Zone describes the scheduled zone that we are extending, or nullptr
2780 //              if Cand is from a different zone than TryCand.
2781 void GenericScheduler::tryCandidate(SchedCandidate &Cand,
2782                                     SchedCandidate &TryCand,
2783                                     SchedBoundary *Zone) {
2784   // Initialize the candidate if needed.
2785   if (!Cand.isValid()) {
2786     TryCand.Reason = NodeOrder;
2787     return;
2788   }
2789 
2790   if (tryGreater(biasPhysRegCopy(TryCand.SU, TryCand.AtTop),
2791                  biasPhysRegCopy(Cand.SU, Cand.AtTop),
2792                  TryCand, Cand, PhysRegCopy))
2793     return;
2794 
2795   // Avoid exceeding the target's limit.
2796   if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2797                                                Cand.RPDelta.Excess,
2798                                                TryCand, Cand, RegExcess, TRI,
2799                                                DAG->MF))
2800     return;
2801 
2802   // Avoid increasing the max critical pressure in the scheduled region.
2803   if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2804                                                Cand.RPDelta.CriticalMax,
2805                                                TryCand, Cand, RegCritical, TRI,
2806                                                DAG->MF))
2807     return;
2808 
2809   // We only compare a subset of features when comparing nodes between
2810   // Top and Bottom boundary. Some properties are simply incomparable, in many
2811   // other instances we should only override the other boundary if something
2812   // is a clear good pick on one boundary. Skip heuristics that are more
2813   // "tie-breaking" in nature.
2814   bool SameBoundary = Zone != nullptr;
2815   if (SameBoundary) {
2816     // For loops that are acyclic path limited, aggressively schedule for
2817     // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
2818     // heuristics to take precedence.
2819     if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
2820         tryLatency(TryCand, Cand, *Zone))
2821       return;
2822 
2823     // Prioritize instructions that read unbuffered resources by stall cycles.
2824     if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
2825                 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2826       return;
2827   }
2828 
2829   // Keep clustered nodes together to encourage downstream peephole
2830   // optimizations which may reduce resource requirements.
2831   //
2832   // This is a best effort to set things up for a post-RA pass. Optimizations
2833   // like generating loads of multiple registers should ideally be done within
2834   // the scheduler pass by combining the loads during DAG postprocessing.
2835   const SUnit *CandNextClusterSU =
2836     Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2837   const SUnit *TryCandNextClusterSU =
2838     TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2839   if (tryGreater(TryCand.SU == TryCandNextClusterSU,
2840                  Cand.SU == CandNextClusterSU,
2841                  TryCand, Cand, Cluster))
2842     return;
2843 
2844   if (SameBoundary) {
2845     // Weak edges are for clustering and other constraints.
2846     if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
2847                 getWeakLeft(Cand.SU, Cand.AtTop),
2848                 TryCand, Cand, Weak))
2849       return;
2850   }
2851 
2852   // Avoid increasing the max pressure of the entire region.
2853   if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2854                                                Cand.RPDelta.CurrentMax,
2855                                                TryCand, Cand, RegMax, TRI,
2856                                                DAG->MF))
2857     return;
2858 
2859   if (SameBoundary) {
2860     // Avoid critical resource consumption and balance the schedule.
2861     TryCand.initResourceDelta(DAG, SchedModel);
2862     if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2863                 TryCand, Cand, ResourceReduce))
2864       return;
2865     if (tryGreater(TryCand.ResDelta.DemandedResources,
2866                    Cand.ResDelta.DemandedResources,
2867                    TryCand, Cand, ResourceDemand))
2868       return;
2869 
2870     // Avoid serializing long latency dependence chains.
2871     // For acyclic path limited loops, latency was already checked above.
2872     if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
2873         !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
2874       return;
2875 
2876     // Fall through to original instruction order.
2877     if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2878         || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2879       TryCand.Reason = NodeOrder;
2880     }
2881   }
2882 }
2883 
2884 /// Pick the best candidate from the queue.
2885 ///
2886 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2887 /// DAG building. To adjust for the current scheduling location we need to
2888 /// maintain the number of vreg uses remaining to be top-scheduled.
2889 void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
2890                                          const CandPolicy &ZonePolicy,
2891                                          const RegPressureTracker &RPTracker,
2892                                          SchedCandidate &Cand) {
2893   // getMaxPressureDelta temporarily modifies the tracker.
2894   RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2895 
2896   ReadyQueue &Q = Zone.Available;
2897   for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
2898 
2899     SchedCandidate TryCand(ZonePolicy);
2900     initCandidate(TryCand, *I, Zone.isTop(), RPTracker, TempTracker);
2901     // Pass SchedBoundary only when comparing nodes from the same boundary.
2902     SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
2903     tryCandidate(Cand, TryCand, ZoneArg);
2904     if (TryCand.Reason != NoCand) {
2905       // Initialize resource delta if needed in case future heuristics query it.
2906       if (TryCand.ResDelta == SchedResourceDelta())
2907         TryCand.initResourceDelta(DAG, SchedModel);
2908       Cand.setBest(TryCand);
2909       DEBUG(traceCandidate(Cand));
2910     }
2911   }
2912 }
2913 
2914 /// Pick the best candidate node from either the top or bottom queue.
2915 SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
2916   // Schedule as far as possible in the direction of no choice. This is most
2917   // efficient, but also provides the best heuristics for CriticalPSets.
2918   if (SUnit *SU = Bot.pickOnlyChoice()) {
2919     IsTopNode = false;
2920     tracePick(Only1, false);
2921     return SU;
2922   }
2923   if (SUnit *SU = Top.pickOnlyChoice()) {
2924     IsTopNode = true;
2925     tracePick(Only1, true);
2926     return SU;
2927   }
2928   // Set the bottom-up policy based on the state of the current bottom zone and
2929   // the instructions outside the zone, including the top zone.
2930   CandPolicy BotPolicy;
2931   setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
2932   // Set the top-down policy based on the state of the current top zone and
2933   // the instructions outside the zone, including the bottom zone.
2934   CandPolicy TopPolicy;
2935   setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
2936 
2937   // See if BotCand is still valid (because we previously scheduled from Top).
2938   DEBUG(dbgs() << "Picking from Bot:\n");
2939   if (!BotCand.isValid() || BotCand.SU->isScheduled ||
2940       BotCand.Policy != BotPolicy) {
2941     BotCand.reset(CandPolicy());
2942     pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
2943     assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2944   } else {
2945     DEBUG(traceCandidate(BotCand));
2946 #ifndef NDEBUG
2947     if (VerifyScheduling) {
2948       SchedCandidate TCand;
2949       TCand.reset(CandPolicy());
2950       pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
2951       assert(TCand.SU == BotCand.SU &&
2952              "Last pick result should correspond to re-picking right now");
2953     }
2954 #endif
2955   }
2956 
2957   // Check if the top Q has a better candidate.
2958   DEBUG(dbgs() << "Picking from Top:\n");
2959   if (!TopCand.isValid() || TopCand.SU->isScheduled ||
2960       TopCand.Policy != TopPolicy) {
2961     TopCand.reset(CandPolicy());
2962     pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
2963     assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2964   } else {
2965     DEBUG(traceCandidate(TopCand));
2966 #ifndef NDEBUG
2967     if (VerifyScheduling) {
2968       SchedCandidate TCand;
2969       TCand.reset(CandPolicy());
2970       pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
2971       assert(TCand.SU == TopCand.SU &&
2972            "Last pick result should correspond to re-picking right now");
2973     }
2974 #endif
2975   }
2976 
2977   // Pick best from BotCand and TopCand.
2978   assert(BotCand.isValid());
2979   assert(TopCand.isValid());
2980   SchedCandidate Cand = BotCand;
2981   TopCand.Reason = NoCand;
2982   tryCandidate(Cand, TopCand, nullptr);
2983   if (TopCand.Reason != NoCand) {
2984     Cand.setBest(TopCand);
2985     DEBUG(traceCandidate(Cand));
2986   }
2987 
2988   IsTopNode = Cand.AtTop;
2989   tracePick(Cand);
2990   return Cand.SU;
2991 }
2992 
2993 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
2994 SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
2995   if (DAG->top() == DAG->bottom()) {
2996     assert(Top.Available.empty() && Top.Pending.empty() &&
2997            Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
2998     return nullptr;
2999   }
3000   SUnit *SU;
3001   do {
3002     if (RegionPolicy.OnlyTopDown) {
3003       SU = Top.pickOnlyChoice();
3004       if (!SU) {
3005         CandPolicy NoPolicy;
3006         TopCand.reset(NoPolicy);
3007         pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
3008         assert(TopCand.Reason != NoCand && "failed to find a candidate");
3009         tracePick(TopCand);
3010         SU = TopCand.SU;
3011       }
3012       IsTopNode = true;
3013     } else if (RegionPolicy.OnlyBottomUp) {
3014       SU = Bot.pickOnlyChoice();
3015       if (!SU) {
3016         CandPolicy NoPolicy;
3017         BotCand.reset(NoPolicy);
3018         pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
3019         assert(BotCand.Reason != NoCand && "failed to find a candidate");
3020         tracePick(BotCand);
3021         SU = BotCand.SU;
3022       }
3023       IsTopNode = false;
3024     } else {
3025       SU = pickNodeBidirectional(IsTopNode);
3026     }
3027   } while (SU->isScheduled);
3028 
3029   if (SU->isTopReady())
3030     Top.removeReady(SU);
3031   if (SU->isBottomReady())
3032     Bot.removeReady(SU);
3033 
3034   DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
3035   return SU;
3036 }
3037 
3038 void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
3039 
3040   MachineBasicBlock::iterator InsertPos = SU->getInstr();
3041   if (!isTop)
3042     ++InsertPos;
3043   SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
3044 
3045   // Find already scheduled copies with a single physreg dependence and move
3046   // them just above the scheduled instruction.
3047   for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
3048        I != E; ++I) {
3049     if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
3050       continue;
3051     SUnit *DepSU = I->getSUnit();
3052     if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
3053       continue;
3054     MachineInstr *Copy = DepSU->getInstr();
3055     if (!Copy->isCopy())
3056       continue;
3057     DEBUG(dbgs() << "  Rescheduling physreg copy ";
3058           I->getSUnit()->dump(DAG));
3059     DAG->moveInstruction(Copy, InsertPos);
3060   }
3061 }
3062 
3063 /// Update the scheduler's state after scheduling a node. This is the same node
3064 /// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
3065 /// update it's state based on the current cycle before MachineSchedStrategy
3066 /// does.
3067 ///
3068 /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
3069 /// them here. See comments in biasPhysRegCopy.
3070 void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3071   if (IsTopNode) {
3072     SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3073     Top.bumpNode(SU);
3074     if (SU->hasPhysRegUses)
3075       reschedulePhysRegCopies(SU, true);
3076   } else {
3077     SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
3078     Bot.bumpNode(SU);
3079     if (SU->hasPhysRegDefs)
3080       reschedulePhysRegCopies(SU, false);
3081   }
3082 }
3083 
3084 /// Create the standard converging machine scheduler. This will be used as the
3085 /// default scheduler if the target does not set a default.
3086 ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
3087   ScheduleDAGMILive *DAG = new ScheduleDAGMILive(C, make_unique<GenericScheduler>(C));
3088   // Register DAG post-processors.
3089   //
3090   // FIXME: extend the mutation API to allow earlier mutations to instantiate
3091   // data and pass it to later mutations. Have a single mutation that gathers
3092   // the interesting nodes in one pass.
3093   DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
3094   return DAG;
3095 }
3096 
3097 static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) {
3098   return createGenericSchedLive(C);
3099 }
3100 
3101 static MachineSchedRegistry
3102 GenericSchedRegistry("converge", "Standard converging scheduler.",
3103                      createConveringSched);
3104 
3105 //===----------------------------------------------------------------------===//
3106 // PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3107 //===----------------------------------------------------------------------===//
3108 
3109 void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
3110   DAG = Dag;
3111   SchedModel = DAG->getSchedModel();
3112   TRI = DAG->TRI;
3113 
3114   Rem.init(DAG, SchedModel);
3115   Top.init(DAG, SchedModel, &Rem);
3116   BotRoots.clear();
3117 
3118   // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3119   // or are disabled, then these HazardRecs will be disabled.
3120   const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
3121   if (!Top.HazardRec) {
3122     Top.HazardRec =
3123         DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
3124             Itin, DAG);
3125   }
3126 }
3127 
3128 
3129 void PostGenericScheduler::registerRoots() {
3130   Rem.CriticalPath = DAG->ExitSU.getDepth();
3131 
3132   // Some roots may not feed into ExitSU. Check all of them in case.
3133   for (SmallVectorImpl<SUnit*>::const_iterator
3134          I = BotRoots.begin(), E = BotRoots.end(); I != E; ++I) {
3135     if ((*I)->getDepth() > Rem.CriticalPath)
3136       Rem.CriticalPath = (*I)->getDepth();
3137   }
3138   DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
3139   if (DumpCriticalPathLength) {
3140     errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
3141   }
3142 }
3143 
3144 /// Apply a set of heursitics to a new candidate for PostRA scheduling.
3145 ///
3146 /// \param Cand provides the policy and current best candidate.
3147 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3148 void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3149                                         SchedCandidate &TryCand) {
3150 
3151   // Initialize the candidate if needed.
3152   if (!Cand.isValid()) {
3153     TryCand.Reason = NodeOrder;
3154     return;
3155   }
3156 
3157   // Prioritize instructions that read unbuffered resources by stall cycles.
3158   if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3159               Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3160     return;
3161 
3162   // Avoid critical resource consumption and balance the schedule.
3163   if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3164               TryCand, Cand, ResourceReduce))
3165     return;
3166   if (tryGreater(TryCand.ResDelta.DemandedResources,
3167                  Cand.ResDelta.DemandedResources,
3168                  TryCand, Cand, ResourceDemand))
3169     return;
3170 
3171   // Avoid serializing long latency dependence chains.
3172   if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3173     return;
3174   }
3175 
3176   // Fall through to original instruction order.
3177   if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3178     TryCand.Reason = NodeOrder;
3179 }
3180 
3181 void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3182   ReadyQueue &Q = Top.Available;
3183   for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
3184     SchedCandidate TryCand(Cand.Policy);
3185     TryCand.SU = *I;
3186     TryCand.AtTop = true;
3187     TryCand.initResourceDelta(DAG, SchedModel);
3188     tryCandidate(Cand, TryCand);
3189     if (TryCand.Reason != NoCand) {
3190       Cand.setBest(TryCand);
3191       DEBUG(traceCandidate(Cand));
3192     }
3193   }
3194 }
3195 
3196 /// Pick the next node to schedule.
3197 SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3198   if (DAG->top() == DAG->bottom()) {
3199     assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
3200     return nullptr;
3201   }
3202   SUnit *SU;
3203   do {
3204     SU = Top.pickOnlyChoice();
3205     if (SU) {
3206       tracePick(Only1, true);
3207     } else {
3208       CandPolicy NoPolicy;
3209       SchedCandidate TopCand(NoPolicy);
3210       // Set the top-down policy based on the state of the current top zone and
3211       // the instructions outside the zone, including the bottom zone.
3212       setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
3213       pickNodeFromQueue(TopCand);
3214       assert(TopCand.Reason != NoCand && "failed to find a candidate");
3215       tracePick(TopCand);
3216       SU = TopCand.SU;
3217     }
3218   } while (SU->isScheduled);
3219 
3220   IsTopNode = true;
3221   Top.removeReady(SU);
3222 
3223   DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
3224   return SU;
3225 }
3226 
3227 /// Called after ScheduleDAGMI has scheduled an instruction and updated
3228 /// scheduled/remaining flags in the DAG nodes.
3229 void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3230   SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3231   Top.bumpNode(SU);
3232 }
3233 
3234 ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
3235   return new ScheduleDAGMI(C, make_unique<PostGenericScheduler>(C),
3236                            /*RemoveKillFlags=*/true);
3237 }
3238 
3239 //===----------------------------------------------------------------------===//
3240 // ILP Scheduler. Currently for experimental analysis of heuristics.
3241 //===----------------------------------------------------------------------===//
3242 
3243 namespace {
3244 /// \brief Order nodes by the ILP metric.
3245 struct ILPOrder {
3246   const SchedDFSResult *DFSResult;
3247   const BitVector *ScheduledTrees;
3248   bool MaximizeILP;
3249 
3250   ILPOrder(bool MaxILP)
3251     : DFSResult(nullptr), ScheduledTrees(nullptr), MaximizeILP(MaxILP) {}
3252 
3253   /// \brief Apply a less-than relation on node priority.
3254   ///
3255   /// (Return true if A comes after B in the Q.)
3256   bool operator()(const SUnit *A, const SUnit *B) const {
3257     unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3258     unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3259     if (SchedTreeA != SchedTreeB) {
3260       // Unscheduled trees have lower priority.
3261       if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3262         return ScheduledTrees->test(SchedTreeB);
3263 
3264       // Trees with shallower connections have have lower priority.
3265       if (DFSResult->getSubtreeLevel(SchedTreeA)
3266           != DFSResult->getSubtreeLevel(SchedTreeB)) {
3267         return DFSResult->getSubtreeLevel(SchedTreeA)
3268           < DFSResult->getSubtreeLevel(SchedTreeB);
3269       }
3270     }
3271     if (MaximizeILP)
3272       return DFSResult->getILP(A) < DFSResult->getILP(B);
3273     else
3274       return DFSResult->getILP(A) > DFSResult->getILP(B);
3275   }
3276 };
3277 
3278 /// \brief Schedule based on the ILP metric.
3279 class ILPScheduler : public MachineSchedStrategy {
3280   ScheduleDAGMILive *DAG;
3281   ILPOrder Cmp;
3282 
3283   std::vector<SUnit*> ReadyQ;
3284 public:
3285   ILPScheduler(bool MaximizeILP): DAG(nullptr), Cmp(MaximizeILP) {}
3286 
3287   void initialize(ScheduleDAGMI *dag) override {
3288     assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3289     DAG = static_cast<ScheduleDAGMILive*>(dag);
3290     DAG->computeDFSResult();
3291     Cmp.DFSResult = DAG->getDFSResult();
3292     Cmp.ScheduledTrees = &DAG->getScheduledTrees();
3293     ReadyQ.clear();
3294   }
3295 
3296   void registerRoots() override {
3297     // Restore the heap in ReadyQ with the updated DFS results.
3298     std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3299   }
3300 
3301   /// Implement MachineSchedStrategy interface.
3302   /// -----------------------------------------
3303 
3304   /// Callback to select the highest priority node from the ready Q.
3305   SUnit *pickNode(bool &IsTopNode) override {
3306     if (ReadyQ.empty()) return nullptr;
3307     std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3308     SUnit *SU = ReadyQ.back();
3309     ReadyQ.pop_back();
3310     IsTopNode = false;
3311     DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
3312           << " ILP: " << DAG->getDFSResult()->getILP(SU)
3313           << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3314           << DAG->getDFSResult()->getSubtreeLevel(
3315             DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3316           << "Scheduling " << *SU->getInstr());
3317     return SU;
3318   }
3319 
3320   /// \brief Scheduler callback to notify that a new subtree is scheduled.
3321   void scheduleTree(unsigned SubtreeID) override {
3322     std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3323   }
3324 
3325   /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3326   /// DFSResults, and resort the priority Q.
3327   void schedNode(SUnit *SU, bool IsTopNode) override {
3328     assert(!IsTopNode && "SchedDFSResult needs bottom-up");
3329   }
3330 
3331   void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
3332 
3333   void releaseBottomNode(SUnit *SU) override {
3334     ReadyQ.push_back(SU);
3335     std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3336   }
3337 };
3338 } // namespace
3339 
3340 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
3341   return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(true));
3342 }
3343 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
3344   return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(false));
3345 }
3346 static MachineSchedRegistry ILPMaxRegistry(
3347   "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3348 static MachineSchedRegistry ILPMinRegistry(
3349   "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3350 
3351 //===----------------------------------------------------------------------===//
3352 // Machine Instruction Shuffler for Correctness Testing
3353 //===----------------------------------------------------------------------===//
3354 
3355 #ifndef NDEBUG
3356 namespace {
3357 /// Apply a less-than relation on the node order, which corresponds to the
3358 /// instruction order prior to scheduling. IsReverse implements greater-than.
3359 template<bool IsReverse>
3360 struct SUnitOrder {
3361   bool operator()(SUnit *A, SUnit *B) const {
3362     if (IsReverse)
3363       return A->NodeNum > B->NodeNum;
3364     else
3365       return A->NodeNum < B->NodeNum;
3366   }
3367 };
3368 
3369 /// Reorder instructions as much as possible.
3370 class InstructionShuffler : public MachineSchedStrategy {
3371   bool IsAlternating;
3372   bool IsTopDown;
3373 
3374   // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3375   // gives nodes with a higher number higher priority causing the latest
3376   // instructions to be scheduled first.
3377   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
3378     TopQ;
3379   // When scheduling bottom-up, use greater-than as the queue priority.
3380   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
3381     BottomQ;
3382 public:
3383   InstructionShuffler(bool alternate, bool topdown)
3384     : IsAlternating(alternate), IsTopDown(topdown) {}
3385 
3386   void initialize(ScheduleDAGMI*) override {
3387     TopQ.clear();
3388     BottomQ.clear();
3389   }
3390 
3391   /// Implement MachineSchedStrategy interface.
3392   /// -----------------------------------------
3393 
3394   SUnit *pickNode(bool &IsTopNode) override {
3395     SUnit *SU;
3396     if (IsTopDown) {
3397       do {
3398         if (TopQ.empty()) return nullptr;
3399         SU = TopQ.top();
3400         TopQ.pop();
3401       } while (SU->isScheduled);
3402       IsTopNode = true;
3403     } else {
3404       do {
3405         if (BottomQ.empty()) return nullptr;
3406         SU = BottomQ.top();
3407         BottomQ.pop();
3408       } while (SU->isScheduled);
3409       IsTopNode = false;
3410     }
3411     if (IsAlternating)
3412       IsTopDown = !IsTopDown;
3413     return SU;
3414   }
3415 
3416   void schedNode(SUnit *SU, bool IsTopNode) override {}
3417 
3418   void releaseTopNode(SUnit *SU) override {
3419     TopQ.push(SU);
3420   }
3421   void releaseBottomNode(SUnit *SU) override {
3422     BottomQ.push(SU);
3423   }
3424 };
3425 } // namespace
3426 
3427 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
3428   bool Alternate = !ForceTopDown && !ForceBottomUp;
3429   bool TopDown = !ForceBottomUp;
3430   assert((TopDown || !ForceTopDown) &&
3431          "-misched-topdown incompatible with -misched-bottomup");
3432   return new ScheduleDAGMILive(C, make_unique<InstructionShuffler>(Alternate, TopDown));
3433 }
3434 static MachineSchedRegistry ShufflerRegistry(
3435   "shuffle", "Shuffle machine instructions alternating directions",
3436   createInstructionShuffler);
3437 #endif // !NDEBUG
3438 
3439 //===----------------------------------------------------------------------===//
3440 // GraphWriter support for ScheduleDAGMILive.
3441 //===----------------------------------------------------------------------===//
3442 
3443 #ifndef NDEBUG
3444 namespace llvm {
3445 
3446 template<> struct GraphTraits<
3447   ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3448 
3449 template<>
3450 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
3451 
3452   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3453 
3454   static std::string getGraphName(const ScheduleDAG *G) {
3455     return G->MF.getName();
3456   }
3457 
3458   static bool renderGraphFromBottomUp() {
3459     return true;
3460   }
3461 
3462   static bool isNodeHidden(const SUnit *Node) {
3463     if (ViewMISchedCutoff == 0)
3464       return false;
3465     return (Node->Preds.size() > ViewMISchedCutoff
3466          || Node->Succs.size() > ViewMISchedCutoff);
3467   }
3468 
3469   /// If you want to override the dot attributes printed for a particular
3470   /// edge, override this method.
3471   static std::string getEdgeAttributes(const SUnit *Node,
3472                                        SUnitIterator EI,
3473                                        const ScheduleDAG *Graph) {
3474     if (EI.isArtificialDep())
3475       return "color=cyan,style=dashed";
3476     if (EI.isCtrlDep())
3477       return "color=blue,style=dashed";
3478     return "";
3479   }
3480 
3481   static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
3482     std::string Str;
3483     raw_string_ostream SS(Str);
3484     const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3485     const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3486       static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
3487     SS << "SU:" << SU->NodeNum;
3488     if (DFS)
3489       SS << " I:" << DFS->getNumInstrs(SU);
3490     return SS.str();
3491   }
3492   static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3493     return G->getGraphNodeLabel(SU);
3494   }
3495 
3496   static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
3497     std::string Str("shape=Mrecord");
3498     const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3499     const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3500       static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
3501     if (DFS) {
3502       Str += ",style=filled,fillcolor=\"#";
3503       Str += DOT::getColorString(DFS->getSubtreeID(N));
3504       Str += '"';
3505     }
3506     return Str;
3507   }
3508 };
3509 } // namespace llvm
3510 #endif // NDEBUG
3511 
3512 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3513 /// rendered using 'dot'.
3514 ///
3515 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3516 #ifndef NDEBUG
3517   ViewGraph(this, Name, false, Title);
3518 #else
3519   errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3520          << "systems with Graphviz or gv!\n";
3521 #endif  // NDEBUG
3522 }
3523 
3524 /// Out-of-line implementation with no arguments is handy for gdb.
3525 void ScheduleDAGMI::viewGraph() {
3526   viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3527 }
3528