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