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