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