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     FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
1584   for (auto &PI : Cur->Preds)
1585     if (PI.getKind() == SDep::Anti)
1586       FoundPath |=
1587           computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
1588   if (FoundPath)
1589     Path.insert(Cur);
1590   return FoundPath;
1591 }
1592 
1593 /// Compute the live-out registers for the instructions in a node-set.
1594 /// The live-out registers are those that are defined in the node-set,
1595 /// but not used. Except for use operands of Phis.
1596 static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
1597                             NodeSet &NS) {
1598   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1599   MachineRegisterInfo &MRI = MF.getRegInfo();
1600   SmallVector<RegisterMaskPair, 8> LiveOutRegs;
1601   SmallSet<unsigned, 4> Uses;
1602   for (SUnit *SU : NS) {
1603     const MachineInstr *MI = SU->getInstr();
1604     if (MI->isPHI())
1605       continue;
1606     for (const MachineOperand &MO : MI->operands())
1607       if (MO.isReg() && MO.isUse()) {
1608         Register Reg = MO.getReg();
1609         if (Register::isVirtualRegister(Reg))
1610           Uses.insert(Reg);
1611         else if (MRI.isAllocatable(Reg))
1612           for (MCRegUnitIterator Units(Reg.asMCReg(), TRI); Units.isValid();
1613                ++Units)
1614             Uses.insert(*Units);
1615       }
1616   }
1617   for (SUnit *SU : NS)
1618     for (const MachineOperand &MO : SU->getInstr()->operands())
1619       if (MO.isReg() && MO.isDef() && !MO.isDead()) {
1620         Register Reg = MO.getReg();
1621         if (Register::isVirtualRegister(Reg)) {
1622           if (!Uses.count(Reg))
1623             LiveOutRegs.push_back(RegisterMaskPair(Reg,
1624                                                    LaneBitmask::getNone()));
1625         } else if (MRI.isAllocatable(Reg)) {
1626           for (MCRegUnitIterator Units(Reg.asMCReg(), TRI); Units.isValid();
1627                ++Units)
1628             if (!Uses.count(*Units))
1629               LiveOutRegs.push_back(RegisterMaskPair(*Units,
1630                                                      LaneBitmask::getNone()));
1631         }
1632       }
1633   RPTracker.addLiveRegs(LiveOutRegs);
1634 }
1635 
1636 /// A heuristic to filter nodes in recurrent node-sets if the register
1637 /// pressure of a set is too high.
1638 void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
1639   for (auto &NS : NodeSets) {
1640     // Skip small node-sets since they won't cause register pressure problems.
1641     if (NS.size() <= 2)
1642       continue;
1643     IntervalPressure RecRegPressure;
1644     RegPressureTracker RecRPTracker(RecRegPressure);
1645     RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
1646     computeLiveOuts(MF, RecRPTracker, NS);
1647     RecRPTracker.closeBottom();
1648 
1649     std::vector<SUnit *> SUnits(NS.begin(), NS.end());
1650     llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
1651       return A->NodeNum > B->NodeNum;
1652     });
1653 
1654     for (auto &SU : SUnits) {
1655       // Since we're computing the register pressure for a subset of the
1656       // instructions in a block, we need to set the tracker for each
1657       // instruction in the node-set. The tracker is set to the instruction
1658       // just after the one we're interested in.
1659       MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
1660       RecRPTracker.setPos(std::next(CurInstI));
1661 
1662       RegPressureDelta RPDelta;
1663       ArrayRef<PressureChange> CriticalPSets;
1664       RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
1665                                              CriticalPSets,
1666                                              RecRegPressure.MaxSetPressure);
1667       if (RPDelta.Excess.isValid()) {
1668         LLVM_DEBUG(
1669             dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
1670                    << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
1671                    << ":" << RPDelta.Excess.getUnitInc());
1672         NS.setExceedPressure(SU);
1673         break;
1674       }
1675       RecRPTracker.recede();
1676     }
1677   }
1678 }
1679 
1680 /// A heuristic to colocate node sets that have the same set of
1681 /// successors.
1682 void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
1683   unsigned Colocate = 0;
1684   for (int i = 0, e = NodeSets.size(); i < e; ++i) {
1685     NodeSet &N1 = NodeSets[i];
1686     SmallSetVector<SUnit *, 8> S1;
1687     if (N1.empty() || !succ_L(N1, S1))
1688       continue;
1689     for (int j = i + 1; j < e; ++j) {
1690       NodeSet &N2 = NodeSets[j];
1691       if (N1.compareRecMII(N2) != 0)
1692         continue;
1693       SmallSetVector<SUnit *, 8> S2;
1694       if (N2.empty() || !succ_L(N2, S2))
1695         continue;
1696       if (llvm::set_is_subset(S1, S2) && S1.size() == S2.size()) {
1697         N1.setColocate(++Colocate);
1698         N2.setColocate(Colocate);
1699         break;
1700       }
1701     }
1702   }
1703 }
1704 
1705 /// Check if the existing node-sets are profitable. If not, then ignore the
1706 /// recurrent node-sets, and attempt to schedule all nodes together. This is
1707 /// a heuristic. If the MII is large and all the recurrent node-sets are small,
1708 /// then it's best to try to schedule all instructions together instead of
1709 /// starting with the recurrent node-sets.
1710 void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
1711   // Look for loops with a large MII.
1712   if (MII < 17)
1713     return;
1714   // Check if the node-set contains only a simple add recurrence.
1715   for (auto &NS : NodeSets) {
1716     if (NS.getRecMII() > 2)
1717       return;
1718     if (NS.getMaxDepth() > MII)
1719       return;
1720   }
1721   NodeSets.clear();
1722   LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
1723 }
1724 
1725 /// Add the nodes that do not belong to a recurrence set into groups
1726 /// based upon connected components.
1727 void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
1728   SetVector<SUnit *> NodesAdded;
1729   SmallPtrSet<SUnit *, 8> Visited;
1730   // Add the nodes that are on a path between the previous node sets and
1731   // the current node set.
1732   for (NodeSet &I : NodeSets) {
1733     SmallSetVector<SUnit *, 8> N;
1734     // Add the nodes from the current node set to the previous node set.
1735     if (succ_L(I, N)) {
1736       SetVector<SUnit *> Path;
1737       for (SUnit *NI : N) {
1738         Visited.clear();
1739         computePath(NI, Path, NodesAdded, I, Visited);
1740       }
1741       if (!Path.empty())
1742         I.insert(Path.begin(), Path.end());
1743     }
1744     // Add the nodes from the previous node set to the current node set.
1745     N.clear();
1746     if (succ_L(NodesAdded, N)) {
1747       SetVector<SUnit *> Path;
1748       for (SUnit *NI : N) {
1749         Visited.clear();
1750         computePath(NI, Path, I, NodesAdded, Visited);
1751       }
1752       if (!Path.empty())
1753         I.insert(Path.begin(), Path.end());
1754     }
1755     NodesAdded.insert(I.begin(), I.end());
1756   }
1757 
1758   // Create a new node set with the connected nodes of any successor of a node
1759   // in a recurrent set.
1760   NodeSet NewSet;
1761   SmallSetVector<SUnit *, 8> N;
1762   if (succ_L(NodesAdded, N))
1763     for (SUnit *I : N)
1764       addConnectedNodes(I, NewSet, NodesAdded);
1765   if (!NewSet.empty())
1766     NodeSets.push_back(NewSet);
1767 
1768   // Create a new node set with the connected nodes of any predecessor of a node
1769   // in a recurrent set.
1770   NewSet.clear();
1771   if (pred_L(NodesAdded, N))
1772     for (SUnit *I : N)
1773       addConnectedNodes(I, NewSet, NodesAdded);
1774   if (!NewSet.empty())
1775     NodeSets.push_back(NewSet);
1776 
1777   // Create new nodes sets with the connected nodes any remaining node that
1778   // has no predecessor.
1779   for (SUnit &SU : SUnits) {
1780     if (NodesAdded.count(&SU) == 0) {
1781       NewSet.clear();
1782       addConnectedNodes(&SU, NewSet, NodesAdded);
1783       if (!NewSet.empty())
1784         NodeSets.push_back(NewSet);
1785     }
1786   }
1787 }
1788 
1789 /// Add the node to the set, and add all of its connected nodes to the set.
1790 void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
1791                                           SetVector<SUnit *> &NodesAdded) {
1792   NewSet.insert(SU);
1793   NodesAdded.insert(SU);
1794   for (auto &SI : SU->Succs) {
1795     SUnit *Successor = SI.getSUnit();
1796     if (!SI.isArtificial() && !Successor->isBoundaryNode() &&
1797         NodesAdded.count(Successor) == 0)
1798       addConnectedNodes(Successor, NewSet, NodesAdded);
1799   }
1800   for (auto &PI : SU->Preds) {
1801     SUnit *Predecessor = PI.getSUnit();
1802     if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
1803       addConnectedNodes(Predecessor, NewSet, NodesAdded);
1804   }
1805 }
1806 
1807 /// Return true if Set1 contains elements in Set2. The elements in common
1808 /// are returned in a different container.
1809 static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
1810                         SmallSetVector<SUnit *, 8> &Result) {
1811   Result.clear();
1812   for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
1813     SUnit *SU = Set1[i];
1814     if (Set2.count(SU) != 0)
1815       Result.insert(SU);
1816   }
1817   return !Result.empty();
1818 }
1819 
1820 /// Merge the recurrence node sets that have the same initial node.
1821 void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
1822   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1823        ++I) {
1824     NodeSet &NI = *I;
1825     for (NodeSetType::iterator J = I + 1; J != E;) {
1826       NodeSet &NJ = *J;
1827       if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
1828         if (NJ.compareRecMII(NI) > 0)
1829           NI.setRecMII(NJ.getRecMII());
1830         for (SUnit *SU : *J)
1831           I->insert(SU);
1832         NodeSets.erase(J);
1833         E = NodeSets.end();
1834       } else {
1835         ++J;
1836       }
1837     }
1838   }
1839 }
1840 
1841 /// Remove nodes that have been scheduled in previous NodeSets.
1842 void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
1843   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1844        ++I)
1845     for (NodeSetType::iterator J = I + 1; J != E;) {
1846       J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
1847 
1848       if (J->empty()) {
1849         NodeSets.erase(J);
1850         E = NodeSets.end();
1851       } else {
1852         ++J;
1853       }
1854     }
1855 }
1856 
1857 /// Compute an ordered list of the dependence graph nodes, which
1858 /// indicates the order that the nodes will be scheduled.  This is a
1859 /// two-level algorithm. First, a partial order is created, which
1860 /// consists of a list of sets ordered from highest to lowest priority.
1861 void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
1862   SmallSetVector<SUnit *, 8> R;
1863   NodeOrder.clear();
1864 
1865   for (auto &Nodes : NodeSets) {
1866     LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
1867     OrderKind Order;
1868     SmallSetVector<SUnit *, 8> N;
1869     if (pred_L(NodeOrder, N) && llvm::set_is_subset(N, Nodes)) {
1870       R.insert(N.begin(), N.end());
1871       Order = BottomUp;
1872       LLVM_DEBUG(dbgs() << "  Bottom up (preds) ");
1873     } else if (succ_L(NodeOrder, N) && llvm::set_is_subset(N, Nodes)) {
1874       R.insert(N.begin(), N.end());
1875       Order = TopDown;
1876       LLVM_DEBUG(dbgs() << "  Top down (succs) ");
1877     } else if (isIntersect(N, Nodes, R)) {
1878       // If some of the successors are in the existing node-set, then use the
1879       // top-down ordering.
1880       Order = TopDown;
1881       LLVM_DEBUG(dbgs() << "  Top down (intersect) ");
1882     } else if (NodeSets.size() == 1) {
1883       for (auto &N : Nodes)
1884         if (N->Succs.size() == 0)
1885           R.insert(N);
1886       Order = BottomUp;
1887       LLVM_DEBUG(dbgs() << "  Bottom up (all) ");
1888     } else {
1889       // Find the node with the highest ASAP.
1890       SUnit *maxASAP = nullptr;
1891       for (SUnit *SU : Nodes) {
1892         if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
1893             (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
1894           maxASAP = SU;
1895       }
1896       R.insert(maxASAP);
1897       Order = BottomUp;
1898       LLVM_DEBUG(dbgs() << "  Bottom up (default) ");
1899     }
1900 
1901     while (!R.empty()) {
1902       if (Order == TopDown) {
1903         // Choose the node with the maximum height.  If more than one, choose
1904         // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
1905         // choose the node with the lowest MOV.
1906         while (!R.empty()) {
1907           SUnit *maxHeight = nullptr;
1908           for (SUnit *I : R) {
1909             if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
1910               maxHeight = I;
1911             else if (getHeight(I) == getHeight(maxHeight) &&
1912                      getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
1913               maxHeight = I;
1914             else if (getHeight(I) == getHeight(maxHeight) &&
1915                      getZeroLatencyHeight(I) ==
1916                          getZeroLatencyHeight(maxHeight) &&
1917                      getMOV(I) < getMOV(maxHeight))
1918               maxHeight = I;
1919           }
1920           NodeOrder.insert(maxHeight);
1921           LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
1922           R.remove(maxHeight);
1923           for (const auto &I : maxHeight->Succs) {
1924             if (Nodes.count(I.getSUnit()) == 0)
1925               continue;
1926             if (NodeOrder.contains(I.getSUnit()))
1927               continue;
1928             if (ignoreDependence(I, false))
1929               continue;
1930             R.insert(I.getSUnit());
1931           }
1932           // Back-edges are predecessors with an anti-dependence.
1933           for (const auto &I : maxHeight->Preds) {
1934             if (I.getKind() != SDep::Anti)
1935               continue;
1936             if (Nodes.count(I.getSUnit()) == 0)
1937               continue;
1938             if (NodeOrder.contains(I.getSUnit()))
1939               continue;
1940             R.insert(I.getSUnit());
1941           }
1942         }
1943         Order = BottomUp;
1944         LLVM_DEBUG(dbgs() << "\n   Switching order to bottom up ");
1945         SmallSetVector<SUnit *, 8> N;
1946         if (pred_L(NodeOrder, N, &Nodes))
1947           R.insert(N.begin(), N.end());
1948       } else {
1949         // Choose the node with the maximum depth.  If more than one, choose
1950         // the node with the maximum ZeroLatencyDepth. If still more than one,
1951         // choose the node with the lowest MOV.
1952         while (!R.empty()) {
1953           SUnit *maxDepth = nullptr;
1954           for (SUnit *I : R) {
1955             if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
1956               maxDepth = I;
1957             else if (getDepth(I) == getDepth(maxDepth) &&
1958                      getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
1959               maxDepth = I;
1960             else if (getDepth(I) == getDepth(maxDepth) &&
1961                      getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
1962                      getMOV(I) < getMOV(maxDepth))
1963               maxDepth = I;
1964           }
1965           NodeOrder.insert(maxDepth);
1966           LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
1967           R.remove(maxDepth);
1968           if (Nodes.isExceedSU(maxDepth)) {
1969             Order = TopDown;
1970             R.clear();
1971             R.insert(Nodes.getNode(0));
1972             break;
1973           }
1974           for (const auto &I : maxDepth->Preds) {
1975             if (Nodes.count(I.getSUnit()) == 0)
1976               continue;
1977             if (NodeOrder.contains(I.getSUnit()))
1978               continue;
1979             R.insert(I.getSUnit());
1980           }
1981           // Back-edges are predecessors with an anti-dependence.
1982           for (const auto &I : maxDepth->Succs) {
1983             if (I.getKind() != SDep::Anti)
1984               continue;
1985             if (Nodes.count(I.getSUnit()) == 0)
1986               continue;
1987             if (NodeOrder.contains(I.getSUnit()))
1988               continue;
1989             R.insert(I.getSUnit());
1990           }
1991         }
1992         Order = TopDown;
1993         LLVM_DEBUG(dbgs() << "\n   Switching order to top down ");
1994         SmallSetVector<SUnit *, 8> N;
1995         if (succ_L(NodeOrder, N, &Nodes))
1996           R.insert(N.begin(), N.end());
1997       }
1998     }
1999     LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
2000   }
2001 
2002   LLVM_DEBUG({
2003     dbgs() << "Node order: ";
2004     for (SUnit *I : NodeOrder)
2005       dbgs() << " " << I->NodeNum << " ";
2006     dbgs() << "\n";
2007   });
2008 }
2009 
2010 /// Process the nodes in the computed order and create the pipelined schedule
2011 /// of the instructions, if possible. Return true if a schedule is found.
2012 bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
2013 
2014   if (NodeOrder.empty()){
2015     LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
2016     return false;
2017   }
2018 
2019   bool scheduleFound = false;
2020   // Keep increasing II until a valid schedule is found.
2021   for (unsigned II = MII; II <= MAX_II && !scheduleFound; ++II) {
2022     Schedule.reset();
2023     Schedule.setInitiationInterval(II);
2024     LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
2025 
2026     SetVector<SUnit *>::iterator NI = NodeOrder.begin();
2027     SetVector<SUnit *>::iterator NE = NodeOrder.end();
2028     do {
2029       SUnit *SU = *NI;
2030 
2031       // Compute the schedule time for the instruction, which is based
2032       // upon the scheduled time for any predecessors/successors.
2033       int EarlyStart = INT_MIN;
2034       int LateStart = INT_MAX;
2035       // These values are set when the size of the schedule window is limited
2036       // due to chain dependences.
2037       int SchedEnd = INT_MAX;
2038       int SchedStart = INT_MIN;
2039       Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
2040                             II, this);
2041       LLVM_DEBUG({
2042         dbgs() << "\n";
2043         dbgs() << "Inst (" << SU->NodeNum << ") ";
2044         SU->getInstr()->dump();
2045         dbgs() << "\n";
2046       });
2047       LLVM_DEBUG({
2048         dbgs() << format("\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart,
2049                          LateStart, SchedEnd, SchedStart);
2050       });
2051 
2052       if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
2053           SchedStart > LateStart)
2054         scheduleFound = false;
2055       else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
2056         SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
2057         scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
2058       } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
2059         SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
2060         scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
2061       } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
2062         SchedEnd =
2063             std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
2064         // When scheduling a Phi it is better to start at the late cycle and go
2065         // backwards. The default order may insert the Phi too far away from
2066         // its first dependence.
2067         if (SU->getInstr()->isPHI())
2068           scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
2069         else
2070           scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
2071       } else {
2072         int FirstCycle = Schedule.getFirstCycle();
2073         scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
2074                                         FirstCycle + getASAP(SU) + II - 1, II);
2075       }
2076       // Even if we find a schedule, make sure the schedule doesn't exceed the
2077       // allowable number of stages. We keep trying if this happens.
2078       if (scheduleFound)
2079         if (SwpMaxStages > -1 &&
2080             Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
2081           scheduleFound = false;
2082 
2083       LLVM_DEBUG({
2084         if (!scheduleFound)
2085           dbgs() << "\tCan't schedule\n";
2086       });
2087     } while (++NI != NE && scheduleFound);
2088 
2089     // If a schedule is found, ensure non-pipelined instructions are in stage 0
2090     if (scheduleFound)
2091       scheduleFound =
2092           Schedule.normalizeNonPipelinedInstructions(this, LoopPipelinerInfo);
2093 
2094     // If a schedule is found, check if it is a valid schedule too.
2095     if (scheduleFound)
2096       scheduleFound = Schedule.isValidSchedule(this);
2097   }
2098 
2099   LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound
2100                     << " (II=" << Schedule.getInitiationInterval()
2101                     << ")\n");
2102 
2103   if (scheduleFound) {
2104     Schedule.finalizeSchedule(this);
2105     Pass.ORE->emit([&]() {
2106       return MachineOptimizationRemarkAnalysis(
2107                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
2108              << "Schedule found with Initiation Interval: "
2109              << ore::NV("II", Schedule.getInitiationInterval())
2110              << ", MaxStageCount: "
2111              << ore::NV("MaxStageCount", Schedule.getMaxStageCount());
2112     });
2113   } else
2114     Schedule.reset();
2115 
2116   return scheduleFound && Schedule.getMaxStageCount() > 0;
2117 }
2118 
2119 /// Return true if we can compute the amount the instruction changes
2120 /// during each iteration. Set Delta to the amount of the change.
2121 bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
2122   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2123   const MachineOperand *BaseOp;
2124   int64_t Offset;
2125   bool OffsetIsScalable;
2126   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
2127     return false;
2128 
2129   // FIXME: This algorithm assumes instructions have fixed-size offsets.
2130   if (OffsetIsScalable)
2131     return false;
2132 
2133   if (!BaseOp->isReg())
2134     return false;
2135 
2136   Register BaseReg = BaseOp->getReg();
2137 
2138   MachineRegisterInfo &MRI = MF.getRegInfo();
2139   // Check if there is a Phi. If so, get the definition in the loop.
2140   MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
2141   if (BaseDef && BaseDef->isPHI()) {
2142     BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
2143     BaseDef = MRI.getVRegDef(BaseReg);
2144   }
2145   if (!BaseDef)
2146     return false;
2147 
2148   int D = 0;
2149   if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
2150     return false;
2151 
2152   Delta = D;
2153   return true;
2154 }
2155 
2156 /// Check if we can change the instruction to use an offset value from the
2157 /// previous iteration. If so, return true and set the base and offset values
2158 /// so that we can rewrite the load, if necessary.
2159 ///   v1 = Phi(v0, v3)
2160 ///   v2 = load v1, 0
2161 ///   v3 = post_store v1, 4, x
2162 /// This function enables the load to be rewritten as v2 = load v3, 4.
2163 bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
2164                                               unsigned &BasePos,
2165                                               unsigned &OffsetPos,
2166                                               unsigned &NewBase,
2167                                               int64_t &Offset) {
2168   // Get the load instruction.
2169   if (TII->isPostIncrement(*MI))
2170     return false;
2171   unsigned BasePosLd, OffsetPosLd;
2172   if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
2173     return false;
2174   Register BaseReg = MI->getOperand(BasePosLd).getReg();
2175 
2176   // Look for the Phi instruction.
2177   MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
2178   MachineInstr *Phi = MRI.getVRegDef(BaseReg);
2179   if (!Phi || !Phi->isPHI())
2180     return false;
2181   // Get the register defined in the loop block.
2182   unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
2183   if (!PrevReg)
2184     return false;
2185 
2186   // Check for the post-increment load/store instruction.
2187   MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
2188   if (!PrevDef || PrevDef == MI)
2189     return false;
2190 
2191   if (!TII->isPostIncrement(*PrevDef))
2192     return false;
2193 
2194   unsigned BasePos1 = 0, OffsetPos1 = 0;
2195   if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
2196     return false;
2197 
2198   // Make sure that the instructions do not access the same memory location in
2199   // the next iteration.
2200   int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
2201   int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
2202   MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2203   NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
2204   bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
2205   MF.deleteMachineInstr(NewMI);
2206   if (!Disjoint)
2207     return false;
2208 
2209   // Set the return value once we determine that we return true.
2210   BasePos = BasePosLd;
2211   OffsetPos = OffsetPosLd;
2212   NewBase = PrevReg;
2213   Offset = StoreOffset;
2214   return true;
2215 }
2216 
2217 /// Apply changes to the instruction if needed. The changes are need
2218 /// to improve the scheduling and depend up on the final schedule.
2219 void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
2220                                          SMSchedule &Schedule) {
2221   SUnit *SU = getSUnit(MI);
2222   DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
2223       InstrChanges.find(SU);
2224   if (It != InstrChanges.end()) {
2225     std::pair<unsigned, int64_t> RegAndOffset = It->second;
2226     unsigned BasePos, OffsetPos;
2227     if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
2228       return;
2229     Register BaseReg = MI->getOperand(BasePos).getReg();
2230     MachineInstr *LoopDef = findDefInLoop(BaseReg);
2231     int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
2232     int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
2233     int BaseStageNum = Schedule.stageScheduled(SU);
2234     int BaseCycleNum = Schedule.cycleScheduled(SU);
2235     if (BaseStageNum < DefStageNum) {
2236       MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2237       int OffsetDiff = DefStageNum - BaseStageNum;
2238       if (DefCycleNum < BaseCycleNum) {
2239         NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
2240         if (OffsetDiff > 0)
2241           --OffsetDiff;
2242       }
2243       int64_t NewOffset =
2244           MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
2245       NewMI->getOperand(OffsetPos).setImm(NewOffset);
2246       SU->setInstr(NewMI);
2247       MISUnitMap[NewMI] = SU;
2248       NewMIs[MI] = NewMI;
2249     }
2250   }
2251 }
2252 
2253 /// Return the instruction in the loop that defines the register.
2254 /// If the definition is a Phi, then follow the Phi operand to
2255 /// the instruction in the loop.
2256 MachineInstr *SwingSchedulerDAG::findDefInLoop(Register Reg) {
2257   SmallPtrSet<MachineInstr *, 8> Visited;
2258   MachineInstr *Def = MRI.getVRegDef(Reg);
2259   while (Def->isPHI()) {
2260     if (!Visited.insert(Def).second)
2261       break;
2262     for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
2263       if (Def->getOperand(i + 1).getMBB() == BB) {
2264         Def = MRI.getVRegDef(Def->getOperand(i).getReg());
2265         break;
2266       }
2267   }
2268   return Def;
2269 }
2270 
2271 /// Return true for an order or output dependence that is loop carried
2272 /// potentially. A dependence is loop carried if the destination defines a valu
2273 /// that may be used or defined by the source in a subsequent iteration.
2274 bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
2275                                          bool isSucc) {
2276   if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
2277       Dep.isArtificial() || Dep.getSUnit()->isBoundaryNode())
2278     return false;
2279 
2280   if (!SwpPruneLoopCarried)
2281     return true;
2282 
2283   if (Dep.getKind() == SDep::Output)
2284     return true;
2285 
2286   MachineInstr *SI = Source->getInstr();
2287   MachineInstr *DI = Dep.getSUnit()->getInstr();
2288   if (!isSucc)
2289     std::swap(SI, DI);
2290   assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
2291 
2292   // Assume ordered loads and stores may have a loop carried dependence.
2293   if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
2294       SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
2295       SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
2296     return true;
2297 
2298   // Only chain dependences between a load and store can be loop carried.
2299   if (!DI->mayStore() || !SI->mayLoad())
2300     return false;
2301 
2302   unsigned DeltaS, DeltaD;
2303   if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
2304     return true;
2305 
2306   const MachineOperand *BaseOpS, *BaseOpD;
2307   int64_t OffsetS, OffsetD;
2308   bool OffsetSIsScalable, OffsetDIsScalable;
2309   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2310   if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, OffsetSIsScalable,
2311                                     TRI) ||
2312       !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, OffsetDIsScalable,
2313                                     TRI))
2314     return true;
2315 
2316   assert(!OffsetSIsScalable && !OffsetDIsScalable &&
2317          "Expected offsets to be byte offsets");
2318 
2319   if (!BaseOpS->isIdenticalTo(*BaseOpD))
2320     return true;
2321 
2322   // Check that the base register is incremented by a constant value for each
2323   // iteration.
2324   MachineInstr *Def = MRI.getVRegDef(BaseOpS->getReg());
2325   if (!Def || !Def->isPHI())
2326     return true;
2327   unsigned InitVal = 0;
2328   unsigned LoopVal = 0;
2329   getPhiRegs(*Def, BB, InitVal, LoopVal);
2330   MachineInstr *LoopDef = MRI.getVRegDef(LoopVal);
2331   int D = 0;
2332   if (!LoopDef || !TII->getIncrementValue(*LoopDef, D))
2333     return true;
2334 
2335   uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
2336   uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
2337 
2338   // This is the main test, which checks the offset values and the loop
2339   // increment value to determine if the accesses may be loop carried.
2340   if (AccessSizeS == MemoryLocation::UnknownSize ||
2341       AccessSizeD == MemoryLocation::UnknownSize)
2342     return true;
2343 
2344   if (DeltaS != DeltaD || DeltaS < AccessSizeS || DeltaD < AccessSizeD)
2345     return true;
2346 
2347   return (OffsetS + (int64_t)AccessSizeS < OffsetD + (int64_t)AccessSizeD);
2348 }
2349 
2350 void SwingSchedulerDAG::postprocessDAG() {
2351   for (auto &M : Mutations)
2352     M->apply(this);
2353 }
2354 
2355 /// Try to schedule the node at the specified StartCycle and continue
2356 /// until the node is schedule or the EndCycle is reached.  This function
2357 /// returns true if the node is scheduled.  This routine may search either
2358 /// forward or backward for a place to insert the instruction based upon
2359 /// the relative values of StartCycle and EndCycle.
2360 bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
2361   bool forward = true;
2362   LLVM_DEBUG({
2363     dbgs() << "Trying to insert node between " << StartCycle << " and "
2364            << EndCycle << " II: " << II << "\n";
2365   });
2366   if (StartCycle > EndCycle)
2367     forward = false;
2368 
2369   // The terminating condition depends on the direction.
2370   int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
2371   for (int curCycle = StartCycle; curCycle != termCycle;
2372        forward ? ++curCycle : --curCycle) {
2373 
2374     // Add the already scheduled instructions at the specified cycle to the
2375     // DFA.
2376     ProcItinResources.clearResources();
2377     for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
2378          checkCycle <= LastCycle; checkCycle += II) {
2379       std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
2380 
2381       for (SUnit *CI : cycleInstrs) {
2382         if (ST.getInstrInfo()->isZeroCost(CI->getInstr()->getOpcode()))
2383           continue;
2384         assert(ProcItinResources.canReserveResources(*CI->getInstr()) &&
2385                "These instructions have already been scheduled.");
2386         ProcItinResources.reserveResources(*CI->getInstr());
2387       }
2388     }
2389     if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
2390         ProcItinResources.canReserveResources(*SU->getInstr())) {
2391       LLVM_DEBUG({
2392         dbgs() << "\tinsert at cycle " << curCycle << " ";
2393         SU->getInstr()->dump();
2394       });
2395 
2396       ScheduledInstrs[curCycle].push_back(SU);
2397       InstrToCycle.insert(std::make_pair(SU, curCycle));
2398       if (curCycle > LastCycle)
2399         LastCycle = curCycle;
2400       if (curCycle < FirstCycle)
2401         FirstCycle = curCycle;
2402       return true;
2403     }
2404     LLVM_DEBUG({
2405       dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
2406       SU->getInstr()->dump();
2407     });
2408   }
2409   return false;
2410 }
2411 
2412 // Return the cycle of the earliest scheduled instruction in the chain.
2413 int SMSchedule::earliestCycleInChain(const SDep &Dep) {
2414   SmallPtrSet<SUnit *, 8> Visited;
2415   SmallVector<SDep, 8> Worklist;
2416   Worklist.push_back(Dep);
2417   int EarlyCycle = INT_MAX;
2418   while (!Worklist.empty()) {
2419     const SDep &Cur = Worklist.pop_back_val();
2420     SUnit *PrevSU = Cur.getSUnit();
2421     if (Visited.count(PrevSU))
2422       continue;
2423     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
2424     if (it == InstrToCycle.end())
2425       continue;
2426     EarlyCycle = std::min(EarlyCycle, it->second);
2427     for (const auto &PI : PrevSU->Preds)
2428       if (PI.getKind() == SDep::Order || PI.getKind() == SDep::Output)
2429         Worklist.push_back(PI);
2430     Visited.insert(PrevSU);
2431   }
2432   return EarlyCycle;
2433 }
2434 
2435 // Return the cycle of the latest scheduled instruction in the chain.
2436 int SMSchedule::latestCycleInChain(const SDep &Dep) {
2437   SmallPtrSet<SUnit *, 8> Visited;
2438   SmallVector<SDep, 8> Worklist;
2439   Worklist.push_back(Dep);
2440   int LateCycle = INT_MIN;
2441   while (!Worklist.empty()) {
2442     const SDep &Cur = Worklist.pop_back_val();
2443     SUnit *SuccSU = Cur.getSUnit();
2444     if (Visited.count(SuccSU) || SuccSU->isBoundaryNode())
2445       continue;
2446     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
2447     if (it == InstrToCycle.end())
2448       continue;
2449     LateCycle = std::max(LateCycle, it->second);
2450     for (const auto &SI : SuccSU->Succs)
2451       if (SI.getKind() == SDep::Order || SI.getKind() == SDep::Output)
2452         Worklist.push_back(SI);
2453     Visited.insert(SuccSU);
2454   }
2455   return LateCycle;
2456 }
2457 
2458 /// If an instruction has a use that spans multiple iterations, then
2459 /// return true. These instructions are characterized by having a back-ege
2460 /// to a Phi, which contains a reference to another Phi.
2461 static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
2462   for (auto &P : SU->Preds)
2463     if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
2464       for (auto &S : P.getSUnit()->Succs)
2465         if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
2466           return P.getSUnit();
2467   return nullptr;
2468 }
2469 
2470 /// Compute the scheduling start slot for the instruction.  The start slot
2471 /// depends on any predecessor or successor nodes scheduled already.
2472 void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
2473                               int *MinEnd, int *MaxStart, int II,
2474                               SwingSchedulerDAG *DAG) {
2475   // Iterate over each instruction that has been scheduled already.  The start
2476   // slot computation depends on whether the previously scheduled instruction
2477   // is a predecessor or successor of the specified instruction.
2478   for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
2479 
2480     // Iterate over each instruction in the current cycle.
2481     for (SUnit *I : getInstructions(cycle)) {
2482       // Because we're processing a DAG for the dependences, we recognize
2483       // the back-edge in recurrences by anti dependences.
2484       for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
2485         const SDep &Dep = SU->Preds[i];
2486         if (Dep.getSUnit() == I) {
2487           if (!DAG->isBackedge(SU, Dep)) {
2488             int EarlyStart = cycle + Dep.getLatency() -
2489                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
2490             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
2491             if (DAG->isLoopCarriedDep(SU, Dep, false)) {
2492               int End = earliestCycleInChain(Dep) + (II - 1);
2493               *MinEnd = std::min(*MinEnd, End);
2494             }
2495           } else {
2496             int LateStart = cycle - Dep.getLatency() +
2497                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
2498             *MinLateStart = std::min(*MinLateStart, LateStart);
2499           }
2500         }
2501         // For instruction that requires multiple iterations, make sure that
2502         // the dependent instruction is not scheduled past the definition.
2503         SUnit *BE = multipleIterations(I, DAG);
2504         if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
2505             !SU->isPred(I))
2506           *MinLateStart = std::min(*MinLateStart, cycle);
2507       }
2508       for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
2509         if (SU->Succs[i].getSUnit() == I) {
2510           const SDep &Dep = SU->Succs[i];
2511           if (!DAG->isBackedge(SU, Dep)) {
2512             int LateStart = cycle - Dep.getLatency() +
2513                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
2514             *MinLateStart = std::min(*MinLateStart, LateStart);
2515             if (DAG->isLoopCarriedDep(SU, Dep)) {
2516               int Start = latestCycleInChain(Dep) + 1 - II;
2517               *MaxStart = std::max(*MaxStart, Start);
2518             }
2519           } else {
2520             int EarlyStart = cycle + Dep.getLatency() -
2521                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
2522             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
2523           }
2524         }
2525       }
2526     }
2527   }
2528 }
2529 
2530 /// Order the instructions within a cycle so that the definitions occur
2531 /// before the uses. Returns true if the instruction is added to the start
2532 /// of the list, or false if added to the end.
2533 void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
2534                                  std::deque<SUnit *> &Insts) {
2535   MachineInstr *MI = SU->getInstr();
2536   bool OrderBeforeUse = false;
2537   bool OrderAfterDef = false;
2538   bool OrderBeforeDef = false;
2539   unsigned MoveDef = 0;
2540   unsigned MoveUse = 0;
2541   int StageInst1 = stageScheduled(SU);
2542 
2543   unsigned Pos = 0;
2544   for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
2545        ++I, ++Pos) {
2546     for (MachineOperand &MO : MI->operands()) {
2547       if (!MO.isReg() || !Register::isVirtualRegister(MO.getReg()))
2548         continue;
2549 
2550       Register Reg = MO.getReg();
2551       unsigned BasePos, OffsetPos;
2552       if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
2553         if (MI->getOperand(BasePos).getReg() == Reg)
2554           if (unsigned NewReg = SSD->getInstrBaseReg(SU))
2555             Reg = NewReg;
2556       bool Reads, Writes;
2557       std::tie(Reads, Writes) =
2558           (*I)->getInstr()->readsWritesVirtualRegister(Reg);
2559       if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
2560         OrderBeforeUse = true;
2561         if (MoveUse == 0)
2562           MoveUse = Pos;
2563       } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
2564         // Add the instruction after the scheduled instruction.
2565         OrderAfterDef = true;
2566         MoveDef = Pos;
2567       } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
2568         if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
2569           OrderBeforeUse = true;
2570           if (MoveUse == 0)
2571             MoveUse = Pos;
2572         } else {
2573           OrderAfterDef = true;
2574           MoveDef = Pos;
2575         }
2576       } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
2577         OrderBeforeUse = true;
2578         if (MoveUse == 0)
2579           MoveUse = Pos;
2580         if (MoveUse != 0) {
2581           OrderAfterDef = true;
2582           MoveDef = Pos - 1;
2583         }
2584       } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
2585         // Add the instruction before the scheduled instruction.
2586         OrderBeforeUse = true;
2587         if (MoveUse == 0)
2588           MoveUse = Pos;
2589       } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
2590                  isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
2591         if (MoveUse == 0) {
2592           OrderBeforeDef = true;
2593           MoveUse = Pos;
2594         }
2595       }
2596     }
2597     // Check for order dependences between instructions. Make sure the source
2598     // is ordered before the destination.
2599     for (auto &S : SU->Succs) {
2600       if (S.getSUnit() != *I)
2601         continue;
2602       if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
2603         OrderBeforeUse = true;
2604         if (Pos < MoveUse)
2605           MoveUse = Pos;
2606       }
2607       // We did not handle HW dependences in previous for loop,
2608       // and we normally set Latency = 0 for Anti deps,
2609       // so may have nodes in same cycle with Anti denpendent on HW regs.
2610       else if (S.getKind() == SDep::Anti && stageScheduled(*I) == StageInst1) {
2611         OrderBeforeUse = true;
2612         if ((MoveUse == 0) || (Pos < MoveUse))
2613           MoveUse = Pos;
2614       }
2615     }
2616     for (auto &P : SU->Preds) {
2617       if (P.getSUnit() != *I)
2618         continue;
2619       if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
2620         OrderAfterDef = true;
2621         MoveDef = Pos;
2622       }
2623     }
2624   }
2625 
2626   // A circular dependence.
2627   if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
2628     OrderBeforeUse = false;
2629 
2630   // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
2631   // to a loop-carried dependence.
2632   if (OrderBeforeDef)
2633     OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
2634 
2635   // The uncommon case when the instruction order needs to be updated because
2636   // there is both a use and def.
2637   if (OrderBeforeUse && OrderAfterDef) {
2638     SUnit *UseSU = Insts.at(MoveUse);
2639     SUnit *DefSU = Insts.at(MoveDef);
2640     if (MoveUse > MoveDef) {
2641       Insts.erase(Insts.begin() + MoveUse);
2642       Insts.erase(Insts.begin() + MoveDef);
2643     } else {
2644       Insts.erase(Insts.begin() + MoveDef);
2645       Insts.erase(Insts.begin() + MoveUse);
2646     }
2647     orderDependence(SSD, UseSU, Insts);
2648     orderDependence(SSD, SU, Insts);
2649     orderDependence(SSD, DefSU, Insts);
2650     return;
2651   }
2652   // Put the new instruction first if there is a use in the list. Otherwise,
2653   // put it at the end of the list.
2654   if (OrderBeforeUse)
2655     Insts.push_front(SU);
2656   else
2657     Insts.push_back(SU);
2658 }
2659 
2660 /// Return true if the scheduled Phi has a loop carried operand.
2661 bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
2662   if (!Phi.isPHI())
2663     return false;
2664   assert(Phi.isPHI() && "Expecting a Phi.");
2665   SUnit *DefSU = SSD->getSUnit(&Phi);
2666   unsigned DefCycle = cycleScheduled(DefSU);
2667   int DefStage = stageScheduled(DefSU);
2668 
2669   unsigned InitVal = 0;
2670   unsigned LoopVal = 0;
2671   getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
2672   SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
2673   if (!UseSU)
2674     return true;
2675   if (UseSU->getInstr()->isPHI())
2676     return true;
2677   unsigned LoopCycle = cycleScheduled(UseSU);
2678   int LoopStage = stageScheduled(UseSU);
2679   return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
2680 }
2681 
2682 /// Return true if the instruction is a definition that is loop carried
2683 /// and defines the use on the next iteration.
2684 ///        v1 = phi(v2, v3)
2685 ///  (Def) v3 = op v1
2686 ///  (MO)   = v1
2687 /// If MO appears before Def, then then v1 and v3 may get assigned to the same
2688 /// register.
2689 bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
2690                                        MachineInstr *Def, MachineOperand &MO) {
2691   if (!MO.isReg())
2692     return false;
2693   if (Def->isPHI())
2694     return false;
2695   MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
2696   if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
2697     return false;
2698   if (!isLoopCarried(SSD, *Phi))
2699     return false;
2700   unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
2701   for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
2702     MachineOperand &DMO = Def->getOperand(i);
2703     if (!DMO.isReg() || !DMO.isDef())
2704       continue;
2705     if (DMO.getReg() == LoopReg)
2706       return true;
2707   }
2708   return false;
2709 }
2710 
2711 /// Determine transitive dependences of unpipelineable instructions
2712 SmallSet<SUnit *, 8> SMSchedule::computeUnpipelineableNodes(
2713     SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI) {
2714   SmallSet<SUnit *, 8> DoNotPipeline;
2715   SmallVector<SUnit *, 8> Worklist;
2716 
2717   for (auto &SU : SSD->SUnits)
2718     if (SU.isInstr() && PLI->shouldIgnoreForPipelining(SU.getInstr()))
2719       Worklist.push_back(&SU);
2720 
2721   while (!Worklist.empty()) {
2722     auto SU = Worklist.pop_back_val();
2723     if (DoNotPipeline.count(SU))
2724       continue;
2725     LLVM_DEBUG(dbgs() << "Do not pipeline SU(" << SU->NodeNum << ")\n");
2726     DoNotPipeline.insert(SU);
2727     for (auto &Dep : SU->Preds)
2728       Worklist.push_back(Dep.getSUnit());
2729     if (SU->getInstr()->isPHI())
2730       for (auto &Dep : SU->Succs)
2731         if (Dep.getKind() == SDep::Anti)
2732           Worklist.push_back(Dep.getSUnit());
2733   }
2734   return DoNotPipeline;
2735 }
2736 
2737 // Determine all instructions upon which any unpipelineable instruction depends
2738 // and ensure that they are in stage 0.  If unable to do so, return false.
2739 bool SMSchedule::normalizeNonPipelinedInstructions(
2740     SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI) {
2741   SmallSet<SUnit *, 8> DNP = computeUnpipelineableNodes(SSD, PLI);
2742 
2743   int NewLastCycle = INT_MIN;
2744   for (SUnit &SU : SSD->SUnits) {
2745     if (!SU.isInstr())
2746       continue;
2747     if (!DNP.contains(&SU) || stageScheduled(&SU) == 0) {
2748       NewLastCycle = std::max(NewLastCycle, InstrToCycle[&SU]);
2749       continue;
2750     }
2751 
2752     // Put the non-pipelined instruction as early as possible in the schedule
2753     int NewCycle = getFirstCycle();
2754     for (auto &Dep : SU.Preds)
2755       NewCycle = std::max(InstrToCycle[Dep.getSUnit()], NewCycle);
2756 
2757     int OldCycle = InstrToCycle[&SU];
2758     if (OldCycle != NewCycle) {
2759       InstrToCycle[&SU] = NewCycle;
2760       auto &OldS = getInstructions(OldCycle);
2761       OldS.erase(std::remove(OldS.begin(), OldS.end(), &SU), OldS.end());
2762       getInstructions(NewCycle).emplace_back(&SU);
2763       LLVM_DEBUG(dbgs() << "SU(" << SU.NodeNum
2764                         << ") is not pipelined; moving from cycle " << OldCycle
2765                         << " to " << NewCycle << " Instr:" << *SU.getInstr());
2766     }
2767     NewLastCycle = std::max(NewLastCycle, NewCycle);
2768   }
2769   LastCycle = NewLastCycle;
2770   return true;
2771 }
2772 
2773 // Check if the generated schedule is valid. This function checks if
2774 // an instruction that uses a physical register is scheduled in a
2775 // different stage than the definition. The pipeliner does not handle
2776 // physical register values that may cross a basic block boundary.
2777 // Furthermore, if a physical def/use pair is assigned to the same
2778 // cycle, orderDependence does not guarantee def/use ordering, so that
2779 // case should be considered invalid.  (The test checks for both
2780 // earlier and same-cycle use to be more robust.)
2781 bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
2782   for (SUnit &SU : SSD->SUnits) {
2783     if (!SU.hasPhysRegDefs)
2784       continue;
2785     int StageDef = stageScheduled(&SU);
2786     int CycleDef = InstrToCycle[&SU];
2787     assert(StageDef != -1 && "Instruction should have been scheduled.");
2788     for (auto &SI : SU.Succs)
2789       if (SI.isAssignedRegDep() && !SI.getSUnit()->isBoundaryNode())
2790         if (Register::isPhysicalRegister(SI.getReg())) {
2791           if (stageScheduled(SI.getSUnit()) != StageDef)
2792             return false;
2793           if (InstrToCycle[SI.getSUnit()] <= CycleDef)
2794             return false;
2795         }
2796   }
2797   return true;
2798 }
2799 
2800 /// A property of the node order in swing-modulo-scheduling is
2801 /// that for nodes outside circuits the following holds:
2802 /// none of them is scheduled after both a successor and a
2803 /// predecessor.
2804 /// The method below checks whether the property is met.
2805 /// If not, debug information is printed and statistics information updated.
2806 /// Note that we do not use an assert statement.
2807 /// The reason is that although an invalid node oder may prevent
2808 /// the pipeliner from finding a pipelined schedule for arbitrary II,
2809 /// it does not lead to the generation of incorrect code.
2810 void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
2811 
2812   // a sorted vector that maps each SUnit to its index in the NodeOrder
2813   typedef std::pair<SUnit *, unsigned> UnitIndex;
2814   std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
2815 
2816   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
2817     Indices.push_back(std::make_pair(NodeOrder[i], i));
2818 
2819   auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
2820     return std::get<0>(i1) < std::get<0>(i2);
2821   };
2822 
2823   // sort, so that we can perform a binary search
2824   llvm::sort(Indices, CompareKey);
2825 
2826   bool Valid = true;
2827   (void)Valid;
2828   // for each SUnit in the NodeOrder, check whether
2829   // it appears after both a successor and a predecessor
2830   // of the SUnit. If this is the case, and the SUnit
2831   // is not part of circuit, then the NodeOrder is not
2832   // valid.
2833   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
2834     SUnit *SU = NodeOrder[i];
2835     unsigned Index = i;
2836 
2837     bool PredBefore = false;
2838     bool SuccBefore = false;
2839 
2840     SUnit *Succ;
2841     SUnit *Pred;
2842     (void)Succ;
2843     (void)Pred;
2844 
2845     for (SDep &PredEdge : SU->Preds) {
2846       SUnit *PredSU = PredEdge.getSUnit();
2847       unsigned PredIndex = std::get<1>(
2848           *llvm::lower_bound(Indices, std::make_pair(PredSU, 0), CompareKey));
2849       if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
2850         PredBefore = true;
2851         Pred = PredSU;
2852         break;
2853       }
2854     }
2855 
2856     for (SDep &SuccEdge : SU->Succs) {
2857       SUnit *SuccSU = SuccEdge.getSUnit();
2858       // Do not process a boundary node, it was not included in NodeOrder,
2859       // hence not in Indices either, call to std::lower_bound() below will
2860       // return Indices.end().
2861       if (SuccSU->isBoundaryNode())
2862         continue;
2863       unsigned SuccIndex = std::get<1>(
2864           *llvm::lower_bound(Indices, std::make_pair(SuccSU, 0), CompareKey));
2865       if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
2866         SuccBefore = true;
2867         Succ = SuccSU;
2868         break;
2869       }
2870     }
2871 
2872     if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
2873       // instructions in circuits are allowed to be scheduled
2874       // after both a successor and predecessor.
2875       bool InCircuit = llvm::any_of(
2876           Circuits, [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
2877       if (InCircuit)
2878         LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
2879       else {
2880         Valid = false;
2881         NumNodeOrderIssues++;
2882         LLVM_DEBUG(dbgs() << "Predecessor ";);
2883       }
2884       LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
2885                         << " are scheduled before node " << SU->NodeNum
2886                         << "\n";);
2887     }
2888   }
2889 
2890   LLVM_DEBUG({
2891     if (!Valid)
2892       dbgs() << "Invalid node order found!\n";
2893   });
2894 }
2895 
2896 /// Attempt to fix the degenerate cases when the instruction serialization
2897 /// causes the register lifetimes to overlap. For example,
2898 ///   p' = store_pi(p, b)
2899 ///      = load p, offset
2900 /// In this case p and p' overlap, which means that two registers are needed.
2901 /// Instead, this function changes the load to use p' and updates the offset.
2902 void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
2903   unsigned OverlapReg = 0;
2904   unsigned NewBaseReg = 0;
2905   for (SUnit *SU : Instrs) {
2906     MachineInstr *MI = SU->getInstr();
2907     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
2908       const MachineOperand &MO = MI->getOperand(i);
2909       // Look for an instruction that uses p. The instruction occurs in the
2910       // same cycle but occurs later in the serialized order.
2911       if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
2912         // Check that the instruction appears in the InstrChanges structure,
2913         // which contains instructions that can have the offset updated.
2914         DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
2915           InstrChanges.find(SU);
2916         if (It != InstrChanges.end()) {
2917           unsigned BasePos, OffsetPos;
2918           // Update the base register and adjust the offset.
2919           if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
2920             MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2921             NewMI->getOperand(BasePos).setReg(NewBaseReg);
2922             int64_t NewOffset =
2923                 MI->getOperand(OffsetPos).getImm() - It->second.second;
2924             NewMI->getOperand(OffsetPos).setImm(NewOffset);
2925             SU->setInstr(NewMI);
2926             MISUnitMap[NewMI] = SU;
2927             NewMIs[MI] = NewMI;
2928           }
2929         }
2930         OverlapReg = 0;
2931         NewBaseReg = 0;
2932         break;
2933       }
2934       // Look for an instruction of the form p' = op(p), which uses and defines
2935       // two virtual registers that get allocated to the same physical register.
2936       unsigned TiedUseIdx = 0;
2937       if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
2938         // OverlapReg is p in the example above.
2939         OverlapReg = MI->getOperand(TiedUseIdx).getReg();
2940         // NewBaseReg is p' in the example above.
2941         NewBaseReg = MI->getOperand(i).getReg();
2942         break;
2943       }
2944     }
2945   }
2946 }
2947 
2948 /// After the schedule has been formed, call this function to combine
2949 /// the instructions from the different stages/cycles.  That is, this
2950 /// function creates a schedule that represents a single iteration.
2951 void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
2952   // Move all instructions to the first stage from later stages.
2953   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
2954     for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
2955          ++stage) {
2956       std::deque<SUnit *> &cycleInstrs =
2957           ScheduledInstrs[cycle + (stage * InitiationInterval)];
2958       for (SUnit *SU : llvm::reverse(cycleInstrs))
2959         ScheduledInstrs[cycle].push_front(SU);
2960     }
2961   }
2962 
2963   // Erase all the elements in the later stages. Only one iteration should
2964   // remain in the scheduled list, and it contains all the instructions.
2965   for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
2966     ScheduledInstrs.erase(cycle);
2967 
2968   // Change the registers in instruction as specified in the InstrChanges
2969   // map. We need to use the new registers to create the correct order.
2970   for (const SUnit &SU : SSD->SUnits)
2971     SSD->applyInstrChange(SU.getInstr(), *this);
2972 
2973   // Reorder the instructions in each cycle to fix and improve the
2974   // generated code.
2975   for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
2976     std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
2977     std::deque<SUnit *> newOrderPhi;
2978     for (SUnit *SU : cycleInstrs) {
2979       if (SU->getInstr()->isPHI())
2980         newOrderPhi.push_back(SU);
2981     }
2982     std::deque<SUnit *> newOrderI;
2983     for (SUnit *SU : cycleInstrs) {
2984       if (!SU->getInstr()->isPHI())
2985         orderDependence(SSD, SU, newOrderI);
2986     }
2987     // Replace the old order with the new order.
2988     cycleInstrs.swap(newOrderPhi);
2989     llvm::append_range(cycleInstrs, newOrderI);
2990     SSD->fixupRegisterOverlaps(cycleInstrs);
2991   }
2992 
2993   LLVM_DEBUG(dump(););
2994 }
2995 
2996 void NodeSet::print(raw_ostream &os) const {
2997   os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
2998      << " depth " << MaxDepth << " col " << Colocate << "\n";
2999   for (const auto &I : Nodes)
3000     os << "   SU(" << I->NodeNum << ") " << *(I->getInstr());
3001   os << "\n";
3002 }
3003 
3004 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3005 /// Print the schedule information to the given output.
3006 void SMSchedule::print(raw_ostream &os) const {
3007   // Iterate over each cycle.
3008   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3009     // Iterate over each instruction in the cycle.
3010     const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
3011     for (SUnit *CI : cycleInstrs->second) {
3012       os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
3013       os << "(" << CI->NodeNum << ") ";
3014       CI->getInstr()->print(os);
3015       os << "\n";
3016     }
3017   }
3018 }
3019 
3020 /// Utility function used for debugging to print the schedule.
3021 LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
3022 LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
3023 
3024 #endif
3025 
3026 void ResourceManager::initProcResourceVectors(
3027     const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
3028   unsigned ProcResourceID = 0;
3029 
3030   // We currently limit the resource kinds to 64 and below so that we can use
3031   // uint64_t for Masks
3032   assert(SM.getNumProcResourceKinds() < 64 &&
3033          "Too many kinds of resources, unsupported");
3034   // Create a unique bitmask for every processor resource unit.
3035   // Skip resource at index 0, since it always references 'InvalidUnit'.
3036   Masks.resize(SM.getNumProcResourceKinds());
3037   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3038     const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3039     if (Desc.SubUnitsIdxBegin)
3040       continue;
3041     Masks[I] = 1ULL << ProcResourceID;
3042     ProcResourceID++;
3043   }
3044   // Create a unique bitmask for every processor resource group.
3045   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3046     const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3047     if (!Desc.SubUnitsIdxBegin)
3048       continue;
3049     Masks[I] = 1ULL << ProcResourceID;
3050     for (unsigned U = 0; U < Desc.NumUnits; ++U)
3051       Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
3052     ProcResourceID++;
3053   }
3054   LLVM_DEBUG({
3055     if (SwpShowResMask) {
3056       dbgs() << "ProcResourceDesc:\n";
3057       for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3058         const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
3059         dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
3060                          ProcResource->Name, I, Masks[I],
3061                          ProcResource->NumUnits);
3062       }
3063       dbgs() << " -----------------\n";
3064     }
3065   });
3066 }
3067 
3068 bool ResourceManager::canReserveResources(const MCInstrDesc *MID) const {
3069 
3070   LLVM_DEBUG({
3071     if (SwpDebugResource)
3072       dbgs() << "canReserveResources:\n";
3073   });
3074   if (UseDFA)
3075     return DFAResources->canReserveResources(MID);
3076 
3077   unsigned InsnClass = MID->getSchedClass();
3078   const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
3079   if (!SCDesc->isValid()) {
3080     LLVM_DEBUG({
3081       dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3082       dbgs() << "isPseudo:" << MID->isPseudo() << "\n";
3083     });
3084     return true;
3085   }
3086 
3087   const MCWriteProcResEntry *I = STI->getWriteProcResBegin(SCDesc);
3088   const MCWriteProcResEntry *E = STI->getWriteProcResEnd(SCDesc);
3089   for (; I != E; ++I) {
3090     if (!I->Cycles)
3091       continue;
3092     const MCProcResourceDesc *ProcResource =
3093         SM.getProcResource(I->ProcResourceIdx);
3094     unsigned NumUnits = ProcResource->NumUnits;
3095     LLVM_DEBUG({
3096       if (SwpDebugResource)
3097         dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
3098                          ProcResource->Name, I->ProcResourceIdx,
3099                          ProcResourceCount[I->ProcResourceIdx], NumUnits,
3100                          I->Cycles);
3101     });
3102     if (ProcResourceCount[I->ProcResourceIdx] >= NumUnits)
3103       return false;
3104   }
3105   LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return true\n\n";);
3106   return true;
3107 }
3108 
3109 void ResourceManager::reserveResources(const MCInstrDesc *MID) {
3110   LLVM_DEBUG({
3111     if (SwpDebugResource)
3112       dbgs() << "reserveResources:\n";
3113   });
3114   if (UseDFA)
3115     return DFAResources->reserveResources(MID);
3116 
3117   unsigned InsnClass = MID->getSchedClass();
3118   const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
3119   if (!SCDesc->isValid()) {
3120     LLVM_DEBUG({
3121       dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3122       dbgs() << "isPseudo:" << MID->isPseudo() << "\n";
3123     });
3124     return;
3125   }
3126   for (const MCWriteProcResEntry &PRE :
3127        make_range(STI->getWriteProcResBegin(SCDesc),
3128                   STI->getWriteProcResEnd(SCDesc))) {
3129     if (!PRE.Cycles)
3130       continue;
3131     ++ProcResourceCount[PRE.ProcResourceIdx];
3132     LLVM_DEBUG({
3133       if (SwpDebugResource) {
3134         const MCProcResourceDesc *ProcResource =
3135             SM.getProcResource(PRE.ProcResourceIdx);
3136         dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
3137                          ProcResource->Name, PRE.ProcResourceIdx,
3138                          ProcResourceCount[PRE.ProcResourceIdx],
3139                          ProcResource->NumUnits, PRE.Cycles);
3140       }
3141     });
3142   }
3143   LLVM_DEBUG({
3144     if (SwpDebugResource)
3145       dbgs() << "reserveResources: done!\n\n";
3146   });
3147 }
3148 
3149 bool ResourceManager::canReserveResources(const MachineInstr &MI) const {
3150   return canReserveResources(&MI.getDesc());
3151 }
3152 
3153 void ResourceManager::reserveResources(const MachineInstr &MI) {
3154   return reserveResources(&MI.getDesc());
3155 }
3156 
3157 void ResourceManager::clearResources() {
3158   if (UseDFA)
3159     return DFAResources->clearResources();
3160   std::fill(ProcResourceCount.begin(), ProcResourceCount.end(), 0);
3161 }
3162