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