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