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