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> SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
173                                  cl::init(true),
174                                  cl::desc("Enable CopyToPhi DAG Mutation"));
175 
176 } // end namespace llvm
177 
178 unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
179 char MachinePipeliner::ID = 0;
180 #ifndef NDEBUG
181 int MachinePipeliner::NumTries = 0;
182 #endif
183 char &llvm::MachinePipelinerID = MachinePipeliner::ID;
184 
185 INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
186                       "Modulo Software Pipelining", false, false)
187 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
188 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
189 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
190 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
191 INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
192                     "Modulo Software Pipelining", false, false)
193 
194 /// The "main" function for implementing Swing Modulo Scheduling.
195 bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
196   if (skipFunction(mf.getFunction()))
197     return false;
198 
199   if (!EnableSWP)
200     return false;
201 
202   if (mf.getFunction().getAttributes().hasFnAttr(Attribute::OptimizeForSize) &&
203       !EnableSWPOptSize.getPosition())
204     return false;
205 
206   if (!mf.getSubtarget().enableMachinePipeliner())
207     return false;
208 
209   // Cannot pipeline loops without instruction itineraries if we are using
210   // DFA for the pipeliner.
211   if (mf.getSubtarget().useDFAforSMS() &&
212       (!mf.getSubtarget().getInstrItineraryData() ||
213        mf.getSubtarget().getInstrItineraryData()->isEmpty()))
214     return false;
215 
216   MF = &mf;
217   MLI = &getAnalysis<MachineLoopInfo>();
218   MDT = &getAnalysis<MachineDominatorTree>();
219   ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
220   TII = MF->getSubtarget().getInstrInfo();
221   RegClassInfo.runOnMachineFunction(*MF);
222 
223   for (auto &L : *MLI)
224     scheduleLoop(*L);
225 
226   return false;
227 }
228 
229 /// Attempt to perform the SMS algorithm on the specified loop. This function is
230 /// the main entry point for the algorithm.  The function identifies candidate
231 /// loops, calculates the minimum initiation interval, and attempts to schedule
232 /// the loop.
233 bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
234   bool Changed = false;
235   for (auto &InnerLoop : L)
236     Changed |= scheduleLoop(*InnerLoop);
237 
238 #ifndef NDEBUG
239   // Stop trying after reaching the limit (if any).
240   int Limit = SwpLoopLimit;
241   if (Limit >= 0) {
242     if (NumTries >= SwpLoopLimit)
243       return Changed;
244     NumTries++;
245   }
246 #endif
247 
248   setPragmaPipelineOptions(L);
249   if (!canPipelineLoop(L)) {
250     LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
251     ORE->emit([&]() {
252       return MachineOptimizationRemarkMissed(DEBUG_TYPE, "canPipelineLoop",
253                                              L.getStartLoc(), L.getHeader())
254              << "Failed to pipeline loop";
255     });
256 
257     LI.LoopPipelinerInfo.reset();
258     return Changed;
259   }
260 
261   ++NumTrytoPipeline;
262 
263   Changed = swingModuloScheduler(L);
264 
265   LI.LoopPipelinerInfo.reset();
266   return Changed;
267 }
268 
269 void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) {
270   // Reset the pragma for the next loop in iteration.
271   disabledByPragma = false;
272   II_setByPragma = 0;
273 
274   MachineBasicBlock *LBLK = L.getTopBlock();
275 
276   if (LBLK == nullptr)
277     return;
278 
279   const BasicBlock *BBLK = LBLK->getBasicBlock();
280   if (BBLK == nullptr)
281     return;
282 
283   const Instruction *TI = BBLK->getTerminator();
284   if (TI == nullptr)
285     return;
286 
287   MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop);
288   if (LoopID == nullptr)
289     return;
290 
291   assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
292   assert(LoopID->getOperand(0) == LoopID && "invalid loop");
293 
294   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
295     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
296 
297     if (MD == nullptr)
298       continue;
299 
300     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
301 
302     if (S == nullptr)
303       continue;
304 
305     if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
306       assert(MD->getNumOperands() == 2 &&
307              "Pipeline initiation interval hint metadata should have two operands.");
308       II_setByPragma =
309           mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
310       assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
311     } else if (S->getString() == "llvm.loop.pipeline.disable") {
312       disabledByPragma = true;
313     }
314   }
315 }
316 
317 /// Return true if the loop can be software pipelined.  The algorithm is
318 /// restricted to loops with a single basic block.  Make sure that the
319 /// branch in the loop can be analyzed.
320 bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
321   if (L.getNumBlocks() != 1) {
322     ORE->emit([&]() {
323       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
324                                                L.getStartLoc(), L.getHeader())
325              << "Not a single basic block: "
326              << ore::NV("NumBlocks", L.getNumBlocks());
327     });
328     return false;
329   }
330 
331   if (disabledByPragma) {
332     ORE->emit([&]() {
333       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
334                                                L.getStartLoc(), L.getHeader())
335              << "Disabled by Pragma.";
336     });
337     return false;
338   }
339 
340   // Check if the branch can't be understood because we can't do pipelining
341   // if that's the case.
342   LI.TBB = nullptr;
343   LI.FBB = nullptr;
344   LI.BrCond.clear();
345   if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) {
346     LLVM_DEBUG(dbgs() << "Unable to analyzeBranch, can NOT pipeline Loop\n");
347     NumFailBranch++;
348     ORE->emit([&]() {
349       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
350                                                L.getStartLoc(), L.getHeader())
351              << "The branch can't be understood";
352     });
353     return false;
354   }
355 
356   LI.LoopInductionVar = nullptr;
357   LI.LoopCompare = nullptr;
358   LI.LoopPipelinerInfo = TII->analyzeLoopForPipelining(L.getTopBlock());
359   if (!LI.LoopPipelinerInfo) {
360     LLVM_DEBUG(dbgs() << "Unable to analyzeLoop, can NOT pipeline Loop\n");
361     NumFailLoop++;
362     ORE->emit([&]() {
363       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
364                                                L.getStartLoc(), L.getHeader())
365              << "The loop structure is not supported";
366     });
367     return false;
368   }
369 
370   if (!L.getLoopPreheader()) {
371     LLVM_DEBUG(dbgs() << "Preheader not found, can NOT pipeline Loop\n");
372     NumFailPreheader++;
373     ORE->emit([&]() {
374       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
375                                                L.getStartLoc(), L.getHeader())
376              << "No loop preheader found";
377     });
378     return false;
379   }
380 
381   // Remove any subregisters from inputs to phi nodes.
382   preprocessPhiNodes(*L.getHeader());
383   return true;
384 }
385 
386 void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
387   MachineRegisterInfo &MRI = MF->getRegInfo();
388   SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
389 
390   for (MachineInstr &PI : B.phis()) {
391     MachineOperand &DefOp = PI.getOperand(0);
392     assert(DefOp.getSubReg() == 0);
393     auto *RC = MRI.getRegClass(DefOp.getReg());
394 
395     for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
396       MachineOperand &RegOp = PI.getOperand(i);
397       if (RegOp.getSubReg() == 0)
398         continue;
399 
400       // If the operand uses a subregister, replace it with a new register
401       // without subregisters, and generate a copy to the new register.
402       Register NewReg = MRI.createVirtualRegister(RC);
403       MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
404       MachineBasicBlock::iterator At = PredB.getFirstTerminator();
405       const DebugLoc &DL = PredB.findDebugLoc(At);
406       auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
407                     .addReg(RegOp.getReg(), getRegState(RegOp),
408                             RegOp.getSubReg());
409       Slots.insertMachineInstrInMaps(*Copy);
410       RegOp.setReg(NewReg);
411       RegOp.setSubReg(0);
412     }
413   }
414 }
415 
416 /// The SMS algorithm consists of the following main steps:
417 /// 1. Computation and analysis of the dependence graph.
418 /// 2. Ordering of the nodes (instructions).
419 /// 3. Attempt to Schedule the loop.
420 bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
421   assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
422 
423   SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo,
424                         II_setByPragma, LI.LoopPipelinerInfo.get());
425 
426   MachineBasicBlock *MBB = L.getHeader();
427   // The kernel should not include any terminator instructions.  These
428   // will be added back later.
429   SMS.startBlock(MBB);
430 
431   // Compute the number of 'real' instructions in the basic block by
432   // ignoring terminators.
433   unsigned size = MBB->size();
434   for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
435                                    E = MBB->instr_end();
436        I != E; ++I, --size)
437     ;
438 
439   SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
440   SMS.schedule();
441   SMS.exitRegion();
442 
443   SMS.finishBlock();
444   return SMS.hasNewSchedule();
445 }
446 
447 void MachinePipeliner::getAnalysisUsage(AnalysisUsage &AU) const {
448   AU.addRequired<AAResultsWrapperPass>();
449   AU.addPreserved<AAResultsWrapperPass>();
450   AU.addRequired<MachineLoopInfo>();
451   AU.addRequired<MachineDominatorTree>();
452   AU.addRequired<LiveIntervals>();
453   AU.addRequired<MachineOptimizationRemarkEmitterPass>();
454   MachineFunctionPass::getAnalysisUsage(AU);
455 }
456 
457 void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
458   if (II_setByPragma > 0)
459     MII = II_setByPragma;
460   else
461     MII = std::max(ResMII, RecMII);
462 }
463 
464 void SwingSchedulerDAG::setMAX_II() {
465   if (II_setByPragma > 0)
466     MAX_II = II_setByPragma;
467   else
468     MAX_II = MII + 10;
469 }
470 
471 /// We override the schedule function in ScheduleDAGInstrs to implement the
472 /// scheduling part of the Swing Modulo Scheduling algorithm.
473 void SwingSchedulerDAG::schedule() {
474   AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
475   buildSchedGraph(AA);
476   addLoopCarriedDependences(AA);
477   updatePhiDependences();
478   Topo.InitDAGTopologicalSorting();
479   changeDependences();
480   postprocessDAG();
481   LLVM_DEBUG(dump());
482 
483   NodeSetType NodeSets;
484   findCircuits(NodeSets);
485   NodeSetType Circuits = NodeSets;
486 
487   // Calculate the MII.
488   unsigned ResMII = calculateResMII();
489   unsigned RecMII = calculateRecMII(NodeSets);
490 
491   fuseRecs(NodeSets);
492 
493   // This flag is used for testing and can cause correctness problems.
494   if (SwpIgnoreRecMII)
495     RecMII = 0;
496 
497   setMII(ResMII, RecMII);
498   setMAX_II();
499 
500   LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
501                     << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
502 
503   // Can't schedule a loop without a valid MII.
504   if (MII == 0) {
505     LLVM_DEBUG(dbgs() << "Invalid Minimal Initiation Interval: 0\n");
506     NumFailZeroMII++;
507     Pass.ORE->emit([&]() {
508       return MachineOptimizationRemarkAnalysis(
509                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
510              << "Invalid Minimal Initiation Interval: 0";
511     });
512     return;
513   }
514 
515   // Don't pipeline large loops.
516   if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) {
517     LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
518                       << ", we don't pipleline large loops\n");
519     NumFailLargeMaxMII++;
520     Pass.ORE->emit([&]() {
521       return MachineOptimizationRemarkAnalysis(
522                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
523              << "Minimal Initiation Interval too large: "
524              << ore::NV("MII", (int)MII) << " > "
525              << ore::NV("SwpMaxMii", SwpMaxMii) << "."
526              << "Refer to -pipeliner-max-mii.";
527     });
528     return;
529   }
530 
531   computeNodeFunctions(NodeSets);
532 
533   registerPressureFilter(NodeSets);
534 
535   colocateNodeSets(NodeSets);
536 
537   checkNodeSets(NodeSets);
538 
539   LLVM_DEBUG({
540     for (auto &I : NodeSets) {
541       dbgs() << "  Rec NodeSet ";
542       I.dump();
543     }
544   });
545 
546   llvm::stable_sort(NodeSets, std::greater<NodeSet>());
547 
548   groupRemainingNodes(NodeSets);
549 
550   removeDuplicateNodes(NodeSets);
551 
552   LLVM_DEBUG({
553     for (auto &I : NodeSets) {
554       dbgs() << "  NodeSet ";
555       I.dump();
556     }
557   });
558 
559   computeNodeOrder(NodeSets);
560 
561   // check for node order issues
562   checkValidNodeOrder(Circuits);
563 
564   SMSchedule Schedule(Pass.MF);
565   Scheduled = schedulePipeline(Schedule);
566 
567   if (!Scheduled){
568     LLVM_DEBUG(dbgs() << "No schedule found, return\n");
569     NumFailNoSchedule++;
570     Pass.ORE->emit([&]() {
571       return MachineOptimizationRemarkAnalysis(
572                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
573              << "Unable to find schedule";
574     });
575     return;
576   }
577 
578   unsigned numStages = Schedule.getMaxStageCount();
579   // No need to generate pipeline if there are no overlapped iterations.
580   if (numStages == 0) {
581     LLVM_DEBUG(dbgs() << "No overlapped iterations, skip.\n");
582     NumFailZeroStage++;
583     Pass.ORE->emit([&]() {
584       return MachineOptimizationRemarkAnalysis(
585                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
586              << "No need to pipeline - no overlapped iterations in schedule.";
587     });
588     return;
589   }
590   // Check that the maximum stage count is less than user-defined limit.
591   if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) {
592     LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages
593                       << " : too many stages, abort\n");
594     NumFailLargeMaxStage++;
595     Pass.ORE->emit([&]() {
596       return MachineOptimizationRemarkAnalysis(
597                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
598              << "Too many stages in schedule: "
599              << ore::NV("numStages", (int)numStages) << " > "
600              << ore::NV("SwpMaxStages", SwpMaxStages)
601              << ". Refer to -pipeliner-max-stages.";
602     });
603     return;
604   }
605 
606   Pass.ORE->emit([&]() {
607     return MachineOptimizationRemark(DEBUG_TYPE, "schedule", Loop.getStartLoc(),
608                                      Loop.getHeader())
609            << "Pipelined succesfully!";
610   });
611 
612   // Generate the schedule as a ModuloSchedule.
613   DenseMap<MachineInstr *, int> Cycles, Stages;
614   std::vector<MachineInstr *> OrderedInsts;
615   for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
616        ++Cycle) {
617     for (SUnit *SU : Schedule.getInstructions(Cycle)) {
618       OrderedInsts.push_back(SU->getInstr());
619       Cycles[SU->getInstr()] = Cycle;
620       Stages[SU->getInstr()] = Schedule.stageScheduled(SU);
621     }
622   }
623   DenseMap<MachineInstr *, std::pair<unsigned, int64_t>> NewInstrChanges;
624   for (auto &KV : NewMIs) {
625     Cycles[KV.first] = Cycles[KV.second];
626     Stages[KV.first] = Stages[KV.second];
627     NewInstrChanges[KV.first] = InstrChanges[getSUnit(KV.first)];
628   }
629 
630   ModuloSchedule MS(MF, &Loop, std::move(OrderedInsts), std::move(Cycles),
631                     std::move(Stages));
632   if (EmitTestAnnotations) {
633     assert(NewInstrChanges.empty() &&
634            "Cannot serialize a schedule with InstrChanges!");
635     ModuloScheduleTestAnnotater MSTI(MF, MS);
636     MSTI.annotate();
637     return;
638   }
639   // The experimental code generator can't work if there are InstChanges.
640   if (ExperimentalCodeGen && NewInstrChanges.empty()) {
641     PeelingModuloScheduleExpander MSE(MF, MS, &LIS);
642     MSE.expand();
643   } else {
644     ModuloScheduleExpander MSE(MF, MS, LIS, std::move(NewInstrChanges));
645     MSE.expand();
646     MSE.cleanup();
647   }
648   ++NumPipelined;
649 }
650 
651 /// Clean up after the software pipeliner runs.
652 void SwingSchedulerDAG::finishBlock() {
653   for (auto &KV : NewMIs)
654     MF.deleteMachineInstr(KV.second);
655   NewMIs.clear();
656 
657   // Call the superclass.
658   ScheduleDAGInstrs::finishBlock();
659 }
660 
661 /// Return the register values for  the operands of a Phi instruction.
662 /// This function assume the instruction is a Phi.
663 static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
664                        unsigned &InitVal, unsigned &LoopVal) {
665   assert(Phi.isPHI() && "Expecting a Phi.");
666 
667   InitVal = 0;
668   LoopVal = 0;
669   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
670     if (Phi.getOperand(i + 1).getMBB() != Loop)
671       InitVal = Phi.getOperand(i).getReg();
672     else
673       LoopVal = Phi.getOperand(i).getReg();
674 
675   assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
676 }
677 
678 /// Return the Phi register value that comes the loop block.
679 static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
680   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
681     if (Phi.getOperand(i + 1).getMBB() == LoopBB)
682       return Phi.getOperand(i).getReg();
683   return 0;
684 }
685 
686 /// Return true if SUb can be reached from SUa following the chain edges.
687 static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
688   SmallPtrSet<SUnit *, 8> Visited;
689   SmallVector<SUnit *, 8> Worklist;
690   Worklist.push_back(SUa);
691   while (!Worklist.empty()) {
692     const SUnit *SU = Worklist.pop_back_val();
693     for (auto &SI : SU->Succs) {
694       SUnit *SuccSU = SI.getSUnit();
695       if (SI.getKind() == SDep::Order) {
696         if (Visited.count(SuccSU))
697           continue;
698         if (SuccSU == SUb)
699           return true;
700         Worklist.push_back(SuccSU);
701         Visited.insert(SuccSU);
702       }
703     }
704   }
705   return false;
706 }
707 
708 /// Return true if the instruction causes a chain between memory
709 /// references before and after it.
710 static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
711   return MI.isCall() || MI.mayRaiseFPException() ||
712          MI.hasUnmodeledSideEffects() ||
713          (MI.hasOrderedMemoryRef() &&
714           (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
715 }
716 
717 /// Return the underlying objects for the memory references of an instruction.
718 /// This function calls the code in ValueTracking, but first checks that the
719 /// instruction has a memory operand.
720 static void getUnderlyingObjects(const MachineInstr *MI,
721                                  SmallVectorImpl<const Value *> &Objs) {
722   if (!MI->hasOneMemOperand())
723     return;
724   MachineMemOperand *MM = *MI->memoperands_begin();
725   if (!MM->getValue())
726     return;
727   getUnderlyingObjects(MM->getValue(), Objs);
728   for (const Value *V : Objs) {
729     if (!isIdentifiedObject(V)) {
730       Objs.clear();
731       return;
732     }
733     Objs.push_back(V);
734   }
735 }
736 
737 /// Add a chain edge between a load and store if the store can be an
738 /// alias of the load on a subsequent iteration, i.e., a loop carried
739 /// dependence. This code is very similar to the code in ScheduleDAGInstrs
740 /// but that code doesn't create loop carried dependences.
741 void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
742   MapVector<const Value *, SmallVector<SUnit *, 4>> PendingLoads;
743   Value *UnknownValue =
744     UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
745   for (auto &SU : SUnits) {
746     MachineInstr &MI = *SU.getInstr();
747     if (isDependenceBarrier(MI, AA))
748       PendingLoads.clear();
749     else if (MI.mayLoad()) {
750       SmallVector<const Value *, 4> Objs;
751       ::getUnderlyingObjects(&MI, Objs);
752       if (Objs.empty())
753         Objs.push_back(UnknownValue);
754       for (auto V : Objs) {
755         SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
756         SUs.push_back(&SU);
757       }
758     } else if (MI.mayStore()) {
759       SmallVector<const Value *, 4> Objs;
760       ::getUnderlyingObjects(&MI, Objs);
761       if (Objs.empty())
762         Objs.push_back(UnknownValue);
763       for (auto V : Objs) {
764         MapVector<const Value *, SmallVector<SUnit *, 4>>::iterator I =
765             PendingLoads.find(V);
766         if (I == PendingLoads.end())
767           continue;
768         for (auto Load : I->second) {
769           if (isSuccOrder(Load, &SU))
770             continue;
771           MachineInstr &LdMI = *Load->getInstr();
772           // First, perform the cheaper check that compares the base register.
773           // If they are the same and the load offset is less than the store
774           // offset, then mark the dependence as loop carried potentially.
775           const MachineOperand *BaseOp1, *BaseOp2;
776           int64_t Offset1, Offset2;
777           bool Offset1IsScalable, Offset2IsScalable;
778           if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1,
779                                            Offset1IsScalable, TRI) &&
780               TII->getMemOperandWithOffset(MI, BaseOp2, Offset2,
781                                            Offset2IsScalable, TRI)) {
782             if (BaseOp1->isIdenticalTo(*BaseOp2) &&
783                 Offset1IsScalable == Offset2IsScalable &&
784                 (int)Offset1 < (int)Offset2) {
785               assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI) &&
786                      "What happened to the chain edge?");
787               SDep Dep(Load, SDep::Barrier);
788               Dep.setLatency(1);
789               SU.addPred(Dep);
790               continue;
791             }
792           }
793           // Second, the more expensive check that uses alias analysis on the
794           // base registers. If they alias, and the load offset is less than
795           // the store offset, the mark the dependence as loop carried.
796           if (!AA) {
797             SDep Dep(Load, SDep::Barrier);
798             Dep.setLatency(1);
799             SU.addPred(Dep);
800             continue;
801           }
802           MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
803           MachineMemOperand *MMO2 = *MI.memoperands_begin();
804           if (!MMO1->getValue() || !MMO2->getValue()) {
805             SDep Dep(Load, SDep::Barrier);
806             Dep.setLatency(1);
807             SU.addPred(Dep);
808             continue;
809           }
810           if (MMO1->getValue() == MMO2->getValue() &&
811               MMO1->getOffset() <= MMO2->getOffset()) {
812             SDep Dep(Load, SDep::Barrier);
813             Dep.setLatency(1);
814             SU.addPred(Dep);
815             continue;
816           }
817           if (!AA->isNoAlias(
818                   MemoryLocation::getAfter(MMO1->getValue(), MMO1->getAAInfo()),
819                   MemoryLocation::getAfter(MMO2->getValue(),
820                                            MMO2->getAAInfo()))) {
821             SDep Dep(Load, SDep::Barrier);
822             Dep.setLatency(1);
823             SU.addPred(Dep);
824           }
825         }
826       }
827     }
828   }
829 }
830 
831 /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
832 /// processes dependences for PHIs. This function adds true dependences
833 /// from a PHI to a use, and a loop carried dependence from the use to the
834 /// PHI. The loop carried dependence is represented as an anti dependence
835 /// edge. This function also removes chain dependences between unrelated
836 /// PHIs.
837 void SwingSchedulerDAG::updatePhiDependences() {
838   SmallVector<SDep, 4> RemoveDeps;
839   const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
840 
841   // Iterate over each DAG node.
842   for (SUnit &I : SUnits) {
843     RemoveDeps.clear();
844     // Set to true if the instruction has an operand defined by a Phi.
845     unsigned HasPhiUse = 0;
846     unsigned HasPhiDef = 0;
847     MachineInstr *MI = I.getInstr();
848     // Iterate over each operand, and we process the definitions.
849     for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
850                                     MOE = MI->operands_end();
851          MOI != MOE; ++MOI) {
852       if (!MOI->isReg())
853         continue;
854       Register Reg = MOI->getReg();
855       if (MOI->isDef()) {
856         // If the register is used by a Phi, then create an anti dependence.
857         for (MachineRegisterInfo::use_instr_iterator
858                  UI = MRI.use_instr_begin(Reg),
859                  UE = MRI.use_instr_end();
860              UI != UE; ++UI) {
861           MachineInstr *UseMI = &*UI;
862           SUnit *SU = getSUnit(UseMI);
863           if (SU != nullptr && UseMI->isPHI()) {
864             if (!MI->isPHI()) {
865               SDep Dep(SU, SDep::Anti, Reg);
866               Dep.setLatency(1);
867               I.addPred(Dep);
868             } else {
869               HasPhiDef = Reg;
870               // Add a chain edge to a dependent Phi that isn't an existing
871               // predecessor.
872               if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
873                 I.addPred(SDep(SU, SDep::Barrier));
874             }
875           }
876         }
877       } else if (MOI->isUse()) {
878         // If the register is defined by a Phi, then create a true dependence.
879         MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
880         if (DefMI == nullptr)
881           continue;
882         SUnit *SU = getSUnit(DefMI);
883         if (SU != nullptr && DefMI->isPHI()) {
884           if (!MI->isPHI()) {
885             SDep Dep(SU, SDep::Data, Reg);
886             Dep.setLatency(0);
887             ST.adjustSchedDependency(SU, 0, &I, MI->getOperandNo(MOI), Dep);
888             I.addPred(Dep);
889           } else {
890             HasPhiUse = Reg;
891             // Add a chain edge to a dependent Phi that isn't an existing
892             // predecessor.
893             if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
894               I.addPred(SDep(SU, SDep::Barrier));
895           }
896         }
897       }
898     }
899     // Remove order dependences from an unrelated Phi.
900     if (!SwpPruneDeps)
901       continue;
902     for (auto &PI : I.Preds) {
903       MachineInstr *PMI = PI.getSUnit()->getInstr();
904       if (PMI->isPHI() && PI.getKind() == SDep::Order) {
905         if (I.getInstr()->isPHI()) {
906           if (PMI->getOperand(0).getReg() == HasPhiUse)
907             continue;
908           if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
909             continue;
910         }
911         RemoveDeps.push_back(PI);
912       }
913     }
914     for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
915       I.removePred(RemoveDeps[i]);
916   }
917 }
918 
919 /// Iterate over each DAG node and see if we can change any dependences
920 /// in order to reduce the recurrence MII.
921 void SwingSchedulerDAG::changeDependences() {
922   // See if an instruction can use a value from the previous iteration.
923   // If so, we update the base and offset of the instruction and change
924   // the dependences.
925   for (SUnit &I : SUnits) {
926     unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
927     int64_t NewOffset = 0;
928     if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
929                                NewOffset))
930       continue;
931 
932     // Get the MI and SUnit for the instruction that defines the original base.
933     Register OrigBase = I.getInstr()->getOperand(BasePos).getReg();
934     MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
935     if (!DefMI)
936       continue;
937     SUnit *DefSU = getSUnit(DefMI);
938     if (!DefSU)
939       continue;
940     // Get the MI and SUnit for the instruction that defins the new base.
941     MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
942     if (!LastMI)
943       continue;
944     SUnit *LastSU = getSUnit(LastMI);
945     if (!LastSU)
946       continue;
947 
948     if (Topo.IsReachable(&I, LastSU))
949       continue;
950 
951     // Remove the dependence. The value now depends on a prior iteration.
952     SmallVector<SDep, 4> Deps;
953     for (const SDep &P : I.Preds)
954       if (P.getSUnit() == DefSU)
955         Deps.push_back(P);
956     for (int i = 0, e = Deps.size(); i != e; i++) {
957       Topo.RemovePred(&I, Deps[i].getSUnit());
958       I.removePred(Deps[i]);
959     }
960     // Remove the chain dependence between the instructions.
961     Deps.clear();
962     for (auto &P : LastSU->Preds)
963       if (P.getSUnit() == &I && P.getKind() == SDep::Order)
964         Deps.push_back(P);
965     for (int i = 0, e = Deps.size(); i != e; i++) {
966       Topo.RemovePred(LastSU, Deps[i].getSUnit());
967       LastSU->removePred(Deps[i]);
968     }
969 
970     // Add a dependence between the new instruction and the instruction
971     // that defines the new base.
972     SDep Dep(&I, SDep::Anti, NewBase);
973     Topo.AddPred(LastSU, &I);
974     LastSU->addPred(Dep);
975 
976     // Remember the base and offset information so that we can update the
977     // instruction during code generation.
978     InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
979   }
980 }
981 
982 namespace {
983 
984 // FuncUnitSorter - Comparison operator used to sort instructions by
985 // the number of functional unit choices.
986 struct FuncUnitSorter {
987   const InstrItineraryData *InstrItins;
988   const MCSubtargetInfo *STI;
989   DenseMap<InstrStage::FuncUnits, unsigned> Resources;
990 
991   FuncUnitSorter(const TargetSubtargetInfo &TSI)
992       : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
993 
994   // Compute the number of functional unit alternatives needed
995   // at each stage, and take the minimum value. We prioritize the
996   // instructions by the least number of choices first.
997   unsigned minFuncUnits(const MachineInstr *Inst,
998                         InstrStage::FuncUnits &F) const {
999     unsigned SchedClass = Inst->getDesc().getSchedClass();
1000     unsigned min = UINT_MAX;
1001     if (InstrItins && !InstrItins->isEmpty()) {
1002       for (const InstrStage &IS :
1003            make_range(InstrItins->beginStage(SchedClass),
1004                       InstrItins->endStage(SchedClass))) {
1005         InstrStage::FuncUnits funcUnits = IS.getUnits();
1006         unsigned numAlternatives = countPopulation(funcUnits);
1007         if (numAlternatives < min) {
1008           min = numAlternatives;
1009           F = funcUnits;
1010         }
1011       }
1012       return min;
1013     }
1014     if (STI && STI->getSchedModel().hasInstrSchedModel()) {
1015       const MCSchedClassDesc *SCDesc =
1016           STI->getSchedModel().getSchedClassDesc(SchedClass);
1017       if (!SCDesc->isValid())
1018         // No valid Schedule Class Desc for schedClass, should be
1019         // Pseudo/PostRAPseudo
1020         return min;
1021 
1022       for (const MCWriteProcResEntry &PRE :
1023            make_range(STI->getWriteProcResBegin(SCDesc),
1024                       STI->getWriteProcResEnd(SCDesc))) {
1025         if (!PRE.Cycles)
1026           continue;
1027         const MCProcResourceDesc *ProcResource =
1028             STI->getSchedModel().getProcResource(PRE.ProcResourceIdx);
1029         unsigned NumUnits = ProcResource->NumUnits;
1030         if (NumUnits < min) {
1031           min = NumUnits;
1032           F = PRE.ProcResourceIdx;
1033         }
1034       }
1035       return min;
1036     }
1037     llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1038   }
1039 
1040   // Compute the critical resources needed by the instruction. This
1041   // function records the functional units needed by instructions that
1042   // must use only one functional unit. We use this as a tie breaker
1043   // for computing the resource MII. The instrutions that require
1044   // the same, highly used, functional unit have high priority.
1045   void calcCriticalResources(MachineInstr &MI) {
1046     unsigned SchedClass = MI.getDesc().getSchedClass();
1047     if (InstrItins && !InstrItins->isEmpty()) {
1048       for (const InstrStage &IS :
1049            make_range(InstrItins->beginStage(SchedClass),
1050                       InstrItins->endStage(SchedClass))) {
1051         InstrStage::FuncUnits FuncUnits = IS.getUnits();
1052         if (countPopulation(FuncUnits) == 1)
1053           Resources[FuncUnits]++;
1054       }
1055       return;
1056     }
1057     if (STI && STI->getSchedModel().hasInstrSchedModel()) {
1058       const MCSchedClassDesc *SCDesc =
1059           STI->getSchedModel().getSchedClassDesc(SchedClass);
1060       if (!SCDesc->isValid())
1061         // No valid Schedule Class Desc for schedClass, should be
1062         // Pseudo/PostRAPseudo
1063         return;
1064 
1065       for (const MCWriteProcResEntry &PRE :
1066            make_range(STI->getWriteProcResBegin(SCDesc),
1067                       STI->getWriteProcResEnd(SCDesc))) {
1068         if (!PRE.Cycles)
1069           continue;
1070         Resources[PRE.ProcResourceIdx]++;
1071       }
1072       return;
1073     }
1074     llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1075   }
1076 
1077   /// Return true if IS1 has less priority than IS2.
1078   bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
1079     InstrStage::FuncUnits F1 = 0, F2 = 0;
1080     unsigned MFUs1 = minFuncUnits(IS1, F1);
1081     unsigned MFUs2 = minFuncUnits(IS2, F2);
1082     if (MFUs1 == MFUs2)
1083       return Resources.lookup(F1) < Resources.lookup(F2);
1084     return MFUs1 > MFUs2;
1085   }
1086 };
1087 
1088 } // end anonymous namespace
1089 
1090 /// Calculate the resource constrained minimum initiation interval for the
1091 /// specified loop. We use the DFA to model the resources needed for
1092 /// each instruction, and we ignore dependences. A different DFA is created
1093 /// for each cycle that is required. When adding a new instruction, we attempt
1094 /// to add it to each existing DFA, until a legal space is found. If the
1095 /// instruction cannot be reserved in an existing DFA, we create a new one.
1096 unsigned SwingSchedulerDAG::calculateResMII() {
1097 
1098   LLVM_DEBUG(dbgs() << "calculateResMII:\n");
1099   SmallVector<ResourceManager*, 8> Resources;
1100   MachineBasicBlock *MBB = Loop.getHeader();
1101   Resources.push_back(new ResourceManager(&MF.getSubtarget()));
1102 
1103   // Sort the instructions by the number of available choices for scheduling,
1104   // least to most. Use the number of critical resources as the tie breaker.
1105   FuncUnitSorter FUS = FuncUnitSorter(MF.getSubtarget());
1106   for (MachineInstr &MI :
1107        llvm::make_range(MBB->getFirstNonPHI(), MBB->getFirstTerminator()))
1108     FUS.calcCriticalResources(MI);
1109   PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
1110       FuncUnitOrder(FUS);
1111 
1112   for (MachineInstr &MI :
1113        llvm::make_range(MBB->getFirstNonPHI(), MBB->getFirstTerminator()))
1114     FuncUnitOrder.push(&MI);
1115 
1116   while (!FuncUnitOrder.empty()) {
1117     MachineInstr *MI = FuncUnitOrder.top();
1118     FuncUnitOrder.pop();
1119     if (TII->isZeroCost(MI->getOpcode()))
1120       continue;
1121     // Attempt to reserve the instruction in an existing DFA. At least one
1122     // DFA is needed for each cycle.
1123     unsigned NumCycles = getSUnit(MI)->Latency;
1124     unsigned ReservedCycles = 0;
1125     SmallVectorImpl<ResourceManager *>::iterator RI = Resources.begin();
1126     SmallVectorImpl<ResourceManager *>::iterator RE = Resources.end();
1127     LLVM_DEBUG({
1128       dbgs() << "Trying to reserve resource for " << NumCycles
1129              << " cycles for \n";
1130       MI->dump();
1131     });
1132     for (unsigned C = 0; C < NumCycles; ++C)
1133       while (RI != RE) {
1134         if ((*RI)->canReserveResources(*MI)) {
1135           (*RI)->reserveResources(*MI);
1136           ++ReservedCycles;
1137           break;
1138         }
1139         RI++;
1140       }
1141     LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
1142                       << ", NumCycles:" << NumCycles << "\n");
1143     // Add new DFAs, if needed, to reserve resources.
1144     for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
1145       LLVM_DEBUG(if (SwpDebugResource) dbgs()
1146                  << "NewResource created to reserve resources"
1147                  << "\n");
1148       ResourceManager *NewResource = new ResourceManager(&MF.getSubtarget());
1149       assert(NewResource->canReserveResources(*MI) && "Reserve error.");
1150       NewResource->reserveResources(*MI);
1151       Resources.push_back(NewResource);
1152     }
1153   }
1154   int Resmii = Resources.size();
1155   LLVM_DEBUG(dbgs() << "Return Res MII:" << Resmii << "\n");
1156   // Delete the memory for each of the DFAs that were created earlier.
1157   for (ResourceManager *RI : Resources) {
1158     ResourceManager *D = RI;
1159     delete D;
1160   }
1161   Resources.clear();
1162   return Resmii;
1163 }
1164 
1165 /// Calculate the recurrence-constrainted minimum initiation interval.
1166 /// Iterate over each circuit.  Compute the delay(c) and distance(c)
1167 /// for each circuit. The II needs to satisfy the inequality
1168 /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
1169 /// II that satisfies the inequality, and the RecMII is the maximum
1170 /// of those values.
1171 unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1172   unsigned RecMII = 0;
1173 
1174   for (NodeSet &Nodes : NodeSets) {
1175     if (Nodes.empty())
1176       continue;
1177 
1178     unsigned Delay = Nodes.getLatency();
1179     unsigned Distance = 1;
1180 
1181     // ii = ceil(delay / distance)
1182     unsigned CurMII = (Delay + Distance - 1) / Distance;
1183     Nodes.setRecMII(CurMII);
1184     if (CurMII > RecMII)
1185       RecMII = CurMII;
1186   }
1187 
1188   return RecMII;
1189 }
1190 
1191 /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1192 /// but we do this to find the circuits, and then change them back.
1193 static void swapAntiDependences(std::vector<SUnit> &SUnits) {
1194   SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
1195   for (SUnit &SU : SUnits) {
1196     for (SDep &Pred : SU.Preds)
1197       if (Pred.getKind() == SDep::Anti)
1198         DepsAdded.push_back(std::make_pair(&SU, Pred));
1199   }
1200   for (std::pair<SUnit *, SDep> &P : DepsAdded) {
1201     // Remove this anti dependency and add one in the reverse direction.
1202     SUnit *SU = P.first;
1203     SDep &D = P.second;
1204     SUnit *TargetSU = D.getSUnit();
1205     unsigned Reg = D.getReg();
1206     unsigned Lat = D.getLatency();
1207     SU->removePred(D);
1208     SDep Dep(SU, SDep::Anti, Reg);
1209     Dep.setLatency(Lat);
1210     TargetSU->addPred(Dep);
1211   }
1212 }
1213 
1214 /// Create the adjacency structure of the nodes in the graph.
1215 void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1216     SwingSchedulerDAG *DAG) {
1217   BitVector Added(SUnits.size());
1218   DenseMap<int, int> OutputDeps;
1219   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1220     Added.reset();
1221     // Add any successor to the adjacency matrix and exclude duplicates.
1222     for (auto &SI : SUnits[i].Succs) {
1223       // Only create a back-edge on the first and last nodes of a dependence
1224       // chain. This records any chains and adds them later.
1225       if (SI.getKind() == SDep::Output) {
1226         int N = SI.getSUnit()->NodeNum;
1227         int BackEdge = i;
1228         auto Dep = OutputDeps.find(BackEdge);
1229         if (Dep != OutputDeps.end()) {
1230           BackEdge = Dep->second;
1231           OutputDeps.erase(Dep);
1232         }
1233         OutputDeps[N] = BackEdge;
1234       }
1235       // Do not process a boundary node, an artificial node.
1236       // A back-edge is processed only if it goes to a Phi.
1237       if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() ||
1238           (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
1239         continue;
1240       int N = SI.getSUnit()->NodeNum;
1241       if (!Added.test(N)) {
1242         AdjK[i].push_back(N);
1243         Added.set(N);
1244       }
1245     }
1246     // A chain edge between a store and a load is treated as a back-edge in the
1247     // adjacency matrix.
1248     for (auto &PI : SUnits[i].Preds) {
1249       if (!SUnits[i].getInstr()->mayStore() ||
1250           !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
1251         continue;
1252       if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1253         int N = PI.getSUnit()->NodeNum;
1254         if (!Added.test(N)) {
1255           AdjK[i].push_back(N);
1256           Added.set(N);
1257         }
1258       }
1259     }
1260   }
1261   // Add back-edges in the adjacency matrix for the output dependences.
1262   for (auto &OD : OutputDeps)
1263     if (!Added.test(OD.second)) {
1264       AdjK[OD.first].push_back(OD.second);
1265       Added.set(OD.second);
1266     }
1267 }
1268 
1269 /// Identify an elementary circuit in the dependence graph starting at the
1270 /// specified node.
1271 bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
1272                                           bool HasBackedge) {
1273   SUnit *SV = &SUnits[V];
1274   bool F = false;
1275   Stack.insert(SV);
1276   Blocked.set(V);
1277 
1278   for (auto W : AdjK[V]) {
1279     if (NumPaths > MaxPaths)
1280       break;
1281     if (W < S)
1282       continue;
1283     if (W == S) {
1284       if (!HasBackedge)
1285         NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
1286       F = true;
1287       ++NumPaths;
1288       break;
1289     } else if (!Blocked.test(W)) {
1290       if (circuit(W, S, NodeSets,
1291                   Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
1292         F = true;
1293     }
1294   }
1295 
1296   if (F)
1297     unblock(V);
1298   else {
1299     for (auto W : AdjK[V]) {
1300       if (W < S)
1301         continue;
1302       if (B[W].count(SV) == 0)
1303         B[W].insert(SV);
1304     }
1305   }
1306   Stack.pop_back();
1307   return F;
1308 }
1309 
1310 /// Unblock a node in the circuit finding algorithm.
1311 void SwingSchedulerDAG::Circuits::unblock(int U) {
1312   Blocked.reset(U);
1313   SmallPtrSet<SUnit *, 4> &BU = B[U];
1314   while (!BU.empty()) {
1315     SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
1316     assert(SI != BU.end() && "Invalid B set.");
1317     SUnit *W = *SI;
1318     BU.erase(W);
1319     if (Blocked.test(W->NodeNum))
1320       unblock(W->NodeNum);
1321   }
1322 }
1323 
1324 /// Identify all the elementary circuits in the dependence graph using
1325 /// Johnson's circuit algorithm.
1326 void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1327   // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1328   // but we do this to find the circuits, and then change them back.
1329   swapAntiDependences(SUnits);
1330 
1331   Circuits Cir(SUnits, Topo);
1332   // Create the adjacency structure.
1333   Cir.createAdjacencyStructure(this);
1334   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1335     Cir.reset();
1336     Cir.circuit(i, i, NodeSets);
1337   }
1338 
1339   // Change the dependences back so that we've created a DAG again.
1340   swapAntiDependences(SUnits);
1341 }
1342 
1343 // Create artificial dependencies between the source of COPY/REG_SEQUENCE that
1344 // is loop-carried to the USE in next iteration. This will help pipeliner avoid
1345 // additional copies that are needed across iterations. An artificial dependence
1346 // edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
1347 
1348 // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
1349 // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
1350 // PHI-------True-Dep------> USEOfPhi
1351 
1352 // The mutation creates
1353 // USEOfPHI -------Artificial-Dep---> SRCOfCopy
1354 
1355 // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
1356 // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
1357 // late  to avoid additional copies across iterations. The possible scheduling
1358 // order would be
1359 // USEOfPHI --- SRCOfCopy---  COPY/REG_SEQUENCE.
1360 
1361 void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
1362   for (SUnit &SU : DAG->SUnits) {
1363     // Find the COPY/REG_SEQUENCE instruction.
1364     if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
1365       continue;
1366 
1367     // Record the loop carried PHIs.
1368     SmallVector<SUnit *, 4> PHISUs;
1369     // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
1370     SmallVector<SUnit *, 4> SrcSUs;
1371 
1372     for (auto &Dep : SU.Preds) {
1373       SUnit *TmpSU = Dep.getSUnit();
1374       MachineInstr *TmpMI = TmpSU->getInstr();
1375       SDep::Kind DepKind = Dep.getKind();
1376       // Save the loop carried PHI.
1377       if (DepKind == SDep::Anti && TmpMI->isPHI())
1378         PHISUs.push_back(TmpSU);
1379       // Save the source of COPY/REG_SEQUENCE.
1380       // If the source has no pre-decessors, we will end up creating cycles.
1381       else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
1382         SrcSUs.push_back(TmpSU);
1383     }
1384 
1385     if (PHISUs.size() == 0 || SrcSUs.size() == 0)
1386       continue;
1387 
1388     // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
1389     // SUnit to the container.
1390     SmallVector<SUnit *, 8> UseSUs;
1391     // Do not use iterator based loop here as we are updating the container.
1392     for (size_t Index = 0; Index < PHISUs.size(); ++Index) {
1393       for (auto &Dep : PHISUs[Index]->Succs) {
1394         if (Dep.getKind() != SDep::Data)
1395           continue;
1396 
1397         SUnit *TmpSU = Dep.getSUnit();
1398         MachineInstr *TmpMI = TmpSU->getInstr();
1399         if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
1400           PHISUs.push_back(TmpSU);
1401           continue;
1402         }
1403         UseSUs.push_back(TmpSU);
1404       }
1405     }
1406 
1407     if (UseSUs.size() == 0)
1408       continue;
1409 
1410     SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
1411     // Add the artificial dependencies if it does not form a cycle.
1412     for (auto I : UseSUs) {
1413       for (auto Src : SrcSUs) {
1414         if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
1415           Src->addPred(SDep(I, SDep::Artificial));
1416           SDAG->Topo.AddPred(Src, I);
1417         }
1418       }
1419     }
1420   }
1421 }
1422 
1423 /// Return true for DAG nodes that we ignore when computing the cost functions.
1424 /// We ignore the back-edge recurrence in order to avoid unbounded recursion
1425 /// in the calculation of the ASAP, ALAP, etc functions.
1426 static bool ignoreDependence(const SDep &D, bool isPred) {
1427   if (D.isArtificial() || D.getSUnit()->isBoundaryNode())
1428     return true;
1429   return D.getKind() == SDep::Anti && isPred;
1430 }
1431 
1432 /// Compute several functions need to order the nodes for scheduling.
1433 ///  ASAP - Earliest time to schedule a node.
1434 ///  ALAP - Latest time to schedule a node.
1435 ///  MOV - Mobility function, difference between ALAP and ASAP.
1436 ///  D - Depth of each node.
1437 ///  H - Height of each node.
1438 void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
1439   ScheduleInfo.resize(SUnits.size());
1440 
1441   LLVM_DEBUG({
1442     for (int I : Topo) {
1443       const SUnit &SU = SUnits[I];
1444       dumpNode(SU);
1445     }
1446   });
1447 
1448   int maxASAP = 0;
1449   // Compute ASAP and ZeroLatencyDepth.
1450   for (int I : Topo) {
1451     int asap = 0;
1452     int zeroLatencyDepth = 0;
1453     SUnit *SU = &SUnits[I];
1454     for (const SDep &P : SU->Preds) {
1455       SUnit *pred = P.getSUnit();
1456       if (P.getLatency() == 0)
1457         zeroLatencyDepth =
1458             std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
1459       if (ignoreDependence(P, true))
1460         continue;
1461       asap = std::max(asap, (int)(getASAP(pred) + P.getLatency() -
1462                                   getDistance(pred, SU, P) * MII));
1463     }
1464     maxASAP = std::max(maxASAP, asap);
1465     ScheduleInfo[I].ASAP = asap;
1466     ScheduleInfo[I].ZeroLatencyDepth = zeroLatencyDepth;
1467   }
1468 
1469   // Compute ALAP, ZeroLatencyHeight, and MOV.
1470   for (int I : llvm::reverse(Topo)) {
1471     int alap = maxASAP;
1472     int zeroLatencyHeight = 0;
1473     SUnit *SU = &SUnits[I];
1474     for (const SDep &S : SU->Succs) {
1475       SUnit *succ = S.getSUnit();
1476       if (succ->isBoundaryNode())
1477         continue;
1478       if (S.getLatency() == 0)
1479         zeroLatencyHeight =
1480             std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
1481       if (ignoreDependence(S, true))
1482         continue;
1483       alap = std::min(alap, (int)(getALAP(succ) - S.getLatency() +
1484                                   getDistance(SU, succ, S) * MII));
1485     }
1486 
1487     ScheduleInfo[I].ALAP = alap;
1488     ScheduleInfo[I].ZeroLatencyHeight = zeroLatencyHeight;
1489   }
1490 
1491   // After computing the node functions, compute the summary for each node set.
1492   for (NodeSet &I : NodeSets)
1493     I.computeNodeSetInfo(this);
1494 
1495   LLVM_DEBUG({
1496     for (unsigned i = 0; i < SUnits.size(); i++) {
1497       dbgs() << "\tNode " << i << ":\n";
1498       dbgs() << "\t   ASAP = " << getASAP(&SUnits[i]) << "\n";
1499       dbgs() << "\t   ALAP = " << getALAP(&SUnits[i]) << "\n";
1500       dbgs() << "\t   MOV  = " << getMOV(&SUnits[i]) << "\n";
1501       dbgs() << "\t   D    = " << getDepth(&SUnits[i]) << "\n";
1502       dbgs() << "\t   H    = " << getHeight(&SUnits[i]) << "\n";
1503       dbgs() << "\t   ZLD  = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
1504       dbgs() << "\t   ZLH  = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
1505     }
1506   });
1507 }
1508 
1509 /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1510 /// as the predecessors of the elements of NodeOrder that are not also in
1511 /// NodeOrder.
1512 static bool pred_L(SetVector<SUnit *> &NodeOrder,
1513                    SmallSetVector<SUnit *, 8> &Preds,
1514                    const NodeSet *S = nullptr) {
1515   Preds.clear();
1516   for (const SUnit *SU : NodeOrder) {
1517     for (const SDep &Pred : SU->Preds) {
1518       if (S && S->count(Pred.getSUnit()) == 0)
1519         continue;
1520       if (ignoreDependence(Pred, true))
1521         continue;
1522       if (NodeOrder.count(Pred.getSUnit()) == 0)
1523         Preds.insert(Pred.getSUnit());
1524     }
1525     // Back-edges are predecessors with an anti-dependence.
1526     for (const SDep &Succ : SU->Succs) {
1527       if (Succ.getKind() != SDep::Anti)
1528         continue;
1529       if (S && S->count(Succ.getSUnit()) == 0)
1530         continue;
1531       if (NodeOrder.count(Succ.getSUnit()) == 0)
1532         Preds.insert(Succ.getSUnit());
1533     }
1534   }
1535   return !Preds.empty();
1536 }
1537 
1538 /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1539 /// as the successors of the elements of NodeOrder that are not also in
1540 /// NodeOrder.
1541 static bool succ_L(SetVector<SUnit *> &NodeOrder,
1542                    SmallSetVector<SUnit *, 8> &Succs,
1543                    const NodeSet *S = nullptr) {
1544   Succs.clear();
1545   for (const SUnit *SU : NodeOrder) {
1546     for (const SDep &Succ : SU->Succs) {
1547       if (S && S->count(Succ.getSUnit()) == 0)
1548         continue;
1549       if (ignoreDependence(Succ, false))
1550         continue;
1551       if (NodeOrder.count(Succ.getSUnit()) == 0)
1552         Succs.insert(Succ.getSUnit());
1553     }
1554     for (const SDep &Pred : SU->Preds) {
1555       if (Pred.getKind() != SDep::Anti)
1556         continue;
1557       if (S && S->count(Pred.getSUnit()) == 0)
1558         continue;
1559       if (NodeOrder.count(Pred.getSUnit()) == 0)
1560         Succs.insert(Pred.getSUnit());
1561     }
1562   }
1563   return !Succs.empty();
1564 }
1565 
1566 /// Return true if there is a path from the specified node to any of the nodes
1567 /// in DestNodes. Keep track and return the nodes in any path.
1568 static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
1569                         SetVector<SUnit *> &DestNodes,
1570                         SetVector<SUnit *> &Exclude,
1571                         SmallPtrSet<SUnit *, 8> &Visited) {
1572   if (Cur->isBoundaryNode())
1573     return false;
1574   if (Exclude.contains(Cur))
1575     return false;
1576   if (DestNodes.contains(Cur))
1577     return true;
1578   if (!Visited.insert(Cur).second)
1579     return Path.contains(Cur);
1580   bool FoundPath = false;
1581   for (auto &SI : Cur->Succs)
1582     if (!ignoreDependence(SI, false))
1583       FoundPath |=
1584           computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
1585   for (auto &PI : Cur->Preds)
1586     if (PI.getKind() == SDep::Anti)
1587       FoundPath |=
1588           computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
1589   if (FoundPath)
1590     Path.insert(Cur);
1591   return FoundPath;
1592 }
1593 
1594 /// Compute the live-out registers for the instructions in a node-set.
1595 /// The live-out registers are those that are defined in the node-set,
1596 /// but not used. Except for use operands of Phis.
1597 static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
1598                             NodeSet &NS) {
1599   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1600   MachineRegisterInfo &MRI = MF.getRegInfo();
1601   SmallVector<RegisterMaskPair, 8> LiveOutRegs;
1602   SmallSet<unsigned, 4> Uses;
1603   for (SUnit *SU : NS) {
1604     const MachineInstr *MI = SU->getInstr();
1605     if (MI->isPHI())
1606       continue;
1607     for (const MachineOperand &MO : MI->operands())
1608       if (MO.isReg() && MO.isUse()) {
1609         Register Reg = MO.getReg();
1610         if (Register::isVirtualRegister(Reg))
1611           Uses.insert(Reg);
1612         else if (MRI.isAllocatable(Reg))
1613           for (MCRegUnitIterator Units(Reg.asMCReg(), TRI); Units.isValid();
1614                ++Units)
1615             Uses.insert(*Units);
1616       }
1617   }
1618   for (SUnit *SU : NS)
1619     for (const MachineOperand &MO : SU->getInstr()->operands())
1620       if (MO.isReg() && MO.isDef() && !MO.isDead()) {
1621         Register Reg = MO.getReg();
1622         if (Register::isVirtualRegister(Reg)) {
1623           if (!Uses.count(Reg))
1624             LiveOutRegs.push_back(RegisterMaskPair(Reg,
1625                                                    LaneBitmask::getNone()));
1626         } else if (MRI.isAllocatable(Reg)) {
1627           for (MCRegUnitIterator Units(Reg.asMCReg(), TRI); Units.isValid();
1628                ++Units)
1629             if (!Uses.count(*Units))
1630               LiveOutRegs.push_back(RegisterMaskPair(*Units,
1631                                                      LaneBitmask::getNone()));
1632         }
1633       }
1634   RPTracker.addLiveRegs(LiveOutRegs);
1635 }
1636 
1637 /// A heuristic to filter nodes in recurrent node-sets if the register
1638 /// pressure of a set is too high.
1639 void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
1640   for (auto &NS : NodeSets) {
1641     // Skip small node-sets since they won't cause register pressure problems.
1642     if (NS.size() <= 2)
1643       continue;
1644     IntervalPressure RecRegPressure;
1645     RegPressureTracker RecRPTracker(RecRegPressure);
1646     RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
1647     computeLiveOuts(MF, RecRPTracker, NS);
1648     RecRPTracker.closeBottom();
1649 
1650     std::vector<SUnit *> SUnits(NS.begin(), NS.end());
1651     llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
1652       return A->NodeNum > B->NodeNum;
1653     });
1654 
1655     for (auto &SU : SUnits) {
1656       // Since we're computing the register pressure for a subset of the
1657       // instructions in a block, we need to set the tracker for each
1658       // instruction in the node-set. The tracker is set to the instruction
1659       // just after the one we're interested in.
1660       MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
1661       RecRPTracker.setPos(std::next(CurInstI));
1662 
1663       RegPressureDelta RPDelta;
1664       ArrayRef<PressureChange> CriticalPSets;
1665       RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
1666                                              CriticalPSets,
1667                                              RecRegPressure.MaxSetPressure);
1668       if (RPDelta.Excess.isValid()) {
1669         LLVM_DEBUG(
1670             dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
1671                    << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
1672                    << ":" << RPDelta.Excess.getUnitInc());
1673         NS.setExceedPressure(SU);
1674         break;
1675       }
1676       RecRPTracker.recede();
1677     }
1678   }
1679 }
1680 
1681 /// A heuristic to colocate node sets that have the same set of
1682 /// successors.
1683 void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
1684   unsigned Colocate = 0;
1685   for (int i = 0, e = NodeSets.size(); i < e; ++i) {
1686     NodeSet &N1 = NodeSets[i];
1687     SmallSetVector<SUnit *, 8> S1;
1688     if (N1.empty() || !succ_L(N1, S1))
1689       continue;
1690     for (int j = i + 1; j < e; ++j) {
1691       NodeSet &N2 = NodeSets[j];
1692       if (N1.compareRecMII(N2) != 0)
1693         continue;
1694       SmallSetVector<SUnit *, 8> S2;
1695       if (N2.empty() || !succ_L(N2, S2))
1696         continue;
1697       if (llvm::set_is_subset(S1, S2) && S1.size() == S2.size()) {
1698         N1.setColocate(++Colocate);
1699         N2.setColocate(Colocate);
1700         break;
1701       }
1702     }
1703   }
1704 }
1705 
1706 /// Check if the existing node-sets are profitable. If not, then ignore the
1707 /// recurrent node-sets, and attempt to schedule all nodes together. This is
1708 /// a heuristic. If the MII is large and all the recurrent node-sets are small,
1709 /// then it's best to try to schedule all instructions together instead of
1710 /// starting with the recurrent node-sets.
1711 void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
1712   // Look for loops with a large MII.
1713   if (MII < 17)
1714     return;
1715   // Check if the node-set contains only a simple add recurrence.
1716   for (auto &NS : NodeSets) {
1717     if (NS.getRecMII() > 2)
1718       return;
1719     if (NS.getMaxDepth() > MII)
1720       return;
1721   }
1722   NodeSets.clear();
1723   LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
1724 }
1725 
1726 /// Add the nodes that do not belong to a recurrence set into groups
1727 /// based upon connected components.
1728 void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
1729   SetVector<SUnit *> NodesAdded;
1730   SmallPtrSet<SUnit *, 8> Visited;
1731   // Add the nodes that are on a path between the previous node sets and
1732   // the current node set.
1733   for (NodeSet &I : NodeSets) {
1734     SmallSetVector<SUnit *, 8> N;
1735     // Add the nodes from the current node set to the previous node set.
1736     if (succ_L(I, N)) {
1737       SetVector<SUnit *> Path;
1738       for (SUnit *NI : N) {
1739         Visited.clear();
1740         computePath(NI, Path, NodesAdded, I, Visited);
1741       }
1742       if (!Path.empty())
1743         I.insert(Path.begin(), Path.end());
1744     }
1745     // Add the nodes from the previous node set to the current node set.
1746     N.clear();
1747     if (succ_L(NodesAdded, N)) {
1748       SetVector<SUnit *> Path;
1749       for (SUnit *NI : N) {
1750         Visited.clear();
1751         computePath(NI, Path, I, NodesAdded, Visited);
1752       }
1753       if (!Path.empty())
1754         I.insert(Path.begin(), Path.end());
1755     }
1756     NodesAdded.insert(I.begin(), I.end());
1757   }
1758 
1759   // Create a new node set with the connected nodes of any successor of a node
1760   // in a recurrent set.
1761   NodeSet NewSet;
1762   SmallSetVector<SUnit *, 8> N;
1763   if (succ_L(NodesAdded, N))
1764     for (SUnit *I : N)
1765       addConnectedNodes(I, NewSet, NodesAdded);
1766   if (!NewSet.empty())
1767     NodeSets.push_back(NewSet);
1768 
1769   // Create a new node set with the connected nodes of any predecessor of a node
1770   // in a recurrent set.
1771   NewSet.clear();
1772   if (pred_L(NodesAdded, N))
1773     for (SUnit *I : N)
1774       addConnectedNodes(I, NewSet, NodesAdded);
1775   if (!NewSet.empty())
1776     NodeSets.push_back(NewSet);
1777 
1778   // Create new nodes sets with the connected nodes any remaining node that
1779   // has no predecessor.
1780   for (SUnit &SU : SUnits) {
1781     if (NodesAdded.count(&SU) == 0) {
1782       NewSet.clear();
1783       addConnectedNodes(&SU, NewSet, NodesAdded);
1784       if (!NewSet.empty())
1785         NodeSets.push_back(NewSet);
1786     }
1787   }
1788 }
1789 
1790 /// Add the node to the set, and add all of its connected nodes to the set.
1791 void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
1792                                           SetVector<SUnit *> &NodesAdded) {
1793   NewSet.insert(SU);
1794   NodesAdded.insert(SU);
1795   for (auto &SI : SU->Succs) {
1796     SUnit *Successor = SI.getSUnit();
1797     if (!SI.isArtificial() && !Successor->isBoundaryNode() &&
1798         NodesAdded.count(Successor) == 0)
1799       addConnectedNodes(Successor, NewSet, NodesAdded);
1800   }
1801   for (auto &PI : SU->Preds) {
1802     SUnit *Predecessor = PI.getSUnit();
1803     if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
1804       addConnectedNodes(Predecessor, NewSet, NodesAdded);
1805   }
1806 }
1807 
1808 /// Return true if Set1 contains elements in Set2. The elements in common
1809 /// are returned in a different container.
1810 static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
1811                         SmallSetVector<SUnit *, 8> &Result) {
1812   Result.clear();
1813   for (SUnit *SU : Set1) {
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