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