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