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