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