xref: /llvm-project/llvm/lib/CodeGen/MachinePipeliner.cpp (revision 80f6b42a26ec7594e6b016c5dde5d57db6c9dfb1)
1 //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
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 // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
10 //
11 // This SMS implementation is a target-independent back-end pass. When enabled,
12 // the pass runs just prior to the register allocation pass, while the machine
13 // IR is in SSA form. If software pipelining is successful, then the original
14 // loop is replaced by the optimized loop. The optimized loop contains one or
15 // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
16 // the instructions cannot be scheduled in a given MII, we increase the MII by
17 // one and try again.
18 //
19 // The SMS implementation is an extension of the ScheduleDAGInstrs class. We
20 // represent loop carried dependences in the DAG as order edges to the Phi
21 // nodes. We also perform several passes over the DAG to eliminate unnecessary
22 // edges that inhibit the ability to pipeline. The implementation uses the
23 // DFAPacketizer class to compute the minimum initiation interval and the check
24 // where an instruction may be inserted in the pipelined schedule.
25 //
26 // In order for the SMS pass to work, several target specific hooks need to be
27 // implemented to get information about the loop structure and to rewrite
28 // instructions.
29 //
30 //===----------------------------------------------------------------------===//
31 
32 #include "llvm/CodeGen/MachinePipeliner.h"
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/BitVector.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/MapVector.h"
37 #include "llvm/ADT/PriorityQueue.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SetOperations.h"
40 #include "llvm/ADT/SetVector.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/iterator_range.h"
46 #include "llvm/Analysis/AliasAnalysis.h"
47 #include "llvm/Analysis/CycleAnalysis.h"
48 #include "llvm/Analysis/MemoryLocation.h"
49 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
50 #include "llvm/Analysis/ValueTracking.h"
51 #include "llvm/CodeGen/DFAPacketizer.h"
52 #include "llvm/CodeGen/LiveIntervals.h"
53 #include "llvm/CodeGen/MachineBasicBlock.h"
54 #include "llvm/CodeGen/MachineDominators.h"
55 #include "llvm/CodeGen/MachineFunction.h"
56 #include "llvm/CodeGen/MachineFunctionPass.h"
57 #include "llvm/CodeGen/MachineInstr.h"
58 #include "llvm/CodeGen/MachineInstrBuilder.h"
59 #include "llvm/CodeGen/MachineLoopInfo.h"
60 #include "llvm/CodeGen/MachineMemOperand.h"
61 #include "llvm/CodeGen/MachineOperand.h"
62 #include "llvm/CodeGen/MachineRegisterInfo.h"
63 #include "llvm/CodeGen/ModuloSchedule.h"
64 #include "llvm/CodeGen/Register.h"
65 #include "llvm/CodeGen/RegisterClassInfo.h"
66 #include "llvm/CodeGen/RegisterPressure.h"
67 #include "llvm/CodeGen/ScheduleDAG.h"
68 #include "llvm/CodeGen/ScheduleDAGMutation.h"
69 #include "llvm/CodeGen/TargetInstrInfo.h"
70 #include "llvm/CodeGen/TargetOpcodes.h"
71 #include "llvm/CodeGen/TargetPassConfig.h"
72 #include "llvm/CodeGen/TargetRegisterInfo.h"
73 #include "llvm/CodeGen/TargetSubtargetInfo.h"
74 #include "llvm/Config/llvm-config.h"
75 #include "llvm/IR/Attributes.h"
76 #include "llvm/IR/Function.h"
77 #include "llvm/MC/LaneBitmask.h"
78 #include "llvm/MC/MCInstrDesc.h"
79 #include "llvm/MC/MCInstrItineraries.h"
80 #include "llvm/MC/MCRegisterInfo.h"
81 #include "llvm/Pass.h"
82 #include "llvm/Support/CommandLine.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/Debug.h"
85 #include "llvm/Support/MathExtras.h"
86 #include "llvm/Support/raw_ostream.h"
87 #include <algorithm>
88 #include <cassert>
89 #include <climits>
90 #include <cstdint>
91 #include <deque>
92 #include <functional>
93 #include <iomanip>
94 #include <iterator>
95 #include <map>
96 #include <memory>
97 #include <sstream>
98 #include <tuple>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 
104 #define DEBUG_TYPE "pipeliner"
105 
106 STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
107 STATISTIC(NumPipelined, "Number of loops software pipelined");
108 STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
109 STATISTIC(NumFailBranch, "Pipeliner abort due to unknown branch");
110 STATISTIC(NumFailLoop, "Pipeliner abort due to unsupported loop");
111 STATISTIC(NumFailPreheader, "Pipeliner abort due to missing preheader");
112 STATISTIC(NumFailLargeMaxMII, "Pipeliner abort due to MaxMII too large");
113 STATISTIC(NumFailZeroMII, "Pipeliner abort due to zero MII");
114 STATISTIC(NumFailNoSchedule, "Pipeliner abort due to no schedule found");
115 STATISTIC(NumFailZeroStage, "Pipeliner abort due to zero stage");
116 STATISTIC(NumFailLargeMaxStage, "Pipeliner abort due to too many stages");
117 
118 /// A command line option to turn software pipelining on or off.
119 static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
120                                cl::desc("Enable Software Pipelining"));
121 
122 /// A command line option to enable SWP at -Os.
123 static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
124                                       cl::desc("Enable SWP at Os."), cl::Hidden,
125                                       cl::init(false));
126 
127 /// A command line argument to limit minimum initial interval for pipelining.
128 static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
129                               cl::desc("Size limit for the MII."),
130                               cl::Hidden, cl::init(27));
131 
132 /// A command line argument to force pipeliner to use specified initial
133 /// interval.
134 static cl::opt<int> SwpForceII("pipeliner-force-ii",
135                                cl::desc("Force pipeliner to use specified II."),
136                                cl::Hidden, cl::init(-1));
137 
138 /// A command line argument to limit the number of stages in the pipeline.
139 static cl::opt<int>
140     SwpMaxStages("pipeliner-max-stages",
141                  cl::desc("Maximum stages allowed in the generated scheduled."),
142                  cl::Hidden, cl::init(3));
143 
144 /// A command line option to disable the pruning of chain dependences due to
145 /// an unrelated Phi.
146 static cl::opt<bool>
147     SwpPruneDeps("pipeliner-prune-deps",
148                  cl::desc("Prune dependences between unrelated Phi nodes."),
149                  cl::Hidden, cl::init(true));
150 
151 /// A command line option to disable the pruning of loop carried order
152 /// dependences.
153 static cl::opt<bool>
154     SwpPruneLoopCarried("pipeliner-prune-loop-carried",
155                         cl::desc("Prune loop carried order dependences."),
156                         cl::Hidden, cl::init(true));
157 
158 #ifndef NDEBUG
159 static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
160 #endif
161 
162 static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
163                                      cl::ReallyHidden,
164                                      cl::desc("Ignore RecMII"));
165 
166 static cl::opt<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden,
167                                     cl::init(false));
168 static cl::opt<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden,
169                                       cl::init(false));
170 
171 static cl::opt<bool> EmitTestAnnotations(
172     "pipeliner-annotate-for-testing", cl::Hidden, cl::init(false),
173     cl::desc("Instead of emitting the pipelined code, annotate instructions "
174              "with the generated schedule for feeding into the "
175              "-modulo-schedule-test pass"));
176 
177 static cl::opt<bool> ExperimentalCodeGen(
178     "pipeliner-experimental-cg", cl::Hidden, cl::init(false),
179     cl::desc(
180         "Use the experimental peeling code generator for software pipelining"));
181 
182 static cl::opt<int> SwpIISearchRange("pipeliner-ii-search-range",
183                                      cl::desc("Range to search for II"),
184                                      cl::Hidden, cl::init(10));
185 
186 static cl::opt<bool>
187     LimitRegPressure("pipeliner-register-pressure", cl::Hidden, cl::init(false),
188                      cl::desc("Limit register pressure of scheduled loop"));
189 
190 static cl::opt<int>
191     RegPressureMargin("pipeliner-register-pressure-margin", cl::Hidden,
192                       cl::init(5),
193                       cl::desc("Margin representing the unused percentage of "
194                                "the register pressure limit"));
195 
196 static cl::opt<bool>
197     MVECodeGen("pipeliner-mve-cg", cl::Hidden, cl::init(false),
198                cl::desc("Use the MVE code generator for software pipelining"));
199 
200 namespace llvm {
201 
202 // A command line option to enable the CopyToPhi DAG mutation.
203 cl::opt<bool> SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
204                                  cl::init(true),
205                                  cl::desc("Enable CopyToPhi DAG Mutation"));
206 
207 /// A command line argument to force pipeliner to use specified issue
208 /// width.
209 cl::opt<int> SwpForceIssueWidth(
210     "pipeliner-force-issue-width",
211     cl::desc("Force pipeliner to use specified issue width."), cl::Hidden,
212     cl::init(-1));
213 
214 /// A command line argument to set the window scheduling option.
215 cl::opt<WindowSchedulingFlag> WindowSchedulingOption(
216     "window-sched", cl::Hidden, cl::init(WindowSchedulingFlag::WS_On),
217     cl::desc("Set how to use window scheduling algorithm."),
218     cl::values(clEnumValN(WindowSchedulingFlag::WS_Off, "off",
219                           "Turn off window algorithm."),
220                clEnumValN(WindowSchedulingFlag::WS_On, "on",
221                           "Use window algorithm after SMS algorithm fails."),
222                clEnumValN(WindowSchedulingFlag::WS_Force, "force",
223                           "Use window algorithm instead of SMS algorithm.")));
224 
225 } // end namespace llvm
226 
227 unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
228 char MachinePipeliner::ID = 0;
229 #ifndef NDEBUG
230 int MachinePipeliner::NumTries = 0;
231 #endif
232 char &llvm::MachinePipelinerID = MachinePipeliner::ID;
233 
234 INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
235                       "Modulo Software Pipelining", false, false)
236 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
237 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
238 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
239 INITIALIZE_PASS_DEPENDENCY(LiveIntervalsWrapperPass)
240 INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
241                     "Modulo Software Pipelining", false, false)
242 
243 /// The "main" function for implementing Swing Modulo Scheduling.
244 bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
245   if (skipFunction(mf.getFunction()))
246     return false;
247 
248   if (!EnableSWP)
249     return false;
250 
251   if (mf.getFunction().getAttributes().hasFnAttr(Attribute::OptimizeForSize) &&
252       !EnableSWPOptSize.getPosition())
253     return false;
254 
255   if (!mf.getSubtarget().enableMachinePipeliner())
256     return false;
257 
258   // Cannot pipeline loops without instruction itineraries if we are using
259   // DFA for the pipeliner.
260   if (mf.getSubtarget().useDFAforSMS() &&
261       (!mf.getSubtarget().getInstrItineraryData() ||
262        mf.getSubtarget().getInstrItineraryData()->isEmpty()))
263     return false;
264 
265   MF = &mf;
266   MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
267   MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
268   ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
269   TII = MF->getSubtarget().getInstrInfo();
270   RegClassInfo.runOnMachineFunction(*MF);
271 
272   for (const auto &L : *MLI)
273     scheduleLoop(*L);
274 
275   return false;
276 }
277 
278 /// Attempt to perform the SMS algorithm on the specified loop. This function is
279 /// the main entry point for the algorithm.  The function identifies candidate
280 /// loops, calculates the minimum initiation interval, and attempts to schedule
281 /// the loop.
282 bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
283   bool Changed = false;
284   for (const auto &InnerLoop : L)
285     Changed |= scheduleLoop(*InnerLoop);
286 
287 #ifndef NDEBUG
288   // Stop trying after reaching the limit (if any).
289   int Limit = SwpLoopLimit;
290   if (Limit >= 0) {
291     if (NumTries >= SwpLoopLimit)
292       return Changed;
293     NumTries++;
294   }
295 #endif
296 
297   setPragmaPipelineOptions(L);
298   if (!canPipelineLoop(L)) {
299     LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
300     ORE->emit([&]() {
301       return MachineOptimizationRemarkMissed(DEBUG_TYPE, "canPipelineLoop",
302                                              L.getStartLoc(), L.getHeader())
303              << "Failed to pipeline loop";
304     });
305 
306     LI.LoopPipelinerInfo.reset();
307     return Changed;
308   }
309 
310   ++NumTrytoPipeline;
311   if (useSwingModuloScheduler())
312     Changed = swingModuloScheduler(L);
313 
314   if (useWindowScheduler(Changed))
315     Changed = runWindowScheduler(L);
316 
317   LI.LoopPipelinerInfo.reset();
318   return Changed;
319 }
320 
321 void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) {
322   // Reset the pragma for the next loop in iteration.
323   disabledByPragma = false;
324   II_setByPragma = 0;
325 
326   MachineBasicBlock *LBLK = L.getTopBlock();
327 
328   if (LBLK == nullptr)
329     return;
330 
331   const BasicBlock *BBLK = LBLK->getBasicBlock();
332   if (BBLK == nullptr)
333     return;
334 
335   const Instruction *TI = BBLK->getTerminator();
336   if (TI == nullptr)
337     return;
338 
339   MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop);
340   if (LoopID == nullptr)
341     return;
342 
343   assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
344   assert(LoopID->getOperand(0) == LoopID && "invalid loop");
345 
346   for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
347     MDNode *MD = dyn_cast<MDNode>(MDO);
348 
349     if (MD == nullptr)
350       continue;
351 
352     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
353 
354     if (S == nullptr)
355       continue;
356 
357     if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
358       assert(MD->getNumOperands() == 2 &&
359              "Pipeline initiation interval hint metadata should have two operands.");
360       II_setByPragma =
361           mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
362       assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
363     } else if (S->getString() == "llvm.loop.pipeline.disable") {
364       disabledByPragma = true;
365     }
366   }
367 }
368 
369 /// Return true if the loop can be software pipelined.  The algorithm is
370 /// restricted to loops with a single basic block.  Make sure that the
371 /// branch in the loop can be analyzed.
372 bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
373   if (L.getNumBlocks() != 1) {
374     ORE->emit([&]() {
375       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
376                                                L.getStartLoc(), L.getHeader())
377              << "Not a single basic block: "
378              << ore::NV("NumBlocks", L.getNumBlocks());
379     });
380     return false;
381   }
382 
383   if (disabledByPragma) {
384     ORE->emit([&]() {
385       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
386                                                L.getStartLoc(), L.getHeader())
387              << "Disabled by Pragma.";
388     });
389     return false;
390   }
391 
392   // Check if the branch can't be understood because we can't do pipelining
393   // if that's the case.
394   LI.TBB = nullptr;
395   LI.FBB = nullptr;
396   LI.BrCond.clear();
397   if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) {
398     LLVM_DEBUG(dbgs() << "Unable to analyzeBranch, can NOT pipeline Loop\n");
399     NumFailBranch++;
400     ORE->emit([&]() {
401       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
402                                                L.getStartLoc(), L.getHeader())
403              << "The branch can't be understood";
404     });
405     return false;
406   }
407 
408   LI.LoopInductionVar = nullptr;
409   LI.LoopCompare = nullptr;
410   LI.LoopPipelinerInfo = TII->analyzeLoopForPipelining(L.getTopBlock());
411   if (!LI.LoopPipelinerInfo) {
412     LLVM_DEBUG(dbgs() << "Unable to analyzeLoop, can NOT pipeline Loop\n");
413     NumFailLoop++;
414     ORE->emit([&]() {
415       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
416                                                L.getStartLoc(), L.getHeader())
417              << "The loop structure is not supported";
418     });
419     return false;
420   }
421 
422   if (!L.getLoopPreheader()) {
423     LLVM_DEBUG(dbgs() << "Preheader not found, can NOT pipeline Loop\n");
424     NumFailPreheader++;
425     ORE->emit([&]() {
426       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
427                                                L.getStartLoc(), L.getHeader())
428              << "No loop preheader found";
429     });
430     return false;
431   }
432 
433   // Remove any subregisters from inputs to phi nodes.
434   preprocessPhiNodes(*L.getHeader());
435   return true;
436 }
437 
438 void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
439   MachineRegisterInfo &MRI = MF->getRegInfo();
440   SlotIndexes &Slots =
441       *getAnalysis<LiveIntervalsWrapperPass>().getLIS().getSlotIndexes();
442 
443   for (MachineInstr &PI : B.phis()) {
444     MachineOperand &DefOp = PI.getOperand(0);
445     assert(DefOp.getSubReg() == 0);
446     auto *RC = MRI.getRegClass(DefOp.getReg());
447 
448     for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
449       MachineOperand &RegOp = PI.getOperand(i);
450       if (RegOp.getSubReg() == 0)
451         continue;
452 
453       // If the operand uses a subregister, replace it with a new register
454       // without subregisters, and generate a copy to the new register.
455       Register NewReg = MRI.createVirtualRegister(RC);
456       MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
457       MachineBasicBlock::iterator At = PredB.getFirstTerminator();
458       const DebugLoc &DL = PredB.findDebugLoc(At);
459       auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
460                     .addReg(RegOp.getReg(), getRegState(RegOp),
461                             RegOp.getSubReg());
462       Slots.insertMachineInstrInMaps(*Copy);
463       RegOp.setReg(NewReg);
464       RegOp.setSubReg(0);
465     }
466   }
467 }
468 
469 /// The SMS algorithm consists of the following main steps:
470 /// 1. Computation and analysis of the dependence graph.
471 /// 2. Ordering of the nodes (instructions).
472 /// 3. Attempt to Schedule the loop.
473 bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
474   assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
475 
476   SwingSchedulerDAG SMS(
477       *this, L, getAnalysis<LiveIntervalsWrapperPass>().getLIS(), RegClassInfo,
478       II_setByPragma, LI.LoopPipelinerInfo.get());
479 
480   MachineBasicBlock *MBB = L.getHeader();
481   // The kernel should not include any terminator instructions.  These
482   // will be added back later.
483   SMS.startBlock(MBB);
484 
485   // Compute the number of 'real' instructions in the basic block by
486   // ignoring terminators.
487   unsigned size = MBB->size();
488   for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
489                                    E = MBB->instr_end();
490        I != E; ++I, --size)
491     ;
492 
493   SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
494   SMS.schedule();
495   SMS.exitRegion();
496 
497   SMS.finishBlock();
498   return SMS.hasNewSchedule();
499 }
500 
501 void MachinePipeliner::getAnalysisUsage(AnalysisUsage &AU) const {
502   AU.addRequired<AAResultsWrapperPass>();
503   AU.addPreserved<AAResultsWrapperPass>();
504   AU.addRequired<MachineLoopInfoWrapperPass>();
505   AU.addRequired<MachineDominatorTreeWrapperPass>();
506   AU.addRequired<LiveIntervalsWrapperPass>();
507   AU.addRequired<MachineOptimizationRemarkEmitterPass>();
508   AU.addRequired<TargetPassConfig>();
509   MachineFunctionPass::getAnalysisUsage(AU);
510 }
511 
512 bool MachinePipeliner::runWindowScheduler(MachineLoop &L) {
513   MachineSchedContext Context;
514   Context.MF = MF;
515   Context.MLI = MLI;
516   Context.MDT = MDT;
517   Context.PassConfig = &getAnalysis<TargetPassConfig>();
518   Context.AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
519   Context.LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
520   Context.RegClassInfo->runOnMachineFunction(*MF);
521   WindowScheduler WS(&Context, L);
522   return WS.run();
523 }
524 
525 bool MachinePipeliner::useSwingModuloScheduler() {
526   // SwingModuloScheduler does not work when WindowScheduler is forced.
527   return WindowSchedulingOption != WindowSchedulingFlag::WS_Force;
528 }
529 
530 bool MachinePipeliner::useWindowScheduler(bool Changed) {
531   // WindowScheduler does not work for following cases:
532   // 1. when it is off.
533   // 2. when SwingModuloScheduler is successfully scheduled.
534   // 3. when pragma II is enabled.
535   if (II_setByPragma) {
536     LLVM_DEBUG(dbgs() << "Window scheduling is disabled when "
537                          "llvm.loop.pipeline.initiationinterval is set.\n");
538     return false;
539   }
540 
541   return WindowSchedulingOption == WindowSchedulingFlag::WS_Force ||
542          (WindowSchedulingOption == WindowSchedulingFlag::WS_On && !Changed);
543 }
544 
545 void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
546   if (SwpForceII > 0)
547     MII = SwpForceII;
548   else if (II_setByPragma > 0)
549     MII = II_setByPragma;
550   else
551     MII = std::max(ResMII, RecMII);
552 }
553 
554 void SwingSchedulerDAG::setMAX_II() {
555   if (SwpForceII > 0)
556     MAX_II = SwpForceII;
557   else if (II_setByPragma > 0)
558     MAX_II = II_setByPragma;
559   else
560     MAX_II = MII + SwpIISearchRange;
561 }
562 
563 /// We override the schedule function in ScheduleDAGInstrs to implement the
564 /// scheduling part of the Swing Modulo Scheduling algorithm.
565 void SwingSchedulerDAG::schedule() {
566   AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
567   buildSchedGraph(AA);
568   addLoopCarriedDependences(AA);
569   updatePhiDependences();
570   Topo.InitDAGTopologicalSorting();
571   changeDependences();
572   postProcessDAG();
573   LLVM_DEBUG(dump());
574 
575   NodeSetType NodeSets;
576   findCircuits(NodeSets);
577   NodeSetType Circuits = NodeSets;
578 
579   // Calculate the MII.
580   unsigned ResMII = calculateResMII();
581   unsigned RecMII = calculateRecMII(NodeSets);
582 
583   fuseRecs(NodeSets);
584 
585   // This flag is used for testing and can cause correctness problems.
586   if (SwpIgnoreRecMII)
587     RecMII = 0;
588 
589   setMII(ResMII, RecMII);
590   setMAX_II();
591 
592   LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
593                     << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
594 
595   // Can't schedule a loop without a valid MII.
596   if (MII == 0) {
597     LLVM_DEBUG(dbgs() << "Invalid Minimal Initiation Interval: 0\n");
598     NumFailZeroMII++;
599     Pass.ORE->emit([&]() {
600       return MachineOptimizationRemarkAnalysis(
601                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
602              << "Invalid Minimal Initiation Interval: 0";
603     });
604     return;
605   }
606 
607   // Don't pipeline large loops.
608   if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) {
609     LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
610                       << ", we don't pipeline large loops\n");
611     NumFailLargeMaxMII++;
612     Pass.ORE->emit([&]() {
613       return MachineOptimizationRemarkAnalysis(
614                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
615              << "Minimal Initiation Interval too large: "
616              << ore::NV("MII", (int)MII) << " > "
617              << ore::NV("SwpMaxMii", SwpMaxMii) << "."
618              << "Refer to -pipeliner-max-mii.";
619     });
620     return;
621   }
622 
623   computeNodeFunctions(NodeSets);
624 
625   registerPressureFilter(NodeSets);
626 
627   colocateNodeSets(NodeSets);
628 
629   checkNodeSets(NodeSets);
630 
631   LLVM_DEBUG({
632     for (auto &I : NodeSets) {
633       dbgs() << "  Rec NodeSet ";
634       I.dump();
635     }
636   });
637 
638   llvm::stable_sort(NodeSets, std::greater<NodeSet>());
639 
640   groupRemainingNodes(NodeSets);
641 
642   removeDuplicateNodes(NodeSets);
643 
644   LLVM_DEBUG({
645     for (auto &I : NodeSets) {
646       dbgs() << "  NodeSet ";
647       I.dump();
648     }
649   });
650 
651   computeNodeOrder(NodeSets);
652 
653   // check for node order issues
654   checkValidNodeOrder(Circuits);
655 
656   SMSchedule Schedule(Pass.MF, this);
657   Scheduled = schedulePipeline(Schedule);
658 
659   if (!Scheduled){
660     LLVM_DEBUG(dbgs() << "No schedule found, return\n");
661     NumFailNoSchedule++;
662     Pass.ORE->emit([&]() {
663       return MachineOptimizationRemarkAnalysis(
664                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
665              << "Unable to find schedule";
666     });
667     return;
668   }
669 
670   unsigned numStages = Schedule.getMaxStageCount();
671   // No need to generate pipeline if there are no overlapped iterations.
672   if (numStages == 0) {
673     LLVM_DEBUG(dbgs() << "No overlapped iterations, skip.\n");
674     NumFailZeroStage++;
675     Pass.ORE->emit([&]() {
676       return MachineOptimizationRemarkAnalysis(
677                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
678              << "No need to pipeline - no overlapped iterations in schedule.";
679     });
680     return;
681   }
682   // Check that the maximum stage count is less than user-defined limit.
683   if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) {
684     LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages
685                       << " : too many stages, abort\n");
686     NumFailLargeMaxStage++;
687     Pass.ORE->emit([&]() {
688       return MachineOptimizationRemarkAnalysis(
689                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
690              << "Too many stages in schedule: "
691              << ore::NV("numStages", (int)numStages) << " > "
692              << ore::NV("SwpMaxStages", SwpMaxStages)
693              << ". Refer to -pipeliner-max-stages.";
694     });
695     return;
696   }
697 
698   Pass.ORE->emit([&]() {
699     return MachineOptimizationRemark(DEBUG_TYPE, "schedule", Loop.getStartLoc(),
700                                      Loop.getHeader())
701            << "Pipelined succesfully!";
702   });
703 
704   // Generate the schedule as a ModuloSchedule.
705   DenseMap<MachineInstr *, int> Cycles, Stages;
706   std::vector<MachineInstr *> OrderedInsts;
707   for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
708        ++Cycle) {
709     for (SUnit *SU : Schedule.getInstructions(Cycle)) {
710       OrderedInsts.push_back(SU->getInstr());
711       Cycles[SU->getInstr()] = Cycle;
712       Stages[SU->getInstr()] = Schedule.stageScheduled(SU);
713     }
714   }
715   DenseMap<MachineInstr *, std::pair<unsigned, int64_t>> NewInstrChanges;
716   for (auto &KV : NewMIs) {
717     Cycles[KV.first] = Cycles[KV.second];
718     Stages[KV.first] = Stages[KV.second];
719     NewInstrChanges[KV.first] = InstrChanges[getSUnit(KV.first)];
720   }
721 
722   ModuloSchedule MS(MF, &Loop, std::move(OrderedInsts), std::move(Cycles),
723                     std::move(Stages));
724   if (EmitTestAnnotations) {
725     assert(NewInstrChanges.empty() &&
726            "Cannot serialize a schedule with InstrChanges!");
727     ModuloScheduleTestAnnotater MSTI(MF, MS);
728     MSTI.annotate();
729     return;
730   }
731   // The experimental code generator can't work if there are InstChanges.
732   if (ExperimentalCodeGen && NewInstrChanges.empty()) {
733     PeelingModuloScheduleExpander MSE(MF, MS, &LIS);
734     MSE.expand();
735   } else if (MVECodeGen && NewInstrChanges.empty() &&
736              LoopPipelinerInfo->isMVEExpanderSupported() &&
737              ModuloScheduleExpanderMVE::canApply(Loop)) {
738     ModuloScheduleExpanderMVE MSE(MF, MS, LIS);
739     MSE.expand();
740   } else {
741     ModuloScheduleExpander MSE(MF, MS, LIS, std::move(NewInstrChanges));
742     MSE.expand();
743     MSE.cleanup();
744   }
745   ++NumPipelined;
746 }
747 
748 /// Clean up after the software pipeliner runs.
749 void SwingSchedulerDAG::finishBlock() {
750   for (auto &KV : NewMIs)
751     MF.deleteMachineInstr(KV.second);
752   NewMIs.clear();
753 
754   // Call the superclass.
755   ScheduleDAGInstrs::finishBlock();
756 }
757 
758 /// Return the register values for  the operands of a Phi instruction.
759 /// This function assume the instruction is a Phi.
760 static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
761                        unsigned &InitVal, unsigned &LoopVal) {
762   assert(Phi.isPHI() && "Expecting a Phi.");
763 
764   InitVal = 0;
765   LoopVal = 0;
766   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
767     if (Phi.getOperand(i + 1).getMBB() != Loop)
768       InitVal = Phi.getOperand(i).getReg();
769     else
770       LoopVal = Phi.getOperand(i).getReg();
771 
772   assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
773 }
774 
775 /// Return the Phi register value that comes the loop block.
776 static unsigned getLoopPhiReg(const MachineInstr &Phi,
777                               const MachineBasicBlock *LoopBB) {
778   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
779     if (Phi.getOperand(i + 1).getMBB() == LoopBB)
780       return Phi.getOperand(i).getReg();
781   return 0;
782 }
783 
784 /// Return true if SUb can be reached from SUa following the chain edges.
785 static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
786   SmallPtrSet<SUnit *, 8> Visited;
787   SmallVector<SUnit *, 8> Worklist;
788   Worklist.push_back(SUa);
789   while (!Worklist.empty()) {
790     const SUnit *SU = Worklist.pop_back_val();
791     for (const auto &SI : SU->Succs) {
792       SUnit *SuccSU = SI.getSUnit();
793       if (SI.getKind() == SDep::Order) {
794         if (Visited.count(SuccSU))
795           continue;
796         if (SuccSU == SUb)
797           return true;
798         Worklist.push_back(SuccSU);
799         Visited.insert(SuccSU);
800       }
801     }
802   }
803   return false;
804 }
805 
806 /// Return true if the instruction causes a chain between memory
807 /// references before and after it.
808 static bool isDependenceBarrier(MachineInstr &MI) {
809   return MI.isCall() || MI.mayRaiseFPException() ||
810          MI.hasUnmodeledSideEffects() ||
811          (MI.hasOrderedMemoryRef() &&
812           (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad()));
813 }
814 
815 /// Return the underlying objects for the memory references of an instruction.
816 /// This function calls the code in ValueTracking, but first checks that the
817 /// instruction has a memory operand.
818 static void getUnderlyingObjects(const MachineInstr *MI,
819                                  SmallVectorImpl<const Value *> &Objs) {
820   if (!MI->hasOneMemOperand())
821     return;
822   MachineMemOperand *MM = *MI->memoperands_begin();
823   if (!MM->getValue())
824     return;
825   getUnderlyingObjects(MM->getValue(), Objs);
826   for (const Value *V : Objs) {
827     if (!isIdentifiedObject(V)) {
828       Objs.clear();
829       return;
830     }
831   }
832 }
833 
834 /// Add a chain edge between a load and store if the store can be an
835 /// alias of the load on a subsequent iteration, i.e., a loop carried
836 /// dependence. This code is very similar to the code in ScheduleDAGInstrs
837 /// but that code doesn't create loop carried dependences.
838 void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
839   MapVector<const Value *, SmallVector<SUnit *, 4>> PendingLoads;
840   Value *UnknownValue =
841     UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
842   for (auto &SU : SUnits) {
843     MachineInstr &MI = *SU.getInstr();
844     if (isDependenceBarrier(MI))
845       PendingLoads.clear();
846     else if (MI.mayLoad()) {
847       SmallVector<const Value *, 4> Objs;
848       ::getUnderlyingObjects(&MI, Objs);
849       if (Objs.empty())
850         Objs.push_back(UnknownValue);
851       for (const auto *V : Objs) {
852         SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
853         SUs.push_back(&SU);
854       }
855     } else if (MI.mayStore()) {
856       SmallVector<const Value *, 4> Objs;
857       ::getUnderlyingObjects(&MI, Objs);
858       if (Objs.empty())
859         Objs.push_back(UnknownValue);
860       for (const auto *V : Objs) {
861         MapVector<const Value *, SmallVector<SUnit *, 4>>::iterator I =
862             PendingLoads.find(V);
863         if (I == PendingLoads.end())
864           continue;
865         for (auto *Load : I->second) {
866           if (isSuccOrder(Load, &SU))
867             continue;
868           MachineInstr &LdMI = *Load->getInstr();
869           // First, perform the cheaper check that compares the base register.
870           // If they are the same and the load offset is less than the store
871           // offset, then mark the dependence as loop carried potentially.
872           const MachineOperand *BaseOp1, *BaseOp2;
873           int64_t Offset1, Offset2;
874           bool Offset1IsScalable, Offset2IsScalable;
875           if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1,
876                                            Offset1IsScalable, TRI) &&
877               TII->getMemOperandWithOffset(MI, BaseOp2, Offset2,
878                                            Offset2IsScalable, TRI)) {
879             if (BaseOp1->isIdenticalTo(*BaseOp2) &&
880                 Offset1IsScalable == Offset2IsScalable &&
881                 (int)Offset1 < (int)Offset2) {
882               assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI) &&
883                      "What happened to the chain edge?");
884               SDep Dep(Load, SDep::Barrier);
885               Dep.setLatency(1);
886               SU.addPred(Dep);
887               continue;
888             }
889           }
890           // Second, the more expensive check that uses alias analysis on the
891           // base registers. If they alias, and the load offset is less than
892           // the store offset, the mark the dependence as loop carried.
893           if (!AA) {
894             SDep Dep(Load, SDep::Barrier);
895             Dep.setLatency(1);
896             SU.addPred(Dep);
897             continue;
898           }
899           MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
900           MachineMemOperand *MMO2 = *MI.memoperands_begin();
901           if (!MMO1->getValue() || !MMO2->getValue()) {
902             SDep Dep(Load, SDep::Barrier);
903             Dep.setLatency(1);
904             SU.addPred(Dep);
905             continue;
906           }
907           if (MMO1->getValue() == MMO2->getValue() &&
908               MMO1->getOffset() <= MMO2->getOffset()) {
909             SDep Dep(Load, SDep::Barrier);
910             Dep.setLatency(1);
911             SU.addPred(Dep);
912             continue;
913           }
914           if (!AA->isNoAlias(
915                   MemoryLocation::getAfter(MMO1->getValue(), MMO1->getAAInfo()),
916                   MemoryLocation::getAfter(MMO2->getValue(),
917                                            MMO2->getAAInfo()))) {
918             SDep Dep(Load, SDep::Barrier);
919             Dep.setLatency(1);
920             SU.addPred(Dep);
921           }
922         }
923       }
924     }
925   }
926 }
927 
928 /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
929 /// processes dependences for PHIs. This function adds true dependences
930 /// from a PHI to a use, and a loop carried dependence from the use to the
931 /// PHI. The loop carried dependence is represented as an anti dependence
932 /// edge. This function also removes chain dependences between unrelated
933 /// PHIs.
934 void SwingSchedulerDAG::updatePhiDependences() {
935   SmallVector<SDep, 4> RemoveDeps;
936   const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
937 
938   // Iterate over each DAG node.
939   for (SUnit &I : SUnits) {
940     RemoveDeps.clear();
941     // Set to true if the instruction has an operand defined by a Phi.
942     unsigned HasPhiUse = 0;
943     unsigned HasPhiDef = 0;
944     MachineInstr *MI = I.getInstr();
945     // Iterate over each operand, and we process the definitions.
946     for (const MachineOperand &MO : MI->operands()) {
947       if (!MO.isReg())
948         continue;
949       Register Reg = MO.getReg();
950       if (MO.isDef()) {
951         // If the register is used by a Phi, then create an anti dependence.
952         for (MachineRegisterInfo::use_instr_iterator
953                  UI = MRI.use_instr_begin(Reg),
954                  UE = MRI.use_instr_end();
955              UI != UE; ++UI) {
956           MachineInstr *UseMI = &*UI;
957           SUnit *SU = getSUnit(UseMI);
958           if (SU != nullptr && UseMI->isPHI()) {
959             if (!MI->isPHI()) {
960               SDep Dep(SU, SDep::Anti, Reg);
961               Dep.setLatency(1);
962               I.addPred(Dep);
963             } else {
964               HasPhiDef = Reg;
965               // Add a chain edge to a dependent Phi that isn't an existing
966               // predecessor.
967               if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
968                 I.addPred(SDep(SU, SDep::Barrier));
969             }
970           }
971         }
972       } else if (MO.isUse()) {
973         // If the register is defined by a Phi, then create a true dependence.
974         MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
975         if (DefMI == nullptr)
976           continue;
977         SUnit *SU = getSUnit(DefMI);
978         if (SU != nullptr && DefMI->isPHI()) {
979           if (!MI->isPHI()) {
980             SDep Dep(SU, SDep::Data, Reg);
981             Dep.setLatency(0);
982             ST.adjustSchedDependency(SU, 0, &I, MO.getOperandNo(), Dep,
983                                      &SchedModel);
984             I.addPred(Dep);
985           } else {
986             HasPhiUse = Reg;
987             // Add a chain edge to a dependent Phi that isn't an existing
988             // predecessor.
989             if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
990               I.addPred(SDep(SU, SDep::Barrier));
991           }
992         }
993       }
994     }
995     // Remove order dependences from an unrelated Phi.
996     if (!SwpPruneDeps)
997       continue;
998     for (auto &PI : I.Preds) {
999       MachineInstr *PMI = PI.getSUnit()->getInstr();
1000       if (PMI->isPHI() && PI.getKind() == SDep::Order) {
1001         if (I.getInstr()->isPHI()) {
1002           if (PMI->getOperand(0).getReg() == HasPhiUse)
1003             continue;
1004           if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
1005             continue;
1006         }
1007         RemoveDeps.push_back(PI);
1008       }
1009     }
1010     for (const SDep &D : RemoveDeps)
1011       I.removePred(D);
1012   }
1013 }
1014 
1015 /// Iterate over each DAG node and see if we can change any dependences
1016 /// in order to reduce the recurrence MII.
1017 void SwingSchedulerDAG::changeDependences() {
1018   // See if an instruction can use a value from the previous iteration.
1019   // If so, we update the base and offset of the instruction and change
1020   // the dependences.
1021   for (SUnit &I : SUnits) {
1022     unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
1023     int64_t NewOffset = 0;
1024     if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
1025                                NewOffset))
1026       continue;
1027 
1028     // Get the MI and SUnit for the instruction that defines the original base.
1029     Register OrigBase = I.getInstr()->getOperand(BasePos).getReg();
1030     MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
1031     if (!DefMI)
1032       continue;
1033     SUnit *DefSU = getSUnit(DefMI);
1034     if (!DefSU)
1035       continue;
1036     // Get the MI and SUnit for the instruction that defins the new base.
1037     MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
1038     if (!LastMI)
1039       continue;
1040     SUnit *LastSU = getSUnit(LastMI);
1041     if (!LastSU)
1042       continue;
1043 
1044     if (Topo.IsReachable(&I, LastSU))
1045       continue;
1046 
1047     // Remove the dependence. The value now depends on a prior iteration.
1048     SmallVector<SDep, 4> Deps;
1049     for (const SDep &P : I.Preds)
1050       if (P.getSUnit() == DefSU)
1051         Deps.push_back(P);
1052     for (const SDep &D : Deps) {
1053       Topo.RemovePred(&I, D.getSUnit());
1054       I.removePred(D);
1055     }
1056     // Remove the chain dependence between the instructions.
1057     Deps.clear();
1058     for (auto &P : LastSU->Preds)
1059       if (P.getSUnit() == &I && P.getKind() == SDep::Order)
1060         Deps.push_back(P);
1061     for (const SDep &D : Deps) {
1062       Topo.RemovePred(LastSU, D.getSUnit());
1063       LastSU->removePred(D);
1064     }
1065 
1066     // Add a dependence between the new instruction and the instruction
1067     // that defines the new base.
1068     SDep Dep(&I, SDep::Anti, NewBase);
1069     Topo.AddPred(LastSU, &I);
1070     LastSU->addPred(Dep);
1071 
1072     // Remember the base and offset information so that we can update the
1073     // instruction during code generation.
1074     InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
1075   }
1076 }
1077 
1078 /// Create an instruction stream that represents a single iteration and stage of
1079 /// each instruction. This function differs from SMSchedule::finalizeSchedule in
1080 /// that this doesn't have any side-effect to SwingSchedulerDAG. That is, this
1081 /// function is an approximation of SMSchedule::finalizeSchedule with all
1082 /// non-const operations removed.
1083 static void computeScheduledInsts(const SwingSchedulerDAG *SSD,
1084                                   SMSchedule &Schedule,
1085                                   std::vector<MachineInstr *> &OrderedInsts,
1086                                   DenseMap<MachineInstr *, unsigned> &Stages) {
1087   DenseMap<int, std::deque<SUnit *>> Instrs;
1088 
1089   // Move all instructions to the first stage from the later stages.
1090   for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
1091        ++Cycle) {
1092     for (int Stage = 0, LastStage = Schedule.getMaxStageCount();
1093          Stage <= LastStage; ++Stage) {
1094       for (SUnit *SU : llvm::reverse(Schedule.getInstructions(
1095                Cycle + Stage * Schedule.getInitiationInterval()))) {
1096         Instrs[Cycle].push_front(SU);
1097       }
1098     }
1099   }
1100 
1101   for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
1102        ++Cycle) {
1103     std::deque<SUnit *> &CycleInstrs = Instrs[Cycle];
1104     CycleInstrs = Schedule.reorderInstructions(SSD, CycleInstrs);
1105     for (SUnit *SU : CycleInstrs) {
1106       MachineInstr *MI = SU->getInstr();
1107       OrderedInsts.push_back(MI);
1108       Stages[MI] = Schedule.stageScheduled(SU);
1109     }
1110   }
1111 }
1112 
1113 namespace {
1114 
1115 // FuncUnitSorter - Comparison operator used to sort instructions by
1116 // the number of functional unit choices.
1117 struct FuncUnitSorter {
1118   const InstrItineraryData *InstrItins;
1119   const MCSubtargetInfo *STI;
1120   DenseMap<InstrStage::FuncUnits, unsigned> Resources;
1121 
1122   FuncUnitSorter(const TargetSubtargetInfo &TSI)
1123       : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
1124 
1125   // Compute the number of functional unit alternatives needed
1126   // at each stage, and take the minimum value. We prioritize the
1127   // instructions by the least number of choices first.
1128   unsigned minFuncUnits(const MachineInstr *Inst,
1129                         InstrStage::FuncUnits &F) const {
1130     unsigned SchedClass = Inst->getDesc().getSchedClass();
1131     unsigned min = UINT_MAX;
1132     if (InstrItins && !InstrItins->isEmpty()) {
1133       for (const InstrStage &IS :
1134            make_range(InstrItins->beginStage(SchedClass),
1135                       InstrItins->endStage(SchedClass))) {
1136         InstrStage::FuncUnits funcUnits = IS.getUnits();
1137         unsigned numAlternatives = llvm::popcount(funcUnits);
1138         if (numAlternatives < min) {
1139           min = numAlternatives;
1140           F = funcUnits;
1141         }
1142       }
1143       return min;
1144     }
1145     if (STI && STI->getSchedModel().hasInstrSchedModel()) {
1146       const MCSchedClassDesc *SCDesc =
1147           STI->getSchedModel().getSchedClassDesc(SchedClass);
1148       if (!SCDesc->isValid())
1149         // No valid Schedule Class Desc for schedClass, should be
1150         // Pseudo/PostRAPseudo
1151         return min;
1152 
1153       for (const MCWriteProcResEntry &PRE :
1154            make_range(STI->getWriteProcResBegin(SCDesc),
1155                       STI->getWriteProcResEnd(SCDesc))) {
1156         if (!PRE.ReleaseAtCycle)
1157           continue;
1158         const MCProcResourceDesc *ProcResource =
1159             STI->getSchedModel().getProcResource(PRE.ProcResourceIdx);
1160         unsigned NumUnits = ProcResource->NumUnits;
1161         if (NumUnits < min) {
1162           min = NumUnits;
1163           F = PRE.ProcResourceIdx;
1164         }
1165       }
1166       return min;
1167     }
1168     llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1169   }
1170 
1171   // Compute the critical resources needed by the instruction. This
1172   // function records the functional units needed by instructions that
1173   // must use only one functional unit. We use this as a tie breaker
1174   // for computing the resource MII. The instrutions that require
1175   // the same, highly used, functional unit have high priority.
1176   void calcCriticalResources(MachineInstr &MI) {
1177     unsigned SchedClass = MI.getDesc().getSchedClass();
1178     if (InstrItins && !InstrItins->isEmpty()) {
1179       for (const InstrStage &IS :
1180            make_range(InstrItins->beginStage(SchedClass),
1181                       InstrItins->endStage(SchedClass))) {
1182         InstrStage::FuncUnits FuncUnits = IS.getUnits();
1183         if (llvm::popcount(FuncUnits) == 1)
1184           Resources[FuncUnits]++;
1185       }
1186       return;
1187     }
1188     if (STI && STI->getSchedModel().hasInstrSchedModel()) {
1189       const MCSchedClassDesc *SCDesc =
1190           STI->getSchedModel().getSchedClassDesc(SchedClass);
1191       if (!SCDesc->isValid())
1192         // No valid Schedule Class Desc for schedClass, should be
1193         // Pseudo/PostRAPseudo
1194         return;
1195 
1196       for (const MCWriteProcResEntry &PRE :
1197            make_range(STI->getWriteProcResBegin(SCDesc),
1198                       STI->getWriteProcResEnd(SCDesc))) {
1199         if (!PRE.ReleaseAtCycle)
1200           continue;
1201         Resources[PRE.ProcResourceIdx]++;
1202       }
1203       return;
1204     }
1205     llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1206   }
1207 
1208   /// Return true if IS1 has less priority than IS2.
1209   bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
1210     InstrStage::FuncUnits F1 = 0, F2 = 0;
1211     unsigned MFUs1 = minFuncUnits(IS1, F1);
1212     unsigned MFUs2 = minFuncUnits(IS2, F2);
1213     if (MFUs1 == MFUs2)
1214       return Resources.lookup(F1) < Resources.lookup(F2);
1215     return MFUs1 > MFUs2;
1216   }
1217 };
1218 
1219 /// Calculate the maximum register pressure of the scheduled instructions stream
1220 class HighRegisterPressureDetector {
1221   MachineBasicBlock *OrigMBB;
1222   const MachineFunction &MF;
1223   const MachineRegisterInfo &MRI;
1224   const TargetRegisterInfo *TRI;
1225 
1226   const unsigned PSetNum;
1227 
1228   // Indexed by PSet ID
1229   // InitSetPressure takes into account the register pressure of live-in
1230   // registers. It's not depend on how the loop is scheduled, so it's enough to
1231   // calculate them once at the beginning.
1232   std::vector<unsigned> InitSetPressure;
1233 
1234   // Indexed by PSet ID
1235   // Upper limit for each register pressure set
1236   std::vector<unsigned> PressureSetLimit;
1237 
1238   DenseMap<MachineInstr *, RegisterOperands> ROMap;
1239 
1240   using Instr2LastUsesTy = DenseMap<MachineInstr *, SmallDenseSet<Register, 4>>;
1241 
1242 public:
1243   using OrderedInstsTy = std::vector<MachineInstr *>;
1244   using Instr2StageTy = DenseMap<MachineInstr *, unsigned>;
1245 
1246 private:
1247   static void dumpRegisterPressures(const std::vector<unsigned> &Pressures) {
1248     if (Pressures.size() == 0) {
1249       dbgs() << "[]";
1250     } else {
1251       char Prefix = '[';
1252       for (unsigned P : Pressures) {
1253         dbgs() << Prefix << P;
1254         Prefix = ' ';
1255       }
1256       dbgs() << ']';
1257     }
1258   }
1259 
1260   void dumpPSet(Register Reg) const {
1261     dbgs() << "Reg=" << printReg(Reg, TRI, 0, &MRI) << " PSet=";
1262     for (auto PSetIter = MRI.getPressureSets(Reg); PSetIter.isValid();
1263          ++PSetIter) {
1264       dbgs() << *PSetIter << ' ';
1265     }
1266     dbgs() << '\n';
1267   }
1268 
1269   void increaseRegisterPressure(std::vector<unsigned> &Pressure,
1270                                 Register Reg) const {
1271     auto PSetIter = MRI.getPressureSets(Reg);
1272     unsigned Weight = PSetIter.getWeight();
1273     for (; PSetIter.isValid(); ++PSetIter)
1274       Pressure[*PSetIter] += Weight;
1275   }
1276 
1277   void decreaseRegisterPressure(std::vector<unsigned> &Pressure,
1278                                 Register Reg) const {
1279     auto PSetIter = MRI.getPressureSets(Reg);
1280     unsigned Weight = PSetIter.getWeight();
1281     for (; PSetIter.isValid(); ++PSetIter) {
1282       auto &P = Pressure[*PSetIter];
1283       assert(P >= Weight &&
1284              "register pressure must be greater than or equal weight");
1285       P -= Weight;
1286     }
1287   }
1288 
1289   // Return true if Reg is fixed one, for example, stack pointer
1290   bool isFixedRegister(Register Reg) const {
1291     return Reg.isPhysical() && TRI->isFixedRegister(MF, Reg.asMCReg());
1292   }
1293 
1294   bool isDefinedInThisLoop(Register Reg) const {
1295     return Reg.isVirtual() && MRI.getVRegDef(Reg)->getParent() == OrigMBB;
1296   }
1297 
1298   // Search for live-in variables. They are factored into the register pressure
1299   // from the begining. Live-in variables used by every iteration should be
1300   // considered as alive throughout the loop. For example, the variable `c` in
1301   // following code. \code
1302   //   int c = ...;
1303   //   for (int i = 0; i < n; i++)
1304   //     a[i] += b[i] + c;
1305   // \endcode
1306   void computeLiveIn() {
1307     DenseSet<Register> Used;
1308     for (auto &MI : *OrigMBB) {
1309       if (MI.isDebugInstr())
1310         continue;
1311       for (auto &Use : ROMap[&MI].Uses) {
1312         auto Reg = Use.RegUnit;
1313         // Ignore the variable that appears only on one side of phi instruction
1314         // because it's used only at the first iteration.
1315         if (MI.isPHI() && Reg != getLoopPhiReg(MI, OrigMBB))
1316           continue;
1317         if (isFixedRegister(Reg))
1318           continue;
1319         if (isDefinedInThisLoop(Reg))
1320           continue;
1321         Used.insert(Reg);
1322       }
1323     }
1324 
1325     for (auto LiveIn : Used)
1326       increaseRegisterPressure(InitSetPressure, LiveIn);
1327   }
1328 
1329   // Calculate the upper limit of each pressure set
1330   void computePressureSetLimit(const RegisterClassInfo &RCI) {
1331     for (unsigned PSet = 0; PSet < PSetNum; PSet++)
1332       PressureSetLimit[PSet] = TRI->getRegPressureSetLimit(MF, PSet);
1333 
1334     // We assume fixed registers, such as stack pointer, are already in use.
1335     // Therefore subtracting the weight of the fixed registers from the limit of
1336     // each pressure set in advance.
1337     SmallDenseSet<Register, 8> FixedRegs;
1338     for (const TargetRegisterClass *TRC : TRI->regclasses()) {
1339       for (const MCPhysReg Reg : *TRC)
1340         if (isFixedRegister(Reg))
1341           FixedRegs.insert(Reg);
1342     }
1343 
1344     LLVM_DEBUG({
1345       for (auto Reg : FixedRegs) {
1346         dbgs() << printReg(Reg, TRI, 0, &MRI) << ": [";
1347         for (MCRegUnit Unit : TRI->regunits(Reg)) {
1348           const int *Sets = TRI->getRegUnitPressureSets(Unit);
1349           for (; *Sets != -1; Sets++) {
1350             dbgs() << TRI->getRegPressureSetName(*Sets) << ", ";
1351           }
1352         }
1353         dbgs() << "]\n";
1354       }
1355     });
1356 
1357     for (auto Reg : FixedRegs) {
1358       LLVM_DEBUG(dbgs() << "fixed register: " << printReg(Reg, TRI, 0, &MRI)
1359                         << "\n");
1360       for (MCRegUnit Unit : TRI->regunits(Reg)) {
1361         auto PSetIter = MRI.getPressureSets(Unit);
1362         unsigned Weight = PSetIter.getWeight();
1363         for (; PSetIter.isValid(); ++PSetIter) {
1364           unsigned &Limit = PressureSetLimit[*PSetIter];
1365           assert(
1366               Limit >= Weight &&
1367               "register pressure limit must be greater than or equal weight");
1368           Limit -= Weight;
1369           LLVM_DEBUG(dbgs() << "PSet=" << *PSetIter << " Limit=" << Limit
1370                             << " (decreased by " << Weight << ")\n");
1371         }
1372       }
1373     }
1374   }
1375 
1376   // There are two patterns of last-use.
1377   //   - by an instruction of the current iteration
1378   //   - by a phi instruction of the next iteration (loop carried value)
1379   //
1380   // Furthermore, following two groups of instructions are executed
1381   // simultaneously
1382   //   - next iteration's phi instructions in i-th stage
1383   //   - current iteration's instructions in i+1-th stage
1384   //
1385   // This function calculates the last-use of each register while taking into
1386   // account the above two patterns.
1387   Instr2LastUsesTy computeLastUses(const OrderedInstsTy &OrderedInsts,
1388                                    Instr2StageTy &Stages) const {
1389     // We treat virtual registers that are defined and used in this loop.
1390     // Following virtual register will be ignored
1391     //   - live-in one
1392     //   - defined but not used in the loop (potentially live-out)
1393     DenseSet<Register> TargetRegs;
1394     const auto UpdateTargetRegs = [this, &TargetRegs](Register Reg) {
1395       if (isDefinedInThisLoop(Reg))
1396         TargetRegs.insert(Reg);
1397     };
1398     for (MachineInstr *MI : OrderedInsts) {
1399       if (MI->isPHI()) {
1400         Register Reg = getLoopPhiReg(*MI, OrigMBB);
1401         UpdateTargetRegs(Reg);
1402       } else {
1403         for (auto &Use : ROMap.find(MI)->getSecond().Uses)
1404           UpdateTargetRegs(Use.RegUnit);
1405       }
1406     }
1407 
1408     const auto InstrScore = [&Stages](MachineInstr *MI) {
1409       return Stages[MI] + MI->isPHI();
1410     };
1411 
1412     DenseMap<Register, MachineInstr *> LastUseMI;
1413     for (MachineInstr *MI : llvm::reverse(OrderedInsts)) {
1414       for (auto &Use : ROMap.find(MI)->getSecond().Uses) {
1415         auto Reg = Use.RegUnit;
1416         if (!TargetRegs.contains(Reg))
1417           continue;
1418         auto Ite = LastUseMI.find(Reg);
1419         if (Ite == LastUseMI.end()) {
1420           LastUseMI[Reg] = MI;
1421         } else {
1422           MachineInstr *Orig = Ite->second;
1423           MachineInstr *New = MI;
1424           if (InstrScore(Orig) < InstrScore(New))
1425             LastUseMI[Reg] = New;
1426         }
1427       }
1428     }
1429 
1430     Instr2LastUsesTy LastUses;
1431     for (auto &Entry : LastUseMI)
1432       LastUses[Entry.second].insert(Entry.first);
1433     return LastUses;
1434   }
1435 
1436   // Compute the maximum register pressure of the kernel. We'll simulate #Stage
1437   // iterations and check the register pressure at the point where all stages
1438   // overlapping.
1439   //
1440   // An example of unrolled loop where #Stage is 4..
1441   // Iter   i+0 i+1 i+2 i+3
1442   // ------------------------
1443   // Stage   0
1444   // Stage   1   0
1445   // Stage   2   1   0
1446   // Stage   3   2   1   0  <- All stages overlap
1447   //
1448   std::vector<unsigned>
1449   computeMaxSetPressure(const OrderedInstsTy &OrderedInsts,
1450                         Instr2StageTy &Stages,
1451                         const unsigned StageCount) const {
1452     using RegSetTy = SmallDenseSet<Register, 16>;
1453 
1454     // Indexed by #Iter. To treat "local" variables of each stage separately, we
1455     // manage the liveness of the registers independently by iterations.
1456     SmallVector<RegSetTy> LiveRegSets(StageCount);
1457 
1458     auto CurSetPressure = InitSetPressure;
1459     auto MaxSetPressure = InitSetPressure;
1460     auto LastUses = computeLastUses(OrderedInsts, Stages);
1461 
1462     LLVM_DEBUG({
1463       dbgs() << "Ordered instructions:\n";
1464       for (MachineInstr *MI : OrderedInsts) {
1465         dbgs() << "Stage " << Stages[MI] << ": ";
1466         MI->dump();
1467       }
1468     });
1469 
1470     const auto InsertReg = [this, &CurSetPressure](RegSetTy &RegSet,
1471                                                    Register Reg) {
1472       if (!Reg.isValid() || isFixedRegister(Reg))
1473         return;
1474 
1475       bool Inserted = RegSet.insert(Reg).second;
1476       if (!Inserted)
1477         return;
1478 
1479       LLVM_DEBUG(dbgs() << "insert " << printReg(Reg, TRI, 0, &MRI) << "\n");
1480       increaseRegisterPressure(CurSetPressure, Reg);
1481       LLVM_DEBUG(dumpPSet(Reg));
1482     };
1483 
1484     const auto EraseReg = [this, &CurSetPressure](RegSetTy &RegSet,
1485                                                   Register Reg) {
1486       if (!Reg.isValid() || isFixedRegister(Reg))
1487         return;
1488 
1489       // live-in register
1490       if (!RegSet.contains(Reg))
1491         return;
1492 
1493       LLVM_DEBUG(dbgs() << "erase " << printReg(Reg, TRI, 0, &MRI) << "\n");
1494       RegSet.erase(Reg);
1495       decreaseRegisterPressure(CurSetPressure, Reg);
1496       LLVM_DEBUG(dumpPSet(Reg));
1497     };
1498 
1499     for (unsigned I = 0; I < StageCount; I++) {
1500       for (MachineInstr *MI : OrderedInsts) {
1501         const auto Stage = Stages[MI];
1502         if (I < Stage)
1503           continue;
1504 
1505         const unsigned Iter = I - Stage;
1506 
1507         for (auto &Def : ROMap.find(MI)->getSecond().Defs)
1508           InsertReg(LiveRegSets[Iter], Def.RegUnit);
1509 
1510         for (auto LastUse : LastUses[MI]) {
1511           if (MI->isPHI()) {
1512             if (Iter != 0)
1513               EraseReg(LiveRegSets[Iter - 1], LastUse);
1514           } else {
1515             EraseReg(LiveRegSets[Iter], LastUse);
1516           }
1517         }
1518 
1519         for (unsigned PSet = 0; PSet < PSetNum; PSet++)
1520           MaxSetPressure[PSet] =
1521               std::max(MaxSetPressure[PSet], CurSetPressure[PSet]);
1522 
1523         LLVM_DEBUG({
1524           dbgs() << "CurSetPressure=";
1525           dumpRegisterPressures(CurSetPressure);
1526           dbgs() << " iter=" << Iter << " stage=" << Stage << ":";
1527           MI->dump();
1528         });
1529       }
1530     }
1531 
1532     return MaxSetPressure;
1533   }
1534 
1535 public:
1536   HighRegisterPressureDetector(MachineBasicBlock *OrigMBB,
1537                                const MachineFunction &MF)
1538       : OrigMBB(OrigMBB), MF(MF), MRI(MF.getRegInfo()),
1539         TRI(MF.getSubtarget().getRegisterInfo()),
1540         PSetNum(TRI->getNumRegPressureSets()), InitSetPressure(PSetNum, 0),
1541         PressureSetLimit(PSetNum, 0) {}
1542 
1543   // Used to calculate register pressure, which is independent of loop
1544   // scheduling.
1545   void init(const RegisterClassInfo &RCI) {
1546     for (MachineInstr &MI : *OrigMBB) {
1547       if (MI.isDebugInstr())
1548         continue;
1549       ROMap[&MI].collect(MI, *TRI, MRI, false, true);
1550     }
1551 
1552     computeLiveIn();
1553     computePressureSetLimit(RCI);
1554   }
1555 
1556   // Calculate the maximum register pressures of the loop and check if they
1557   // exceed the limit
1558   bool detect(const SwingSchedulerDAG *SSD, SMSchedule &Schedule,
1559               const unsigned MaxStage) const {
1560     assert(0 <= RegPressureMargin && RegPressureMargin <= 100 &&
1561            "the percentage of the margin must be between 0 to 100");
1562 
1563     OrderedInstsTy OrderedInsts;
1564     Instr2StageTy Stages;
1565     computeScheduledInsts(SSD, Schedule, OrderedInsts, Stages);
1566     const auto MaxSetPressure =
1567         computeMaxSetPressure(OrderedInsts, Stages, MaxStage + 1);
1568 
1569     LLVM_DEBUG({
1570       dbgs() << "Dump MaxSetPressure:\n";
1571       for (unsigned I = 0; I < MaxSetPressure.size(); I++) {
1572         dbgs() << format("MaxSetPressure[%d]=%d\n", I, MaxSetPressure[I]);
1573       }
1574       dbgs() << '\n';
1575     });
1576 
1577     for (unsigned PSet = 0; PSet < PSetNum; PSet++) {
1578       unsigned Limit = PressureSetLimit[PSet];
1579       unsigned Margin = Limit * RegPressureMargin / 100;
1580       LLVM_DEBUG(dbgs() << "PSet=" << PSet << " Limit=" << Limit
1581                         << " Margin=" << Margin << "\n");
1582       if (Limit < MaxSetPressure[PSet] + Margin) {
1583         LLVM_DEBUG(
1584             dbgs()
1585             << "Rejected the schedule because of too high register pressure\n");
1586         return true;
1587       }
1588     }
1589     return false;
1590   }
1591 };
1592 
1593 } // end anonymous namespace
1594 
1595 /// Calculate the resource constrained minimum initiation interval for the
1596 /// specified loop. We use the DFA to model the resources needed for
1597 /// each instruction, and we ignore dependences. A different DFA is created
1598 /// for each cycle that is required. When adding a new instruction, we attempt
1599 /// to add it to each existing DFA, until a legal space is found. If the
1600 /// instruction cannot be reserved in an existing DFA, we create a new one.
1601 unsigned SwingSchedulerDAG::calculateResMII() {
1602   LLVM_DEBUG(dbgs() << "calculateResMII:\n");
1603   ResourceManager RM(&MF.getSubtarget(), this);
1604   return RM.calculateResMII();
1605 }
1606 
1607 /// Calculate the recurrence-constrainted minimum initiation interval.
1608 /// Iterate over each circuit.  Compute the delay(c) and distance(c)
1609 /// for each circuit. The II needs to satisfy the inequality
1610 /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
1611 /// II that satisfies the inequality, and the RecMII is the maximum
1612 /// of those values.
1613 unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1614   unsigned RecMII = 0;
1615 
1616   for (NodeSet &Nodes : NodeSets) {
1617     if (Nodes.empty())
1618       continue;
1619 
1620     unsigned Delay = Nodes.getLatency();
1621     unsigned Distance = 1;
1622 
1623     // ii = ceil(delay / distance)
1624     unsigned CurMII = (Delay + Distance - 1) / Distance;
1625     Nodes.setRecMII(CurMII);
1626     if (CurMII > RecMII)
1627       RecMII = CurMII;
1628   }
1629 
1630   return RecMII;
1631 }
1632 
1633 /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1634 /// but we do this to find the circuits, and then change them back.
1635 static void swapAntiDependences(std::vector<SUnit> &SUnits) {
1636   SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
1637   for (SUnit &SU : SUnits) {
1638     for (SDep &Pred : SU.Preds)
1639       if (Pred.getKind() == SDep::Anti)
1640         DepsAdded.push_back(std::make_pair(&SU, Pred));
1641   }
1642   for (std::pair<SUnit *, SDep> &P : DepsAdded) {
1643     // Remove this anti dependency and add one in the reverse direction.
1644     SUnit *SU = P.first;
1645     SDep &D = P.second;
1646     SUnit *TargetSU = D.getSUnit();
1647     unsigned Reg = D.getReg();
1648     unsigned Lat = D.getLatency();
1649     SU->removePred(D);
1650     SDep Dep(SU, SDep::Anti, Reg);
1651     Dep.setLatency(Lat);
1652     TargetSU->addPred(Dep);
1653   }
1654 }
1655 
1656 /// Create the adjacency structure of the nodes in the graph.
1657 void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1658     SwingSchedulerDAG *DAG) {
1659   BitVector Added(SUnits.size());
1660   DenseMap<int, int> OutputDeps;
1661   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1662     Added.reset();
1663     // Add any successor to the adjacency matrix and exclude duplicates.
1664     for (auto &SI : SUnits[i].Succs) {
1665       // Only create a back-edge on the first and last nodes of a dependence
1666       // chain. This records any chains and adds them later.
1667       if (SI.getKind() == SDep::Output) {
1668         int N = SI.getSUnit()->NodeNum;
1669         int BackEdge = i;
1670         auto Dep = OutputDeps.find(BackEdge);
1671         if (Dep != OutputDeps.end()) {
1672           BackEdge = Dep->second;
1673           OutputDeps.erase(Dep);
1674         }
1675         OutputDeps[N] = BackEdge;
1676       }
1677       // Do not process a boundary node, an artificial node.
1678       // A back-edge is processed only if it goes to a Phi.
1679       if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() ||
1680           (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
1681         continue;
1682       int N = SI.getSUnit()->NodeNum;
1683       if (!Added.test(N)) {
1684         AdjK[i].push_back(N);
1685         Added.set(N);
1686       }
1687     }
1688     // A chain edge between a store and a load is treated as a back-edge in the
1689     // adjacency matrix.
1690     for (auto &PI : SUnits[i].Preds) {
1691       if (!SUnits[i].getInstr()->mayStore() ||
1692           !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
1693         continue;
1694       if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1695         int N = PI.getSUnit()->NodeNum;
1696         if (!Added.test(N)) {
1697           AdjK[i].push_back(N);
1698           Added.set(N);
1699         }
1700       }
1701     }
1702   }
1703   // Add back-edges in the adjacency matrix for the output dependences.
1704   for (auto &OD : OutputDeps)
1705     if (!Added.test(OD.second)) {
1706       AdjK[OD.first].push_back(OD.second);
1707       Added.set(OD.second);
1708     }
1709 }
1710 
1711 /// Identify an elementary circuit in the dependence graph starting at the
1712 /// specified node.
1713 bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
1714                                           const SwingSchedulerDAG *DAG,
1715                                           bool HasBackedge) {
1716   SUnit *SV = &SUnits[V];
1717   bool F = false;
1718   Stack.insert(SV);
1719   Blocked.set(V);
1720 
1721   for (auto W : AdjK[V]) {
1722     if (NumPaths > MaxPaths)
1723       break;
1724     if (W < S)
1725       continue;
1726     if (W == S) {
1727       if (!HasBackedge)
1728         NodeSets.push_back(NodeSet(Stack.begin(), Stack.end(), DAG));
1729       F = true;
1730       ++NumPaths;
1731       break;
1732     }
1733     if (!Blocked.test(W)) {
1734       if (circuit(W, S, NodeSets, DAG,
1735                   Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
1736         F = true;
1737     }
1738   }
1739 
1740   if (F)
1741     unblock(V);
1742   else {
1743     for (auto W : AdjK[V]) {
1744       if (W < S)
1745         continue;
1746       B[W].insert(SV);
1747     }
1748   }
1749   Stack.pop_back();
1750   return F;
1751 }
1752 
1753 /// Unblock a node in the circuit finding algorithm.
1754 void SwingSchedulerDAG::Circuits::unblock(int U) {
1755   Blocked.reset(U);
1756   SmallPtrSet<SUnit *, 4> &BU = B[U];
1757   while (!BU.empty()) {
1758     SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
1759     assert(SI != BU.end() && "Invalid B set.");
1760     SUnit *W = *SI;
1761     BU.erase(W);
1762     if (Blocked.test(W->NodeNum))
1763       unblock(W->NodeNum);
1764   }
1765 }
1766 
1767 /// Identify all the elementary circuits in the dependence graph using
1768 /// Johnson's circuit algorithm.
1769 void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1770   // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1771   // but we do this to find the circuits, and then change them back.
1772   swapAntiDependences(SUnits);
1773 
1774   Circuits Cir(SUnits, Topo);
1775   // Create the adjacency structure.
1776   Cir.createAdjacencyStructure(this);
1777   for (int I = 0, E = SUnits.size(); I != E; ++I) {
1778     Cir.reset();
1779     Cir.circuit(I, I, NodeSets, this);
1780   }
1781 
1782   // Change the dependences back so that we've created a DAG again.
1783   swapAntiDependences(SUnits);
1784 }
1785 
1786 // Create artificial dependencies between the source of COPY/REG_SEQUENCE that
1787 // is loop-carried to the USE in next iteration. This will help pipeliner avoid
1788 // additional copies that are needed across iterations. An artificial dependence
1789 // edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
1790 
1791 // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
1792 // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
1793 // PHI-------True-Dep------> USEOfPhi
1794 
1795 // The mutation creates
1796 // USEOfPHI -------Artificial-Dep---> SRCOfCopy
1797 
1798 // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
1799 // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
1800 // late  to avoid additional copies across iterations. The possible scheduling
1801 // order would be
1802 // USEOfPHI --- SRCOfCopy---  COPY/REG_SEQUENCE.
1803 
1804 void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
1805   for (SUnit &SU : DAG->SUnits) {
1806     // Find the COPY/REG_SEQUENCE instruction.
1807     if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
1808       continue;
1809 
1810     // Record the loop carried PHIs.
1811     SmallVector<SUnit *, 4> PHISUs;
1812     // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
1813     SmallVector<SUnit *, 4> SrcSUs;
1814 
1815     for (auto &Dep : SU.Preds) {
1816       SUnit *TmpSU = Dep.getSUnit();
1817       MachineInstr *TmpMI = TmpSU->getInstr();
1818       SDep::Kind DepKind = Dep.getKind();
1819       // Save the loop carried PHI.
1820       if (DepKind == SDep::Anti && TmpMI->isPHI())
1821         PHISUs.push_back(TmpSU);
1822       // Save the source of COPY/REG_SEQUENCE.
1823       // If the source has no pre-decessors, we will end up creating cycles.
1824       else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
1825         SrcSUs.push_back(TmpSU);
1826     }
1827 
1828     if (PHISUs.size() == 0 || SrcSUs.size() == 0)
1829       continue;
1830 
1831     // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
1832     // SUnit to the container.
1833     SmallVector<SUnit *, 8> UseSUs;
1834     // Do not use iterator based loop here as we are updating the container.
1835     for (size_t Index = 0; Index < PHISUs.size(); ++Index) {
1836       for (auto &Dep : PHISUs[Index]->Succs) {
1837         if (Dep.getKind() != SDep::Data)
1838           continue;
1839 
1840         SUnit *TmpSU = Dep.getSUnit();
1841         MachineInstr *TmpMI = TmpSU->getInstr();
1842         if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
1843           PHISUs.push_back(TmpSU);
1844           continue;
1845         }
1846         UseSUs.push_back(TmpSU);
1847       }
1848     }
1849 
1850     if (UseSUs.size() == 0)
1851       continue;
1852 
1853     SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
1854     // Add the artificial dependencies if it does not form a cycle.
1855     for (auto *I : UseSUs) {
1856       for (auto *Src : SrcSUs) {
1857         if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
1858           Src->addPred(SDep(I, SDep::Artificial));
1859           SDAG->Topo.AddPred(Src, I);
1860         }
1861       }
1862     }
1863   }
1864 }
1865 
1866 /// Return true for DAG nodes that we ignore when computing the cost functions.
1867 /// We ignore the back-edge recurrence in order to avoid unbounded recursion
1868 /// in the calculation of the ASAP, ALAP, etc functions.
1869 static bool ignoreDependence(const SDep &D, bool isPred) {
1870   if (D.isArtificial() || D.getSUnit()->isBoundaryNode())
1871     return true;
1872   return D.getKind() == SDep::Anti && isPred;
1873 }
1874 
1875 /// Compute several functions need to order the nodes for scheduling.
1876 ///  ASAP - Earliest time to schedule a node.
1877 ///  ALAP - Latest time to schedule a node.
1878 ///  MOV - Mobility function, difference between ALAP and ASAP.
1879 ///  D - Depth of each node.
1880 ///  H - Height of each node.
1881 void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
1882   ScheduleInfo.resize(SUnits.size());
1883 
1884   LLVM_DEBUG({
1885     for (int I : Topo) {
1886       const SUnit &SU = SUnits[I];
1887       dumpNode(SU);
1888     }
1889   });
1890 
1891   int maxASAP = 0;
1892   // Compute ASAP and ZeroLatencyDepth.
1893   for (int I : Topo) {
1894     int asap = 0;
1895     int zeroLatencyDepth = 0;
1896     SUnit *SU = &SUnits[I];
1897     for (const SDep &P : SU->Preds) {
1898       SUnit *pred = P.getSUnit();
1899       if (P.getLatency() == 0)
1900         zeroLatencyDepth =
1901             std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
1902       if (ignoreDependence(P, true))
1903         continue;
1904       asap = std::max(asap, (int)(getASAP(pred) + P.getLatency() -
1905                                   getDistance(pred, SU, P) * MII));
1906     }
1907     maxASAP = std::max(maxASAP, asap);
1908     ScheduleInfo[I].ASAP = asap;
1909     ScheduleInfo[I].ZeroLatencyDepth = zeroLatencyDepth;
1910   }
1911 
1912   // Compute ALAP, ZeroLatencyHeight, and MOV.
1913   for (int I : llvm::reverse(Topo)) {
1914     int alap = maxASAP;
1915     int zeroLatencyHeight = 0;
1916     SUnit *SU = &SUnits[I];
1917     for (const SDep &S : SU->Succs) {
1918       SUnit *succ = S.getSUnit();
1919       if (succ->isBoundaryNode())
1920         continue;
1921       if (S.getLatency() == 0)
1922         zeroLatencyHeight =
1923             std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
1924       if (ignoreDependence(S, true))
1925         continue;
1926       alap = std::min(alap, (int)(getALAP(succ) - S.getLatency() +
1927                                   getDistance(SU, succ, S) * MII));
1928     }
1929 
1930     ScheduleInfo[I].ALAP = alap;
1931     ScheduleInfo[I].ZeroLatencyHeight = zeroLatencyHeight;
1932   }
1933 
1934   // After computing the node functions, compute the summary for each node set.
1935   for (NodeSet &I : NodeSets)
1936     I.computeNodeSetInfo(this);
1937 
1938   LLVM_DEBUG({
1939     for (unsigned i = 0; i < SUnits.size(); i++) {
1940       dbgs() << "\tNode " << i << ":\n";
1941       dbgs() << "\t   ASAP = " << getASAP(&SUnits[i]) << "\n";
1942       dbgs() << "\t   ALAP = " << getALAP(&SUnits[i]) << "\n";
1943       dbgs() << "\t   MOV  = " << getMOV(&SUnits[i]) << "\n";
1944       dbgs() << "\t   D    = " << getDepth(&SUnits[i]) << "\n";
1945       dbgs() << "\t   H    = " << getHeight(&SUnits[i]) << "\n";
1946       dbgs() << "\t   ZLD  = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
1947       dbgs() << "\t   ZLH  = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
1948     }
1949   });
1950 }
1951 
1952 /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1953 /// as the predecessors of the elements of NodeOrder that are not also in
1954 /// NodeOrder.
1955 static bool pred_L(SetVector<SUnit *> &NodeOrder,
1956                    SmallSetVector<SUnit *, 8> &Preds,
1957                    const NodeSet *S = nullptr) {
1958   Preds.clear();
1959   for (const SUnit *SU : NodeOrder) {
1960     for (const SDep &Pred : SU->Preds) {
1961       if (S && S->count(Pred.getSUnit()) == 0)
1962         continue;
1963       if (ignoreDependence(Pred, true))
1964         continue;
1965       if (NodeOrder.count(Pred.getSUnit()) == 0)
1966         Preds.insert(Pred.getSUnit());
1967     }
1968     // Back-edges are predecessors with an anti-dependence.
1969     for (const SDep &Succ : SU->Succs) {
1970       if (Succ.getKind() != SDep::Anti)
1971         continue;
1972       if (S && S->count(Succ.getSUnit()) == 0)
1973         continue;
1974       if (NodeOrder.count(Succ.getSUnit()) == 0)
1975         Preds.insert(Succ.getSUnit());
1976     }
1977   }
1978   return !Preds.empty();
1979 }
1980 
1981 /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1982 /// as the successors of the elements of NodeOrder that are not also in
1983 /// NodeOrder.
1984 static bool succ_L(SetVector<SUnit *> &NodeOrder,
1985                    SmallSetVector<SUnit *, 8> &Succs,
1986                    const NodeSet *S = nullptr) {
1987   Succs.clear();
1988   for (const SUnit *SU : NodeOrder) {
1989     for (const SDep &Succ : SU->Succs) {
1990       if (S && S->count(Succ.getSUnit()) == 0)
1991         continue;
1992       if (ignoreDependence(Succ, false))
1993         continue;
1994       if (NodeOrder.count(Succ.getSUnit()) == 0)
1995         Succs.insert(Succ.getSUnit());
1996     }
1997     for (const SDep &Pred : SU->Preds) {
1998       if (Pred.getKind() != SDep::Anti)
1999         continue;
2000       if (S && S->count(Pred.getSUnit()) == 0)
2001         continue;
2002       if (NodeOrder.count(Pred.getSUnit()) == 0)
2003         Succs.insert(Pred.getSUnit());
2004     }
2005   }
2006   return !Succs.empty();
2007 }
2008 
2009 /// Return true if there is a path from the specified node to any of the nodes
2010 /// in DestNodes. Keep track and return the nodes in any path.
2011 static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
2012                         SetVector<SUnit *> &DestNodes,
2013                         SetVector<SUnit *> &Exclude,
2014                         SmallPtrSet<SUnit *, 8> &Visited) {
2015   if (Cur->isBoundaryNode())
2016     return false;
2017   if (Exclude.contains(Cur))
2018     return false;
2019   if (DestNodes.contains(Cur))
2020     return true;
2021   if (!Visited.insert(Cur).second)
2022     return Path.contains(Cur);
2023   bool FoundPath = false;
2024   for (auto &SI : Cur->Succs)
2025     if (!ignoreDependence(SI, false))
2026       FoundPath |=
2027           computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
2028   for (auto &PI : Cur->Preds)
2029     if (PI.getKind() == SDep::Anti)
2030       FoundPath |=
2031           computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
2032   if (FoundPath)
2033     Path.insert(Cur);
2034   return FoundPath;
2035 }
2036 
2037 /// Compute the live-out registers for the instructions in a node-set.
2038 /// The live-out registers are those that are defined in the node-set,
2039 /// but not used. Except for use operands of Phis.
2040 static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
2041                             NodeSet &NS) {
2042   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2043   MachineRegisterInfo &MRI = MF.getRegInfo();
2044   SmallVector<RegisterMaskPair, 8> LiveOutRegs;
2045   SmallSet<unsigned, 4> Uses;
2046   for (SUnit *SU : NS) {
2047     const MachineInstr *MI = SU->getInstr();
2048     if (MI->isPHI())
2049       continue;
2050     for (const MachineOperand &MO : MI->all_uses()) {
2051       Register Reg = MO.getReg();
2052       if (Reg.isVirtual())
2053         Uses.insert(Reg);
2054       else if (MRI.isAllocatable(Reg))
2055         for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
2056           Uses.insert(Unit);
2057     }
2058   }
2059   for (SUnit *SU : NS)
2060     for (const MachineOperand &MO : SU->getInstr()->all_defs())
2061       if (!MO.isDead()) {
2062         Register Reg = MO.getReg();
2063         if (Reg.isVirtual()) {
2064           if (!Uses.count(Reg))
2065             LiveOutRegs.push_back(RegisterMaskPair(Reg,
2066                                                    LaneBitmask::getNone()));
2067         } else if (MRI.isAllocatable(Reg)) {
2068           for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
2069             if (!Uses.count(Unit))
2070               LiveOutRegs.push_back(
2071                   RegisterMaskPair(Unit, LaneBitmask::getNone()));
2072         }
2073       }
2074   RPTracker.addLiveRegs(LiveOutRegs);
2075 }
2076 
2077 /// A heuristic to filter nodes in recurrent node-sets if the register
2078 /// pressure of a set is too high.
2079 void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
2080   for (auto &NS : NodeSets) {
2081     // Skip small node-sets since they won't cause register pressure problems.
2082     if (NS.size() <= 2)
2083       continue;
2084     IntervalPressure RecRegPressure;
2085     RegPressureTracker RecRPTracker(RecRegPressure);
2086     RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
2087     computeLiveOuts(MF, RecRPTracker, NS);
2088     RecRPTracker.closeBottom();
2089 
2090     std::vector<SUnit *> SUnits(NS.begin(), NS.end());
2091     llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
2092       return A->NodeNum > B->NodeNum;
2093     });
2094 
2095     for (auto &SU : SUnits) {
2096       // Since we're computing the register pressure for a subset of the
2097       // instructions in a block, we need to set the tracker for each
2098       // instruction in the node-set. The tracker is set to the instruction
2099       // just after the one we're interested in.
2100       MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
2101       RecRPTracker.setPos(std::next(CurInstI));
2102 
2103       RegPressureDelta RPDelta;
2104       ArrayRef<PressureChange> CriticalPSets;
2105       RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
2106                                              CriticalPSets,
2107                                              RecRegPressure.MaxSetPressure);
2108       if (RPDelta.Excess.isValid()) {
2109         LLVM_DEBUG(
2110             dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
2111                    << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
2112                    << ":" << RPDelta.Excess.getUnitInc() << "\n");
2113         NS.setExceedPressure(SU);
2114         break;
2115       }
2116       RecRPTracker.recede();
2117     }
2118   }
2119 }
2120 
2121 /// A heuristic to colocate node sets that have the same set of
2122 /// successors.
2123 void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
2124   unsigned Colocate = 0;
2125   for (int i = 0, e = NodeSets.size(); i < e; ++i) {
2126     NodeSet &N1 = NodeSets[i];
2127     SmallSetVector<SUnit *, 8> S1;
2128     if (N1.empty() || !succ_L(N1, S1))
2129       continue;
2130     for (int j = i + 1; j < e; ++j) {
2131       NodeSet &N2 = NodeSets[j];
2132       if (N1.compareRecMII(N2) != 0)
2133         continue;
2134       SmallSetVector<SUnit *, 8> S2;
2135       if (N2.empty() || !succ_L(N2, S2))
2136         continue;
2137       if (llvm::set_is_subset(S1, S2) && S1.size() == S2.size()) {
2138         N1.setColocate(++Colocate);
2139         N2.setColocate(Colocate);
2140         break;
2141       }
2142     }
2143   }
2144 }
2145 
2146 /// Check if the existing node-sets are profitable. If not, then ignore the
2147 /// recurrent node-sets, and attempt to schedule all nodes together. This is
2148 /// a heuristic. If the MII is large and all the recurrent node-sets are small,
2149 /// then it's best to try to schedule all instructions together instead of
2150 /// starting with the recurrent node-sets.
2151 void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
2152   // Look for loops with a large MII.
2153   if (MII < 17)
2154     return;
2155   // Check if the node-set contains only a simple add recurrence.
2156   for (auto &NS : NodeSets) {
2157     if (NS.getRecMII() > 2)
2158       return;
2159     if (NS.getMaxDepth() > MII)
2160       return;
2161   }
2162   NodeSets.clear();
2163   LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
2164 }
2165 
2166 /// Add the nodes that do not belong to a recurrence set into groups
2167 /// based upon connected components.
2168 void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
2169   SetVector<SUnit *> NodesAdded;
2170   SmallPtrSet<SUnit *, 8> Visited;
2171   // Add the nodes that are on a path between the previous node sets and
2172   // the current node set.
2173   for (NodeSet &I : NodeSets) {
2174     SmallSetVector<SUnit *, 8> N;
2175     // Add the nodes from the current node set to the previous node set.
2176     if (succ_L(I, N)) {
2177       SetVector<SUnit *> Path;
2178       for (SUnit *NI : N) {
2179         Visited.clear();
2180         computePath(NI, Path, NodesAdded, I, Visited);
2181       }
2182       if (!Path.empty())
2183         I.insert(Path.begin(), Path.end());
2184     }
2185     // Add the nodes from the previous node set to the current node set.
2186     N.clear();
2187     if (succ_L(NodesAdded, N)) {
2188       SetVector<SUnit *> Path;
2189       for (SUnit *NI : N) {
2190         Visited.clear();
2191         computePath(NI, Path, I, NodesAdded, Visited);
2192       }
2193       if (!Path.empty())
2194         I.insert(Path.begin(), Path.end());
2195     }
2196     NodesAdded.insert(I.begin(), I.end());
2197   }
2198 
2199   // Create a new node set with the connected nodes of any successor of a node
2200   // in a recurrent set.
2201   NodeSet NewSet;
2202   SmallSetVector<SUnit *, 8> N;
2203   if (succ_L(NodesAdded, N))
2204     for (SUnit *I : N)
2205       addConnectedNodes(I, NewSet, NodesAdded);
2206   if (!NewSet.empty())
2207     NodeSets.push_back(NewSet);
2208 
2209   // Create a new node set with the connected nodes of any predecessor of a node
2210   // in a recurrent set.
2211   NewSet.clear();
2212   if (pred_L(NodesAdded, N))
2213     for (SUnit *I : N)
2214       addConnectedNodes(I, NewSet, NodesAdded);
2215   if (!NewSet.empty())
2216     NodeSets.push_back(NewSet);
2217 
2218   // Create new nodes sets with the connected nodes any remaining node that
2219   // has no predecessor.
2220   for (SUnit &SU : SUnits) {
2221     if (NodesAdded.count(&SU) == 0) {
2222       NewSet.clear();
2223       addConnectedNodes(&SU, NewSet, NodesAdded);
2224       if (!NewSet.empty())
2225         NodeSets.push_back(NewSet);
2226     }
2227   }
2228 }
2229 
2230 /// Add the node to the set, and add all of its connected nodes to the set.
2231 void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
2232                                           SetVector<SUnit *> &NodesAdded) {
2233   NewSet.insert(SU);
2234   NodesAdded.insert(SU);
2235   for (auto &SI : SU->Succs) {
2236     SUnit *Successor = SI.getSUnit();
2237     if (!SI.isArtificial() && !Successor->isBoundaryNode() &&
2238         NodesAdded.count(Successor) == 0)
2239       addConnectedNodes(Successor, NewSet, NodesAdded);
2240   }
2241   for (auto &PI : SU->Preds) {
2242     SUnit *Predecessor = PI.getSUnit();
2243     if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
2244       addConnectedNodes(Predecessor, NewSet, NodesAdded);
2245   }
2246 }
2247 
2248 /// Return true if Set1 contains elements in Set2. The elements in common
2249 /// are returned in a different container.
2250 static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
2251                         SmallSetVector<SUnit *, 8> &Result) {
2252   Result.clear();
2253   for (SUnit *SU : Set1) {
2254     if (Set2.count(SU) != 0)
2255       Result.insert(SU);
2256   }
2257   return !Result.empty();
2258 }
2259 
2260 /// Merge the recurrence node sets that have the same initial node.
2261 void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
2262   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
2263        ++I) {
2264     NodeSet &NI = *I;
2265     for (NodeSetType::iterator J = I + 1; J != E;) {
2266       NodeSet &NJ = *J;
2267       if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
2268         if (NJ.compareRecMII(NI) > 0)
2269           NI.setRecMII(NJ.getRecMII());
2270         for (SUnit *SU : *J)
2271           I->insert(SU);
2272         NodeSets.erase(J);
2273         E = NodeSets.end();
2274       } else {
2275         ++J;
2276       }
2277     }
2278   }
2279 }
2280 
2281 /// Remove nodes that have been scheduled in previous NodeSets.
2282 void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
2283   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
2284        ++I)
2285     for (NodeSetType::iterator J = I + 1; J != E;) {
2286       J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
2287 
2288       if (J->empty()) {
2289         NodeSets.erase(J);
2290         E = NodeSets.end();
2291       } else {
2292         ++J;
2293       }
2294     }
2295 }
2296 
2297 /// Compute an ordered list of the dependence graph nodes, which
2298 /// indicates the order that the nodes will be scheduled.  This is a
2299 /// two-level algorithm. First, a partial order is created, which
2300 /// consists of a list of sets ordered from highest to lowest priority.
2301 void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
2302   SmallSetVector<SUnit *, 8> R;
2303   NodeOrder.clear();
2304 
2305   for (auto &Nodes : NodeSets) {
2306     LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
2307     OrderKind Order;
2308     SmallSetVector<SUnit *, 8> N;
2309     if (pred_L(NodeOrder, N) && llvm::set_is_subset(N, Nodes)) {
2310       R.insert(N.begin(), N.end());
2311       Order = BottomUp;
2312       LLVM_DEBUG(dbgs() << "  Bottom up (preds) ");
2313     } else if (succ_L(NodeOrder, N) && llvm::set_is_subset(N, Nodes)) {
2314       R.insert(N.begin(), N.end());
2315       Order = TopDown;
2316       LLVM_DEBUG(dbgs() << "  Top down (succs) ");
2317     } else if (isIntersect(N, Nodes, R)) {
2318       // If some of the successors are in the existing node-set, then use the
2319       // top-down ordering.
2320       Order = TopDown;
2321       LLVM_DEBUG(dbgs() << "  Top down (intersect) ");
2322     } else if (NodeSets.size() == 1) {
2323       for (const auto &N : Nodes)
2324         if (N->Succs.size() == 0)
2325           R.insert(N);
2326       Order = BottomUp;
2327       LLVM_DEBUG(dbgs() << "  Bottom up (all) ");
2328     } else {
2329       // Find the node with the highest ASAP.
2330       SUnit *maxASAP = nullptr;
2331       for (SUnit *SU : Nodes) {
2332         if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
2333             (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
2334           maxASAP = SU;
2335       }
2336       R.insert(maxASAP);
2337       Order = BottomUp;
2338       LLVM_DEBUG(dbgs() << "  Bottom up (default) ");
2339     }
2340 
2341     while (!R.empty()) {
2342       if (Order == TopDown) {
2343         // Choose the node with the maximum height.  If more than one, choose
2344         // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
2345         // choose the node with the lowest MOV.
2346         while (!R.empty()) {
2347           SUnit *maxHeight = nullptr;
2348           for (SUnit *I : R) {
2349             if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
2350               maxHeight = I;
2351             else if (getHeight(I) == getHeight(maxHeight) &&
2352                      getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
2353               maxHeight = I;
2354             else if (getHeight(I) == getHeight(maxHeight) &&
2355                      getZeroLatencyHeight(I) ==
2356                          getZeroLatencyHeight(maxHeight) &&
2357                      getMOV(I) < getMOV(maxHeight))
2358               maxHeight = I;
2359           }
2360           NodeOrder.insert(maxHeight);
2361           LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
2362           R.remove(maxHeight);
2363           for (const auto &I : maxHeight->Succs) {
2364             if (Nodes.count(I.getSUnit()) == 0)
2365               continue;
2366             if (NodeOrder.contains(I.getSUnit()))
2367               continue;
2368             if (ignoreDependence(I, false))
2369               continue;
2370             R.insert(I.getSUnit());
2371           }
2372           // Back-edges are predecessors with an anti-dependence.
2373           for (const auto &I : maxHeight->Preds) {
2374             if (I.getKind() != SDep::Anti)
2375               continue;
2376             if (Nodes.count(I.getSUnit()) == 0)
2377               continue;
2378             if (NodeOrder.contains(I.getSUnit()))
2379               continue;
2380             R.insert(I.getSUnit());
2381           }
2382         }
2383         Order = BottomUp;
2384         LLVM_DEBUG(dbgs() << "\n   Switching order to bottom up ");
2385         SmallSetVector<SUnit *, 8> N;
2386         if (pred_L(NodeOrder, N, &Nodes))
2387           R.insert(N.begin(), N.end());
2388       } else {
2389         // Choose the node with the maximum depth.  If more than one, choose
2390         // the node with the maximum ZeroLatencyDepth. If still more than one,
2391         // choose the node with the lowest MOV.
2392         while (!R.empty()) {
2393           SUnit *maxDepth = nullptr;
2394           for (SUnit *I : R) {
2395             if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
2396               maxDepth = I;
2397             else if (getDepth(I) == getDepth(maxDepth) &&
2398                      getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
2399               maxDepth = I;
2400             else if (getDepth(I) == getDepth(maxDepth) &&
2401                      getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
2402                      getMOV(I) < getMOV(maxDepth))
2403               maxDepth = I;
2404           }
2405           NodeOrder.insert(maxDepth);
2406           LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
2407           R.remove(maxDepth);
2408           if (Nodes.isExceedSU(maxDepth)) {
2409             Order = TopDown;
2410             R.clear();
2411             R.insert(Nodes.getNode(0));
2412             break;
2413           }
2414           for (const auto &I : maxDepth->Preds) {
2415             if (Nodes.count(I.getSUnit()) == 0)
2416               continue;
2417             if (NodeOrder.contains(I.getSUnit()))
2418               continue;
2419             R.insert(I.getSUnit());
2420           }
2421           // Back-edges are predecessors with an anti-dependence.
2422           for (const auto &I : maxDepth->Succs) {
2423             if (I.getKind() != SDep::Anti)
2424               continue;
2425             if (Nodes.count(I.getSUnit()) == 0)
2426               continue;
2427             if (NodeOrder.contains(I.getSUnit()))
2428               continue;
2429             R.insert(I.getSUnit());
2430           }
2431         }
2432         Order = TopDown;
2433         LLVM_DEBUG(dbgs() << "\n   Switching order to top down ");
2434         SmallSetVector<SUnit *, 8> N;
2435         if (succ_L(NodeOrder, N, &Nodes))
2436           R.insert(N.begin(), N.end());
2437       }
2438     }
2439     LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
2440   }
2441 
2442   LLVM_DEBUG({
2443     dbgs() << "Node order: ";
2444     for (SUnit *I : NodeOrder)
2445       dbgs() << " " << I->NodeNum << " ";
2446     dbgs() << "\n";
2447   });
2448 }
2449 
2450 /// Process the nodes in the computed order and create the pipelined schedule
2451 /// of the instructions, if possible. Return true if a schedule is found.
2452 bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
2453 
2454   if (NodeOrder.empty()){
2455     LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
2456     return false;
2457   }
2458 
2459   bool scheduleFound = false;
2460   std::unique_ptr<HighRegisterPressureDetector> HRPDetector;
2461   if (LimitRegPressure) {
2462     HRPDetector =
2463         std::make_unique<HighRegisterPressureDetector>(Loop.getHeader(), MF);
2464     HRPDetector->init(RegClassInfo);
2465   }
2466   // Keep increasing II until a valid schedule is found.
2467   for (unsigned II = MII; II <= MAX_II && !scheduleFound; ++II) {
2468     Schedule.reset();
2469     Schedule.setInitiationInterval(II);
2470     LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
2471 
2472     SetVector<SUnit *>::iterator NI = NodeOrder.begin();
2473     SetVector<SUnit *>::iterator NE = NodeOrder.end();
2474     do {
2475       SUnit *SU = *NI;
2476 
2477       // Compute the schedule time for the instruction, which is based
2478       // upon the scheduled time for any predecessors/successors.
2479       int EarlyStart = INT_MIN;
2480       int LateStart = INT_MAX;
2481       Schedule.computeStart(SU, &EarlyStart, &LateStart, II, this);
2482       LLVM_DEBUG({
2483         dbgs() << "\n";
2484         dbgs() << "Inst (" << SU->NodeNum << ") ";
2485         SU->getInstr()->dump();
2486         dbgs() << "\n";
2487       });
2488       LLVM_DEBUG(
2489           dbgs() << format("\tes: %8x ls: %8x\n", EarlyStart, LateStart));
2490 
2491       if (EarlyStart > LateStart)
2492         scheduleFound = false;
2493       else if (EarlyStart != INT_MIN && LateStart == INT_MAX)
2494         scheduleFound =
2495             Schedule.insert(SU, EarlyStart, EarlyStart + (int)II - 1, II);
2496       else if (EarlyStart == INT_MIN && LateStart != INT_MAX)
2497         scheduleFound =
2498             Schedule.insert(SU, LateStart, LateStart - (int)II + 1, II);
2499       else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
2500         LateStart = std::min(LateStart, EarlyStart + (int)II - 1);
2501         // When scheduling a Phi it is better to start at the late cycle and
2502         // go backwards. The default order may insert the Phi too far away
2503         // from its first dependence.
2504         // Also, do backward search when all scheduled predecessors are
2505         // loop-carried output/order dependencies. Empirically, there are also
2506         // cases where scheduling becomes possible with backward search.
2507         if (SU->getInstr()->isPHI() ||
2508             Schedule.onlyHasLoopCarriedOutputOrOrderPreds(SU, this))
2509           scheduleFound = Schedule.insert(SU, LateStart, EarlyStart, II);
2510         else
2511           scheduleFound = Schedule.insert(SU, EarlyStart, LateStart, II);
2512       } else {
2513         int FirstCycle = Schedule.getFirstCycle();
2514         scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
2515                                         FirstCycle + getASAP(SU) + II - 1, II);
2516       }
2517 
2518       // Even if we find a schedule, make sure the schedule doesn't exceed the
2519       // allowable number of stages. We keep trying if this happens.
2520       if (scheduleFound)
2521         if (SwpMaxStages > -1 &&
2522             Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
2523           scheduleFound = false;
2524 
2525       LLVM_DEBUG({
2526         if (!scheduleFound)
2527           dbgs() << "\tCan't schedule\n";
2528       });
2529     } while (++NI != NE && scheduleFound);
2530 
2531     // If a schedule is found, ensure non-pipelined instructions are in stage 0
2532     if (scheduleFound)
2533       scheduleFound =
2534           Schedule.normalizeNonPipelinedInstructions(this, LoopPipelinerInfo);
2535 
2536     // If a schedule is found, check if it is a valid schedule too.
2537     if (scheduleFound)
2538       scheduleFound = Schedule.isValidSchedule(this);
2539 
2540     // If a schedule was found and the option is enabled, check if the schedule
2541     // might generate additional register spills/fills.
2542     if (scheduleFound && LimitRegPressure)
2543       scheduleFound =
2544           !HRPDetector->detect(this, Schedule, Schedule.getMaxStageCount());
2545   }
2546 
2547   LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound
2548                     << " (II=" << Schedule.getInitiationInterval()
2549                     << ")\n");
2550 
2551   if (scheduleFound) {
2552     scheduleFound = LoopPipelinerInfo->shouldUseSchedule(*this, Schedule);
2553     if (!scheduleFound)
2554       LLVM_DEBUG(dbgs() << "Target rejected schedule\n");
2555   }
2556 
2557   if (scheduleFound) {
2558     Schedule.finalizeSchedule(this);
2559     Pass.ORE->emit([&]() {
2560       return MachineOptimizationRemarkAnalysis(
2561                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
2562              << "Schedule found with Initiation Interval: "
2563              << ore::NV("II", Schedule.getInitiationInterval())
2564              << ", MaxStageCount: "
2565              << ore::NV("MaxStageCount", Schedule.getMaxStageCount());
2566     });
2567   } else
2568     Schedule.reset();
2569 
2570   return scheduleFound && Schedule.getMaxStageCount() > 0;
2571 }
2572 
2573 /// Return true if we can compute the amount the instruction changes
2574 /// during each iteration. Set Delta to the amount of the change.
2575 bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) const {
2576   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2577   const MachineOperand *BaseOp;
2578   int64_t Offset;
2579   bool OffsetIsScalable;
2580   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
2581     return false;
2582 
2583   // FIXME: This algorithm assumes instructions have fixed-size offsets.
2584   if (OffsetIsScalable)
2585     return false;
2586 
2587   if (!BaseOp->isReg())
2588     return false;
2589 
2590   Register BaseReg = BaseOp->getReg();
2591 
2592   MachineRegisterInfo &MRI = MF.getRegInfo();
2593   // Check if there is a Phi. If so, get the definition in the loop.
2594   MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
2595   if (BaseDef && BaseDef->isPHI()) {
2596     BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
2597     BaseDef = MRI.getVRegDef(BaseReg);
2598   }
2599   if (!BaseDef)
2600     return false;
2601 
2602   int D = 0;
2603   if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
2604     return false;
2605 
2606   Delta = D;
2607   return true;
2608 }
2609 
2610 /// Check if we can change the instruction to use an offset value from the
2611 /// previous iteration. If so, return true and set the base and offset values
2612 /// so that we can rewrite the load, if necessary.
2613 ///   v1 = Phi(v0, v3)
2614 ///   v2 = load v1, 0
2615 ///   v3 = post_store v1, 4, x
2616 /// This function enables the load to be rewritten as v2 = load v3, 4.
2617 bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
2618                                               unsigned &BasePos,
2619                                               unsigned &OffsetPos,
2620                                               unsigned &NewBase,
2621                                               int64_t &Offset) {
2622   // Get the load instruction.
2623   if (TII->isPostIncrement(*MI))
2624     return false;
2625   unsigned BasePosLd, OffsetPosLd;
2626   if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
2627     return false;
2628   Register BaseReg = MI->getOperand(BasePosLd).getReg();
2629 
2630   // Look for the Phi instruction.
2631   MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
2632   MachineInstr *Phi = MRI.getVRegDef(BaseReg);
2633   if (!Phi || !Phi->isPHI())
2634     return false;
2635   // Get the register defined in the loop block.
2636   unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
2637   if (!PrevReg)
2638     return false;
2639 
2640   // Check for the post-increment load/store instruction.
2641   MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
2642   if (!PrevDef || PrevDef == MI)
2643     return false;
2644 
2645   if (!TII->isPostIncrement(*PrevDef))
2646     return false;
2647 
2648   unsigned BasePos1 = 0, OffsetPos1 = 0;
2649   if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
2650     return false;
2651 
2652   // Make sure that the instructions do not access the same memory location in
2653   // the next iteration.
2654   int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
2655   int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
2656   MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2657   NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
2658   bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
2659   MF.deleteMachineInstr(NewMI);
2660   if (!Disjoint)
2661     return false;
2662 
2663   // Set the return value once we determine that we return true.
2664   BasePos = BasePosLd;
2665   OffsetPos = OffsetPosLd;
2666   NewBase = PrevReg;
2667   Offset = StoreOffset;
2668   return true;
2669 }
2670 
2671 /// Apply changes to the instruction if needed. The changes are need
2672 /// to improve the scheduling and depend up on the final schedule.
2673 void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
2674                                          SMSchedule &Schedule) {
2675   SUnit *SU = getSUnit(MI);
2676   DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
2677       InstrChanges.find(SU);
2678   if (It != InstrChanges.end()) {
2679     std::pair<unsigned, int64_t> RegAndOffset = It->second;
2680     unsigned BasePos, OffsetPos;
2681     if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
2682       return;
2683     Register BaseReg = MI->getOperand(BasePos).getReg();
2684     MachineInstr *LoopDef = findDefInLoop(BaseReg);
2685     int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
2686     int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
2687     int BaseStageNum = Schedule.stageScheduled(SU);
2688     int BaseCycleNum = Schedule.cycleScheduled(SU);
2689     if (BaseStageNum < DefStageNum) {
2690       MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2691       int OffsetDiff = DefStageNum - BaseStageNum;
2692       if (DefCycleNum < BaseCycleNum) {
2693         NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
2694         if (OffsetDiff > 0)
2695           --OffsetDiff;
2696       }
2697       int64_t NewOffset =
2698           MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
2699       NewMI->getOperand(OffsetPos).setImm(NewOffset);
2700       SU->setInstr(NewMI);
2701       MISUnitMap[NewMI] = SU;
2702       NewMIs[MI] = NewMI;
2703     }
2704   }
2705 }
2706 
2707 /// Return the instruction in the loop that defines the register.
2708 /// If the definition is a Phi, then follow the Phi operand to
2709 /// the instruction in the loop.
2710 MachineInstr *SwingSchedulerDAG::findDefInLoop(Register Reg) {
2711   SmallPtrSet<MachineInstr *, 8> Visited;
2712   MachineInstr *Def = MRI.getVRegDef(Reg);
2713   while (Def->isPHI()) {
2714     if (!Visited.insert(Def).second)
2715       break;
2716     for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
2717       if (Def->getOperand(i + 1).getMBB() == BB) {
2718         Def = MRI.getVRegDef(Def->getOperand(i).getReg());
2719         break;
2720       }
2721   }
2722   return Def;
2723 }
2724 
2725 /// Return true for an order or output dependence that is loop carried
2726 /// potentially. A dependence is loop carried if the destination defines a value
2727 /// that may be used or defined by the source in a subsequent iteration.
2728 bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
2729                                          bool isSucc) const {
2730   if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
2731       Dep.isArtificial() || Dep.getSUnit()->isBoundaryNode())
2732     return false;
2733 
2734   if (!SwpPruneLoopCarried)
2735     return true;
2736 
2737   if (Dep.getKind() == SDep::Output)
2738     return true;
2739 
2740   MachineInstr *SI = Source->getInstr();
2741   MachineInstr *DI = Dep.getSUnit()->getInstr();
2742   if (!isSucc)
2743     std::swap(SI, DI);
2744   assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
2745 
2746   // Assume ordered loads and stores may have a loop carried dependence.
2747   if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
2748       SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
2749       SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
2750     return true;
2751 
2752   if (!DI->mayLoadOrStore() || !SI->mayLoadOrStore())
2753     return false;
2754 
2755   // The conservative assumption is that a dependence between memory operations
2756   // may be loop carried. The following code checks when it can be proved that
2757   // there is no loop carried dependence.
2758   unsigned DeltaS, DeltaD;
2759   if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
2760     return true;
2761 
2762   const MachineOperand *BaseOpS, *BaseOpD;
2763   int64_t OffsetS, OffsetD;
2764   bool OffsetSIsScalable, OffsetDIsScalable;
2765   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2766   if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, OffsetSIsScalable,
2767                                     TRI) ||
2768       !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, OffsetDIsScalable,
2769                                     TRI))
2770     return true;
2771 
2772   assert(!OffsetSIsScalable && !OffsetDIsScalable &&
2773          "Expected offsets to be byte offsets");
2774 
2775   MachineInstr *DefS = MRI.getVRegDef(BaseOpS->getReg());
2776   MachineInstr *DefD = MRI.getVRegDef(BaseOpD->getReg());
2777   if (!DefS || !DefD || !DefS->isPHI() || !DefD->isPHI())
2778     return true;
2779 
2780   unsigned InitValS = 0;
2781   unsigned LoopValS = 0;
2782   unsigned InitValD = 0;
2783   unsigned LoopValD = 0;
2784   getPhiRegs(*DefS, BB, InitValS, LoopValS);
2785   getPhiRegs(*DefD, BB, InitValD, LoopValD);
2786   MachineInstr *InitDefS = MRI.getVRegDef(InitValS);
2787   MachineInstr *InitDefD = MRI.getVRegDef(InitValD);
2788 
2789   if (!InitDefS->isIdenticalTo(*InitDefD))
2790     return true;
2791 
2792   // Check that the base register is incremented by a constant value for each
2793   // iteration.
2794   MachineInstr *LoopDefS = MRI.getVRegDef(LoopValS);
2795   int D = 0;
2796   if (!LoopDefS || !TII->getIncrementValue(*LoopDefS, D))
2797     return true;
2798 
2799   LocationSize AccessSizeS = (*SI->memoperands_begin())->getSize();
2800   LocationSize AccessSizeD = (*DI->memoperands_begin())->getSize();
2801 
2802   // This is the main test, which checks the offset values and the loop
2803   // increment value to determine if the accesses may be loop carried.
2804   if (!AccessSizeS.hasValue() || !AccessSizeD.hasValue())
2805     return true;
2806 
2807   if (DeltaS != DeltaD || DeltaS < AccessSizeS.getValue() ||
2808       DeltaD < AccessSizeD.getValue())
2809     return true;
2810 
2811   return (OffsetS + (int64_t)AccessSizeS.getValue() <
2812           OffsetD + (int64_t)AccessSizeD.getValue());
2813 }
2814 
2815 void SwingSchedulerDAG::postProcessDAG() {
2816   for (auto &M : Mutations)
2817     M->apply(this);
2818 }
2819 
2820 /// Try to schedule the node at the specified StartCycle and continue
2821 /// until the node is schedule or the EndCycle is reached.  This function
2822 /// returns true if the node is scheduled.  This routine may search either
2823 /// forward or backward for a place to insert the instruction based upon
2824 /// the relative values of StartCycle and EndCycle.
2825 bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
2826   bool forward = true;
2827   LLVM_DEBUG({
2828     dbgs() << "Trying to insert node between " << StartCycle << " and "
2829            << EndCycle << " II: " << II << "\n";
2830   });
2831   if (StartCycle > EndCycle)
2832     forward = false;
2833 
2834   // The terminating condition depends on the direction.
2835   int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
2836   for (int curCycle = StartCycle; curCycle != termCycle;
2837        forward ? ++curCycle : --curCycle) {
2838 
2839     if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
2840         ProcItinResources.canReserveResources(*SU, curCycle)) {
2841       LLVM_DEBUG({
2842         dbgs() << "\tinsert at cycle " << curCycle << " ";
2843         SU->getInstr()->dump();
2844       });
2845 
2846       if (!ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()))
2847         ProcItinResources.reserveResources(*SU, curCycle);
2848       ScheduledInstrs[curCycle].push_back(SU);
2849       InstrToCycle.insert(std::make_pair(SU, curCycle));
2850       if (curCycle > LastCycle)
2851         LastCycle = curCycle;
2852       if (curCycle < FirstCycle)
2853         FirstCycle = curCycle;
2854       return true;
2855     }
2856     LLVM_DEBUG({
2857       dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
2858       SU->getInstr()->dump();
2859     });
2860   }
2861   return false;
2862 }
2863 
2864 // Return the cycle of the earliest scheduled instruction in the chain.
2865 int SMSchedule::earliestCycleInChain(const SDep &Dep) {
2866   SmallPtrSet<SUnit *, 8> Visited;
2867   SmallVector<SDep, 8> Worklist;
2868   Worklist.push_back(Dep);
2869   int EarlyCycle = INT_MAX;
2870   while (!Worklist.empty()) {
2871     const SDep &Cur = Worklist.pop_back_val();
2872     SUnit *PrevSU = Cur.getSUnit();
2873     if (Visited.count(PrevSU))
2874       continue;
2875     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
2876     if (it == InstrToCycle.end())
2877       continue;
2878     EarlyCycle = std::min(EarlyCycle, it->second);
2879     for (const auto &PI : PrevSU->Preds)
2880       if (PI.getKind() == SDep::Order || PI.getKind() == SDep::Output)
2881         Worklist.push_back(PI);
2882     Visited.insert(PrevSU);
2883   }
2884   return EarlyCycle;
2885 }
2886 
2887 // Return the cycle of the latest scheduled instruction in the chain.
2888 int SMSchedule::latestCycleInChain(const SDep &Dep) {
2889   SmallPtrSet<SUnit *, 8> Visited;
2890   SmallVector<SDep, 8> Worklist;
2891   Worklist.push_back(Dep);
2892   int LateCycle = INT_MIN;
2893   while (!Worklist.empty()) {
2894     const SDep &Cur = Worklist.pop_back_val();
2895     SUnit *SuccSU = Cur.getSUnit();
2896     if (Visited.count(SuccSU) || SuccSU->isBoundaryNode())
2897       continue;
2898     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
2899     if (it == InstrToCycle.end())
2900       continue;
2901     LateCycle = std::max(LateCycle, it->second);
2902     for (const auto &SI : SuccSU->Succs)
2903       if (SI.getKind() == SDep::Order || SI.getKind() == SDep::Output)
2904         Worklist.push_back(SI);
2905     Visited.insert(SuccSU);
2906   }
2907   return LateCycle;
2908 }
2909 
2910 /// If an instruction has a use that spans multiple iterations, then
2911 /// return true. These instructions are characterized by having a back-ege
2912 /// to a Phi, which contains a reference to another Phi.
2913 static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
2914   for (auto &P : SU->Preds)
2915     if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
2916       for (auto &S : P.getSUnit()->Succs)
2917         if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
2918           return P.getSUnit();
2919   return nullptr;
2920 }
2921 
2922 /// Compute the scheduling start slot for the instruction.  The start slot
2923 /// depends on any predecessor or successor nodes scheduled already.
2924 void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
2925                               int II, SwingSchedulerDAG *DAG) {
2926   // Iterate over each instruction that has been scheduled already.  The start
2927   // slot computation depends on whether the previously scheduled instruction
2928   // is a predecessor or successor of the specified instruction.
2929   for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
2930 
2931     // Iterate over each instruction in the current cycle.
2932     for (SUnit *I : getInstructions(cycle)) {
2933       // Because we're processing a DAG for the dependences, we recognize
2934       // the back-edge in recurrences by anti dependences.
2935       for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
2936         const SDep &Dep = SU->Preds[i];
2937         if (Dep.getSUnit() == I) {
2938           if (!DAG->isBackedge(SU, Dep)) {
2939             int EarlyStart = cycle + Dep.getLatency() -
2940                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
2941             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
2942             if (DAG->isLoopCarriedDep(SU, Dep, false)) {
2943               int End = earliestCycleInChain(Dep) + (II - 1);
2944               *MinLateStart = std::min(*MinLateStart, End);
2945             }
2946           } else {
2947             int LateStart = cycle - Dep.getLatency() +
2948                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
2949             *MinLateStart = std::min(*MinLateStart, LateStart);
2950           }
2951         }
2952         // For instruction that requires multiple iterations, make sure that
2953         // the dependent instruction is not scheduled past the definition.
2954         SUnit *BE = multipleIterations(I, DAG);
2955         if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
2956             !SU->isPred(I))
2957           *MinLateStart = std::min(*MinLateStart, cycle);
2958       }
2959       for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
2960         if (SU->Succs[i].getSUnit() == I) {
2961           const SDep &Dep = SU->Succs[i];
2962           if (!DAG->isBackedge(SU, Dep)) {
2963             int LateStart = cycle - Dep.getLatency() +
2964                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
2965             *MinLateStart = std::min(*MinLateStart, LateStart);
2966             if (DAG->isLoopCarriedDep(SU, Dep)) {
2967               int Start = latestCycleInChain(Dep) + 1 - II;
2968               *MaxEarlyStart = std::max(*MaxEarlyStart, Start);
2969             }
2970           } else {
2971             int EarlyStart = cycle + Dep.getLatency() -
2972                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
2973             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
2974           }
2975         }
2976       }
2977     }
2978   }
2979 }
2980 
2981 /// Order the instructions within a cycle so that the definitions occur
2982 /// before the uses. Returns true if the instruction is added to the start
2983 /// of the list, or false if added to the end.
2984 void SMSchedule::orderDependence(const SwingSchedulerDAG *SSD, SUnit *SU,
2985                                  std::deque<SUnit *> &Insts) const {
2986   MachineInstr *MI = SU->getInstr();
2987   bool OrderBeforeUse = false;
2988   bool OrderAfterDef = false;
2989   bool OrderBeforeDef = false;
2990   unsigned MoveDef = 0;
2991   unsigned MoveUse = 0;
2992   int StageInst1 = stageScheduled(SU);
2993 
2994   unsigned Pos = 0;
2995   for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
2996        ++I, ++Pos) {
2997     for (MachineOperand &MO : MI->operands()) {
2998       if (!MO.isReg() || !MO.getReg().isVirtual())
2999         continue;
3000 
3001       Register Reg = MO.getReg();
3002       unsigned BasePos, OffsetPos;
3003       if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
3004         if (MI->getOperand(BasePos).getReg() == Reg)
3005           if (unsigned NewReg = SSD->getInstrBaseReg(SU))
3006             Reg = NewReg;
3007       bool Reads, Writes;
3008       std::tie(Reads, Writes) =
3009           (*I)->getInstr()->readsWritesVirtualRegister(Reg);
3010       if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
3011         OrderBeforeUse = true;
3012         if (MoveUse == 0)
3013           MoveUse = Pos;
3014       } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
3015         // Add the instruction after the scheduled instruction.
3016         OrderAfterDef = true;
3017         MoveDef = Pos;
3018       } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
3019         if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
3020           OrderBeforeUse = true;
3021           if (MoveUse == 0)
3022             MoveUse = Pos;
3023         } else {
3024           OrderAfterDef = true;
3025           MoveDef = Pos;
3026         }
3027       } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
3028         OrderBeforeUse = true;
3029         if (MoveUse == 0)
3030           MoveUse = Pos;
3031         if (MoveUse != 0) {
3032           OrderAfterDef = true;
3033           MoveDef = Pos - 1;
3034         }
3035       } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
3036         // Add the instruction before the scheduled instruction.
3037         OrderBeforeUse = true;
3038         if (MoveUse == 0)
3039           MoveUse = Pos;
3040       } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
3041                  isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
3042         if (MoveUse == 0) {
3043           OrderBeforeDef = true;
3044           MoveUse = Pos;
3045         }
3046       }
3047     }
3048     // Check for order dependences between instructions. Make sure the source
3049     // is ordered before the destination.
3050     for (auto &S : SU->Succs) {
3051       if (S.getSUnit() != *I)
3052         continue;
3053       if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3054         OrderBeforeUse = true;
3055         if (Pos < MoveUse)
3056           MoveUse = Pos;
3057       }
3058       // We did not handle HW dependences in previous for loop,
3059       // and we normally set Latency = 0 for Anti/Output deps,
3060       // so may have nodes in same cycle with Anti/Output dependent on HW regs.
3061       else if ((S.getKind() == SDep::Anti || S.getKind() == SDep::Output) &&
3062                stageScheduled(*I) == StageInst1) {
3063         OrderBeforeUse = true;
3064         if ((MoveUse == 0) || (Pos < MoveUse))
3065           MoveUse = Pos;
3066       }
3067     }
3068     for (auto &P : SU->Preds) {
3069       if (P.getSUnit() != *I)
3070         continue;
3071       if ((P.getKind() == SDep::Order || P.getKind() == SDep::Anti ||
3072            P.getKind() == SDep::Output) &&
3073           stageScheduled(*I) == StageInst1) {
3074         OrderAfterDef = true;
3075         MoveDef = Pos;
3076       }
3077     }
3078   }
3079 
3080   // A circular dependence.
3081   if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
3082     OrderBeforeUse = false;
3083 
3084   // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
3085   // to a loop-carried dependence.
3086   if (OrderBeforeDef)
3087     OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
3088 
3089   // The uncommon case when the instruction order needs to be updated because
3090   // there is both a use and def.
3091   if (OrderBeforeUse && OrderAfterDef) {
3092     SUnit *UseSU = Insts.at(MoveUse);
3093     SUnit *DefSU = Insts.at(MoveDef);
3094     if (MoveUse > MoveDef) {
3095       Insts.erase(Insts.begin() + MoveUse);
3096       Insts.erase(Insts.begin() + MoveDef);
3097     } else {
3098       Insts.erase(Insts.begin() + MoveDef);
3099       Insts.erase(Insts.begin() + MoveUse);
3100     }
3101     orderDependence(SSD, UseSU, Insts);
3102     orderDependence(SSD, SU, Insts);
3103     orderDependence(SSD, DefSU, Insts);
3104     return;
3105   }
3106   // Put the new instruction first if there is a use in the list. Otherwise,
3107   // put it at the end of the list.
3108   if (OrderBeforeUse)
3109     Insts.push_front(SU);
3110   else
3111     Insts.push_back(SU);
3112 }
3113 
3114 /// Return true if the scheduled Phi has a loop carried operand.
3115 bool SMSchedule::isLoopCarried(const SwingSchedulerDAG *SSD,
3116                                MachineInstr &Phi) const {
3117   if (!Phi.isPHI())
3118     return false;
3119   assert(Phi.isPHI() && "Expecting a Phi.");
3120   SUnit *DefSU = SSD->getSUnit(&Phi);
3121   unsigned DefCycle = cycleScheduled(DefSU);
3122   int DefStage = stageScheduled(DefSU);
3123 
3124   unsigned InitVal = 0;
3125   unsigned LoopVal = 0;
3126   getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
3127   SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
3128   if (!UseSU)
3129     return true;
3130   if (UseSU->getInstr()->isPHI())
3131     return true;
3132   unsigned LoopCycle = cycleScheduled(UseSU);
3133   int LoopStage = stageScheduled(UseSU);
3134   return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
3135 }
3136 
3137 /// Return true if the instruction is a definition that is loop carried
3138 /// and defines the use on the next iteration.
3139 ///        v1 = phi(v2, v3)
3140 ///  (Def) v3 = op v1
3141 ///  (MO)   = v1
3142 /// If MO appears before Def, then v1 and v3 may get assigned to the same
3143 /// register.
3144 bool SMSchedule::isLoopCarriedDefOfUse(const SwingSchedulerDAG *SSD,
3145                                        MachineInstr *Def,
3146                                        MachineOperand &MO) const {
3147   if (!MO.isReg())
3148     return false;
3149   if (Def->isPHI())
3150     return false;
3151   MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
3152   if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
3153     return false;
3154   if (!isLoopCarried(SSD, *Phi))
3155     return false;
3156   unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
3157   for (MachineOperand &DMO : Def->all_defs()) {
3158     if (DMO.getReg() == LoopReg)
3159       return true;
3160   }
3161   return false;
3162 }
3163 
3164 /// Return true if all scheduled predecessors are loop-carried output/order
3165 /// dependencies.
3166 bool SMSchedule::onlyHasLoopCarriedOutputOrOrderPreds(
3167     SUnit *SU, SwingSchedulerDAG *DAG) const {
3168   for (const SDep &Pred : SU->Preds)
3169     if (InstrToCycle.count(Pred.getSUnit()) && !DAG->isBackedge(SU, Pred))
3170       return false;
3171   for (const SDep &Succ : SU->Succs)
3172     if (InstrToCycle.count(Succ.getSUnit()) && DAG->isBackedge(SU, Succ))
3173       return false;
3174   return true;
3175 }
3176 
3177 /// Determine transitive dependences of unpipelineable instructions
3178 SmallSet<SUnit *, 8> SMSchedule::computeUnpipelineableNodes(
3179     SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI) {
3180   SmallSet<SUnit *, 8> DoNotPipeline;
3181   SmallVector<SUnit *, 8> Worklist;
3182 
3183   for (auto &SU : SSD->SUnits)
3184     if (SU.isInstr() && PLI->shouldIgnoreForPipelining(SU.getInstr()))
3185       Worklist.push_back(&SU);
3186 
3187   while (!Worklist.empty()) {
3188     auto SU = Worklist.pop_back_val();
3189     if (DoNotPipeline.count(SU))
3190       continue;
3191     LLVM_DEBUG(dbgs() << "Do not pipeline SU(" << SU->NodeNum << ")\n");
3192     DoNotPipeline.insert(SU);
3193     for (auto &Dep : SU->Preds)
3194       Worklist.push_back(Dep.getSUnit());
3195     if (SU->getInstr()->isPHI())
3196       for (auto &Dep : SU->Succs)
3197         if (Dep.getKind() == SDep::Anti)
3198           Worklist.push_back(Dep.getSUnit());
3199   }
3200   return DoNotPipeline;
3201 }
3202 
3203 // Determine all instructions upon which any unpipelineable instruction depends
3204 // and ensure that they are in stage 0.  If unable to do so, return false.
3205 bool SMSchedule::normalizeNonPipelinedInstructions(
3206     SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI) {
3207   SmallSet<SUnit *, 8> DNP = computeUnpipelineableNodes(SSD, PLI);
3208 
3209   int NewLastCycle = INT_MIN;
3210   for (SUnit &SU : SSD->SUnits) {
3211     if (!SU.isInstr())
3212       continue;
3213     if (!DNP.contains(&SU) || stageScheduled(&SU) == 0) {
3214       NewLastCycle = std::max(NewLastCycle, InstrToCycle[&SU]);
3215       continue;
3216     }
3217 
3218     // Put the non-pipelined instruction as early as possible in the schedule
3219     int NewCycle = getFirstCycle();
3220     for (auto &Dep : SU.Preds)
3221       NewCycle = std::max(InstrToCycle[Dep.getSUnit()], NewCycle);
3222 
3223     int OldCycle = InstrToCycle[&SU];
3224     if (OldCycle != NewCycle) {
3225       InstrToCycle[&SU] = NewCycle;
3226       auto &OldS = getInstructions(OldCycle);
3227       llvm::erase(OldS, &SU);
3228       getInstructions(NewCycle).emplace_back(&SU);
3229       LLVM_DEBUG(dbgs() << "SU(" << SU.NodeNum
3230                         << ") is not pipelined; moving from cycle " << OldCycle
3231                         << " to " << NewCycle << " Instr:" << *SU.getInstr());
3232     }
3233     NewLastCycle = std::max(NewLastCycle, NewCycle);
3234   }
3235   LastCycle = NewLastCycle;
3236   return true;
3237 }
3238 
3239 // Check if the generated schedule is valid. This function checks if
3240 // an instruction that uses a physical register is scheduled in a
3241 // different stage than the definition. The pipeliner does not handle
3242 // physical register values that may cross a basic block boundary.
3243 // Furthermore, if a physical def/use pair is assigned to the same
3244 // cycle, orderDependence does not guarantee def/use ordering, so that
3245 // case should be considered invalid.  (The test checks for both
3246 // earlier and same-cycle use to be more robust.)
3247 bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
3248   for (SUnit &SU : SSD->SUnits) {
3249     if (!SU.hasPhysRegDefs)
3250       continue;
3251     int StageDef = stageScheduled(&SU);
3252     int CycleDef = InstrToCycle[&SU];
3253     assert(StageDef != -1 && "Instruction should have been scheduled.");
3254     for (auto &SI : SU.Succs)
3255       if (SI.isAssignedRegDep() && !SI.getSUnit()->isBoundaryNode())
3256         if (Register::isPhysicalRegister(SI.getReg())) {
3257           if (stageScheduled(SI.getSUnit()) != StageDef)
3258             return false;
3259           if (InstrToCycle[SI.getSUnit()] <= CycleDef)
3260             return false;
3261         }
3262   }
3263   return true;
3264 }
3265 
3266 /// A property of the node order in swing-modulo-scheduling is
3267 /// that for nodes outside circuits the following holds:
3268 /// none of them is scheduled after both a successor and a
3269 /// predecessor.
3270 /// The method below checks whether the property is met.
3271 /// If not, debug information is printed and statistics information updated.
3272 /// Note that we do not use an assert statement.
3273 /// The reason is that although an invalid node oder may prevent
3274 /// the pipeliner from finding a pipelined schedule for arbitrary II,
3275 /// it does not lead to the generation of incorrect code.
3276 void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
3277 
3278   // a sorted vector that maps each SUnit to its index in the NodeOrder
3279   typedef std::pair<SUnit *, unsigned> UnitIndex;
3280   std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
3281 
3282   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
3283     Indices.push_back(std::make_pair(NodeOrder[i], i));
3284 
3285   auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
3286     return std::get<0>(i1) < std::get<0>(i2);
3287   };
3288 
3289   // sort, so that we can perform a binary search
3290   llvm::sort(Indices, CompareKey);
3291 
3292   bool Valid = true;
3293   (void)Valid;
3294   // for each SUnit in the NodeOrder, check whether
3295   // it appears after both a successor and a predecessor
3296   // of the SUnit. If this is the case, and the SUnit
3297   // is not part of circuit, then the NodeOrder is not
3298   // valid.
3299   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
3300     SUnit *SU = NodeOrder[i];
3301     unsigned Index = i;
3302 
3303     bool PredBefore = false;
3304     bool SuccBefore = false;
3305 
3306     SUnit *Succ;
3307     SUnit *Pred;
3308     (void)Succ;
3309     (void)Pred;
3310 
3311     for (SDep &PredEdge : SU->Preds) {
3312       SUnit *PredSU = PredEdge.getSUnit();
3313       unsigned PredIndex = std::get<1>(
3314           *llvm::lower_bound(Indices, std::make_pair(PredSU, 0), CompareKey));
3315       if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
3316         PredBefore = true;
3317         Pred = PredSU;
3318         break;
3319       }
3320     }
3321 
3322     for (SDep &SuccEdge : SU->Succs) {
3323       SUnit *SuccSU = SuccEdge.getSUnit();
3324       // Do not process a boundary node, it was not included in NodeOrder,
3325       // hence not in Indices either, call to std::lower_bound() below will
3326       // return Indices.end().
3327       if (SuccSU->isBoundaryNode())
3328         continue;
3329       unsigned SuccIndex = std::get<1>(
3330           *llvm::lower_bound(Indices, std::make_pair(SuccSU, 0), CompareKey));
3331       if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
3332         SuccBefore = true;
3333         Succ = SuccSU;
3334         break;
3335       }
3336     }
3337 
3338     if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
3339       // instructions in circuits are allowed to be scheduled
3340       // after both a successor and predecessor.
3341       bool InCircuit = llvm::any_of(
3342           Circuits, [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
3343       if (InCircuit)
3344         LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
3345       else {
3346         Valid = false;
3347         NumNodeOrderIssues++;
3348         LLVM_DEBUG(dbgs() << "Predecessor ";);
3349       }
3350       LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
3351                         << " are scheduled before node " << SU->NodeNum
3352                         << "\n";);
3353     }
3354   }
3355 
3356   LLVM_DEBUG({
3357     if (!Valid)
3358       dbgs() << "Invalid node order found!\n";
3359   });
3360 }
3361 
3362 /// Attempt to fix the degenerate cases when the instruction serialization
3363 /// causes the register lifetimes to overlap. For example,
3364 ///   p' = store_pi(p, b)
3365 ///      = load p, offset
3366 /// In this case p and p' overlap, which means that two registers are needed.
3367 /// Instead, this function changes the load to use p' and updates the offset.
3368 void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
3369   unsigned OverlapReg = 0;
3370   unsigned NewBaseReg = 0;
3371   for (SUnit *SU : Instrs) {
3372     MachineInstr *MI = SU->getInstr();
3373     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3374       const MachineOperand &MO = MI->getOperand(i);
3375       // Look for an instruction that uses p. The instruction occurs in the
3376       // same cycle but occurs later in the serialized order.
3377       if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
3378         // Check that the instruction appears in the InstrChanges structure,
3379         // which contains instructions that can have the offset updated.
3380         DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3381           InstrChanges.find(SU);
3382         if (It != InstrChanges.end()) {
3383           unsigned BasePos, OffsetPos;
3384           // Update the base register and adjust the offset.
3385           if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
3386             MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3387             NewMI->getOperand(BasePos).setReg(NewBaseReg);
3388             int64_t NewOffset =
3389                 MI->getOperand(OffsetPos).getImm() - It->second.second;
3390             NewMI->getOperand(OffsetPos).setImm(NewOffset);
3391             SU->setInstr(NewMI);
3392             MISUnitMap[NewMI] = SU;
3393             NewMIs[MI] = NewMI;
3394           }
3395         }
3396         OverlapReg = 0;
3397         NewBaseReg = 0;
3398         break;
3399       }
3400       // Look for an instruction of the form p' = op(p), which uses and defines
3401       // two virtual registers that get allocated to the same physical register.
3402       unsigned TiedUseIdx = 0;
3403       if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
3404         // OverlapReg is p in the example above.
3405         OverlapReg = MI->getOperand(TiedUseIdx).getReg();
3406         // NewBaseReg is p' in the example above.
3407         NewBaseReg = MI->getOperand(i).getReg();
3408         break;
3409       }
3410     }
3411   }
3412 }
3413 
3414 std::deque<SUnit *>
3415 SMSchedule::reorderInstructions(const SwingSchedulerDAG *SSD,
3416                                 const std::deque<SUnit *> &Instrs) const {
3417   std::deque<SUnit *> NewOrderPhi;
3418   for (SUnit *SU : Instrs) {
3419     if (SU->getInstr()->isPHI())
3420       NewOrderPhi.push_back(SU);
3421   }
3422   std::deque<SUnit *> NewOrderI;
3423   for (SUnit *SU : Instrs) {
3424     if (!SU->getInstr()->isPHI())
3425       orderDependence(SSD, SU, NewOrderI);
3426   }
3427   llvm::append_range(NewOrderPhi, NewOrderI);
3428   return NewOrderPhi;
3429 }
3430 
3431 /// After the schedule has been formed, call this function to combine
3432 /// the instructions from the different stages/cycles.  That is, this
3433 /// function creates a schedule that represents a single iteration.
3434 void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
3435   // Move all instructions to the first stage from later stages.
3436   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3437     for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
3438          ++stage) {
3439       std::deque<SUnit *> &cycleInstrs =
3440           ScheduledInstrs[cycle + (stage * InitiationInterval)];
3441       for (SUnit *SU : llvm::reverse(cycleInstrs))
3442         ScheduledInstrs[cycle].push_front(SU);
3443     }
3444   }
3445 
3446   // Erase all the elements in the later stages. Only one iteration should
3447   // remain in the scheduled list, and it contains all the instructions.
3448   for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
3449     ScheduledInstrs.erase(cycle);
3450 
3451   // Change the registers in instruction as specified in the InstrChanges
3452   // map. We need to use the new registers to create the correct order.
3453   for (const SUnit &SU : SSD->SUnits)
3454     SSD->applyInstrChange(SU.getInstr(), *this);
3455 
3456   // Reorder the instructions in each cycle to fix and improve the
3457   // generated code.
3458   for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
3459     std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
3460     cycleInstrs = reorderInstructions(SSD, cycleInstrs);
3461     SSD->fixupRegisterOverlaps(cycleInstrs);
3462   }
3463 
3464   LLVM_DEBUG(dump(););
3465 }
3466 
3467 void NodeSet::print(raw_ostream &os) const {
3468   os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
3469      << " depth " << MaxDepth << " col " << Colocate << "\n";
3470   for (const auto &I : Nodes)
3471     os << "   SU(" << I->NodeNum << ") " << *(I->getInstr());
3472   os << "\n";
3473 }
3474 
3475 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3476 /// Print the schedule information to the given output.
3477 void SMSchedule::print(raw_ostream &os) const {
3478   // Iterate over each cycle.
3479   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3480     // Iterate over each instruction in the cycle.
3481     const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
3482     for (SUnit *CI : cycleInstrs->second) {
3483       os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
3484       os << "(" << CI->NodeNum << ") ";
3485       CI->getInstr()->print(os);
3486       os << "\n";
3487     }
3488   }
3489 }
3490 
3491 /// Utility function used for debugging to print the schedule.
3492 LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
3493 LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
3494 
3495 void ResourceManager::dumpMRT() const {
3496   LLVM_DEBUG({
3497     if (UseDFA)
3498       return;
3499     std::stringstream SS;
3500     SS << "MRT:\n";
3501     SS << std::setw(4) << "Slot";
3502     for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I)
3503       SS << std::setw(3) << I;
3504     SS << std::setw(7) << "#Mops"
3505        << "\n";
3506     for (int Slot = 0; Slot < InitiationInterval; ++Slot) {
3507       SS << std::setw(4) << Slot;
3508       for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I)
3509         SS << std::setw(3) << MRT[Slot][I];
3510       SS << std::setw(7) << NumScheduledMops[Slot] << "\n";
3511     }
3512     dbgs() << SS.str();
3513   });
3514 }
3515 #endif
3516 
3517 void ResourceManager::initProcResourceVectors(
3518     const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
3519   unsigned ProcResourceID = 0;
3520 
3521   // We currently limit the resource kinds to 64 and below so that we can use
3522   // uint64_t for Masks
3523   assert(SM.getNumProcResourceKinds() < 64 &&
3524          "Too many kinds of resources, unsupported");
3525   // Create a unique bitmask for every processor resource unit.
3526   // Skip resource at index 0, since it always references 'InvalidUnit'.
3527   Masks.resize(SM.getNumProcResourceKinds());
3528   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3529     const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3530     if (Desc.SubUnitsIdxBegin)
3531       continue;
3532     Masks[I] = 1ULL << ProcResourceID;
3533     ProcResourceID++;
3534   }
3535   // Create a unique bitmask for every processor resource group.
3536   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3537     const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3538     if (!Desc.SubUnitsIdxBegin)
3539       continue;
3540     Masks[I] = 1ULL << ProcResourceID;
3541     for (unsigned U = 0; U < Desc.NumUnits; ++U)
3542       Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
3543     ProcResourceID++;
3544   }
3545   LLVM_DEBUG({
3546     if (SwpShowResMask) {
3547       dbgs() << "ProcResourceDesc:\n";
3548       for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3549         const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
3550         dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
3551                          ProcResource->Name, I, Masks[I],
3552                          ProcResource->NumUnits);
3553       }
3554       dbgs() << " -----------------\n";
3555     }
3556   });
3557 }
3558 
3559 bool ResourceManager::canReserveResources(SUnit &SU, int Cycle) {
3560   LLVM_DEBUG({
3561     if (SwpDebugResource)
3562       dbgs() << "canReserveResources:\n";
3563   });
3564   if (UseDFA)
3565     return DFAResources[positiveModulo(Cycle, InitiationInterval)]
3566         ->canReserveResources(&SU.getInstr()->getDesc());
3567 
3568   const MCSchedClassDesc *SCDesc = DAG->getSchedClass(&SU);
3569   if (!SCDesc->isValid()) {
3570     LLVM_DEBUG({
3571       dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3572       dbgs() << "isPseudo:" << SU.getInstr()->isPseudo() << "\n";
3573     });
3574     return true;
3575   }
3576 
3577   reserveResources(SCDesc, Cycle);
3578   bool Result = !isOverbooked();
3579   unreserveResources(SCDesc, Cycle);
3580 
3581   LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return " << Result << "\n\n";);
3582   return Result;
3583 }
3584 
3585 void ResourceManager::reserveResources(SUnit &SU, int Cycle) {
3586   LLVM_DEBUG({
3587     if (SwpDebugResource)
3588       dbgs() << "reserveResources:\n";
3589   });
3590   if (UseDFA)
3591     return DFAResources[positiveModulo(Cycle, InitiationInterval)]
3592         ->reserveResources(&SU.getInstr()->getDesc());
3593 
3594   const MCSchedClassDesc *SCDesc = DAG->getSchedClass(&SU);
3595   if (!SCDesc->isValid()) {
3596     LLVM_DEBUG({
3597       dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3598       dbgs() << "isPseudo:" << SU.getInstr()->isPseudo() << "\n";
3599     });
3600     return;
3601   }
3602 
3603   reserveResources(SCDesc, Cycle);
3604 
3605   LLVM_DEBUG({
3606     if (SwpDebugResource) {
3607       dumpMRT();
3608       dbgs() << "reserveResources: done!\n\n";
3609     }
3610   });
3611 }
3612 
3613 void ResourceManager::reserveResources(const MCSchedClassDesc *SCDesc,
3614                                        int Cycle) {
3615   assert(!UseDFA);
3616   for (const MCWriteProcResEntry &PRE : make_range(
3617            STI->getWriteProcResBegin(SCDesc), STI->getWriteProcResEnd(SCDesc)))
3618     for (int C = Cycle; C < Cycle + PRE.ReleaseAtCycle; ++C)
3619       ++MRT[positiveModulo(C, InitiationInterval)][PRE.ProcResourceIdx];
3620 
3621   for (int C = Cycle; C < Cycle + SCDesc->NumMicroOps; ++C)
3622     ++NumScheduledMops[positiveModulo(C, InitiationInterval)];
3623 }
3624 
3625 void ResourceManager::unreserveResources(const MCSchedClassDesc *SCDesc,
3626                                          int Cycle) {
3627   assert(!UseDFA);
3628   for (const MCWriteProcResEntry &PRE : make_range(
3629            STI->getWriteProcResBegin(SCDesc), STI->getWriteProcResEnd(SCDesc)))
3630     for (int C = Cycle; C < Cycle + PRE.ReleaseAtCycle; ++C)
3631       --MRT[positiveModulo(C, InitiationInterval)][PRE.ProcResourceIdx];
3632 
3633   for (int C = Cycle; C < Cycle + SCDesc->NumMicroOps; ++C)
3634     --NumScheduledMops[positiveModulo(C, InitiationInterval)];
3635 }
3636 
3637 bool ResourceManager::isOverbooked() const {
3638   assert(!UseDFA);
3639   for (int Slot = 0; Slot < InitiationInterval; ++Slot) {
3640     for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3641       const MCProcResourceDesc *Desc = SM.getProcResource(I);
3642       if (MRT[Slot][I] > Desc->NumUnits)
3643         return true;
3644     }
3645     if (NumScheduledMops[Slot] > IssueWidth)
3646       return true;
3647   }
3648   return false;
3649 }
3650 
3651 int ResourceManager::calculateResMIIDFA() const {
3652   assert(UseDFA);
3653 
3654   // Sort the instructions by the number of available choices for scheduling,
3655   // least to most. Use the number of critical resources as the tie breaker.
3656   FuncUnitSorter FUS = FuncUnitSorter(*ST);
3657   for (SUnit &SU : DAG->SUnits)
3658     FUS.calcCriticalResources(*SU.getInstr());
3659   PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
3660       FuncUnitOrder(FUS);
3661 
3662   for (SUnit &SU : DAG->SUnits)
3663     FuncUnitOrder.push(SU.getInstr());
3664 
3665   SmallVector<std::unique_ptr<DFAPacketizer>, 8> Resources;
3666   Resources.push_back(
3667       std::unique_ptr<DFAPacketizer>(TII->CreateTargetScheduleState(*ST)));
3668 
3669   while (!FuncUnitOrder.empty()) {
3670     MachineInstr *MI = FuncUnitOrder.top();
3671     FuncUnitOrder.pop();
3672     if (TII->isZeroCost(MI->getOpcode()))
3673       continue;
3674 
3675     // Attempt to reserve the instruction in an existing DFA. At least one
3676     // DFA is needed for each cycle.
3677     unsigned NumCycles = DAG->getSUnit(MI)->Latency;
3678     unsigned ReservedCycles = 0;
3679     auto *RI = Resources.begin();
3680     auto *RE = Resources.end();
3681     LLVM_DEBUG({
3682       dbgs() << "Trying to reserve resource for " << NumCycles
3683              << " cycles for \n";
3684       MI->dump();
3685     });
3686     for (unsigned C = 0; C < NumCycles; ++C)
3687       while (RI != RE) {
3688         if ((*RI)->canReserveResources(*MI)) {
3689           (*RI)->reserveResources(*MI);
3690           ++ReservedCycles;
3691           break;
3692         }
3693         RI++;
3694       }
3695     LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
3696                       << ", NumCycles:" << NumCycles << "\n");
3697     // Add new DFAs, if needed, to reserve resources.
3698     for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
3699       LLVM_DEBUG(if (SwpDebugResource) dbgs()
3700                  << "NewResource created to reserve resources"
3701                  << "\n");
3702       auto *NewResource = TII->CreateTargetScheduleState(*ST);
3703       assert(NewResource->canReserveResources(*MI) && "Reserve error.");
3704       NewResource->reserveResources(*MI);
3705       Resources.push_back(std::unique_ptr<DFAPacketizer>(NewResource));
3706     }
3707   }
3708 
3709   int Resmii = Resources.size();
3710   LLVM_DEBUG(dbgs() << "Return Res MII:" << Resmii << "\n");
3711   return Resmii;
3712 }
3713 
3714 int ResourceManager::calculateResMII() const {
3715   if (UseDFA)
3716     return calculateResMIIDFA();
3717 
3718   // Count each resource consumption and divide it by the number of units.
3719   // ResMII is the max value among them.
3720 
3721   int NumMops = 0;
3722   SmallVector<uint64_t> ResourceCount(SM.getNumProcResourceKinds());
3723   for (SUnit &SU : DAG->SUnits) {
3724     if (TII->isZeroCost(SU.getInstr()->getOpcode()))
3725       continue;
3726 
3727     const MCSchedClassDesc *SCDesc = DAG->getSchedClass(&SU);
3728     if (!SCDesc->isValid())
3729       continue;
3730 
3731     LLVM_DEBUG({
3732       if (SwpDebugResource) {
3733         DAG->dumpNode(SU);
3734         dbgs() << "  #Mops: " << SCDesc->NumMicroOps << "\n"
3735                << "  WriteProcRes: ";
3736       }
3737     });
3738     NumMops += SCDesc->NumMicroOps;
3739     for (const MCWriteProcResEntry &PRE :
3740          make_range(STI->getWriteProcResBegin(SCDesc),
3741                     STI->getWriteProcResEnd(SCDesc))) {
3742       LLVM_DEBUG({
3743         if (SwpDebugResource) {
3744           const MCProcResourceDesc *Desc =
3745               SM.getProcResource(PRE.ProcResourceIdx);
3746           dbgs() << Desc->Name << ": " << PRE.ReleaseAtCycle << ", ";
3747         }
3748       });
3749       ResourceCount[PRE.ProcResourceIdx] += PRE.ReleaseAtCycle;
3750     }
3751     LLVM_DEBUG(if (SwpDebugResource) dbgs() << "\n");
3752   }
3753 
3754   int Result = (NumMops + IssueWidth - 1) / IssueWidth;
3755   LLVM_DEBUG({
3756     if (SwpDebugResource)
3757       dbgs() << "#Mops: " << NumMops << ", "
3758              << "IssueWidth: " << IssueWidth << ", "
3759              << "Cycles: " << Result << "\n";
3760   });
3761 
3762   LLVM_DEBUG({
3763     if (SwpDebugResource) {
3764       std::stringstream SS;
3765       SS << std::setw(2) << "ID" << std::setw(16) << "Name" << std::setw(10)
3766          << "Units" << std::setw(10) << "Consumed" << std::setw(10) << "Cycles"
3767          << "\n";
3768       dbgs() << SS.str();
3769     }
3770   });
3771   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3772     const MCProcResourceDesc *Desc = SM.getProcResource(I);
3773     int Cycles = (ResourceCount[I] + Desc->NumUnits - 1) / Desc->NumUnits;
3774     LLVM_DEBUG({
3775       if (SwpDebugResource) {
3776         std::stringstream SS;
3777         SS << std::setw(2) << I << std::setw(16) << Desc->Name << std::setw(10)
3778            << Desc->NumUnits << std::setw(10) << ResourceCount[I]
3779            << std::setw(10) << Cycles << "\n";
3780         dbgs() << SS.str();
3781       }
3782     });
3783     if (Cycles > Result)
3784       Result = Cycles;
3785   }
3786   return Result;
3787 }
3788 
3789 void ResourceManager::init(int II) {
3790   InitiationInterval = II;
3791   DFAResources.clear();
3792   DFAResources.resize(II);
3793   for (auto &I : DFAResources)
3794     I.reset(ST->getInstrInfo()->CreateTargetScheduleState(*ST));
3795   MRT.clear();
3796   MRT.resize(II, SmallVector<uint64_t>(SM.getNumProcResourceKinds()));
3797   NumScheduledMops.clear();
3798   NumScheduledMops.resize(II);
3799 }
3800