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