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