1 //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
11 //
12 // Software pipelining (SWP) is an instruction scheduling technique for loops
13 // that overlap loop iterations and exploits ILP via a compiler transformation.
14 //
15 // Swing Modulo Scheduling is an implementation of software pipelining
16 // that generates schedules that are near optimal in terms of initiation
17 // interval, register requirements, and stage count. See the papers:
18 //
19 // "Swing Modulo Scheduling: A Lifetime-Sensitive Approach", by J. Llosa,
20 // A. Gonzalez, E. Ayguade, and M. Valero. In PACT '96 Processings of the 1996
21 // Conference on Parallel Architectures and Compilation Techiniques.
22 //
23 // "Lifetime-Sensitive Modulo Scheduling in a Production Environment", by J.
24 // Llosa, E. Ayguade, A. Gonzalez, M. Valero, and J. Eckhardt. In IEEE
25 // Transactions on Computers, Vol. 50, No. 3, 2001.
26 //
27 // "An Implementation of Swing Modulo Scheduling With Extensions for
28 // Superblocks", by T. Lattner, Master's Thesis, University of Illinois at
29 // Urbana-Chambpain, 2005.
30 //
31 //
32 // The SMS algorithm consists of three main steps after computing the minimal
33 // initiation interval (MII).
34 // 1) Analyze the dependence graph and compute information about each
35 //    instruction in the graph.
36 // 2) Order the nodes (instructions) by priority based upon the heuristics
37 //    described in the algorithm.
38 // 3) Attempt to schedule the nodes in the specified order using the MII.
39 //
40 // This SMS implementation is a target-independent back-end pass. When enabled,
41 // the pass runs just prior to the register allocation pass, while the machine
42 // IR is in SSA form. If software pipelining is successful, then the original
43 // loop is replaced by the optimized loop. The optimized loop contains one or
44 // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
45 // the instructions cannot be scheduled in a given MII, we increase the MII by
46 // one and try again.
47 //
48 // The SMS implementation is an extension of the ScheduleDAGInstrs class. We
49 // represent loop carried dependences in the DAG as order edges to the Phi
50 // nodes. We also perform several passes over the DAG to eliminate unnecessary
51 // edges that inhibit the ability to pipeline. The implementation uses the
52 // DFAPacketizer class to compute the minimum initiation interval and the check
53 // where an instruction may be inserted in the pipelined schedule.
54 //
55 // In order for the SMS pass to work, several target specific hooks need to be
56 // implemented to get information about the loop structure and to rewrite
57 // instructions.
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #include "llvm/ADT/ArrayRef.h"
62 #include "llvm/ADT/BitVector.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/MapVector.h"
65 #include "llvm/ADT/PriorityQueue.h"
66 #include "llvm/ADT/SetVector.h"
67 #include "llvm/ADT/SmallPtrSet.h"
68 #include "llvm/ADT/SmallSet.h"
69 #include "llvm/ADT/SmallVector.h"
70 #include "llvm/ADT/Statistic.h"
71 #include "llvm/ADT/iterator_range.h"
72 #include "llvm/Analysis/AliasAnalysis.h"
73 #include "llvm/Analysis/MemoryLocation.h"
74 #include "llvm/Analysis/ValueTracking.h"
75 #include "llvm/CodeGen/DFAPacketizer.h"
76 #include "llvm/CodeGen/LiveIntervals.h"
77 #include "llvm/CodeGen/MachineBasicBlock.h"
78 #include "llvm/CodeGen/MachineDominators.h"
79 #include "llvm/CodeGen/MachineFunction.h"
80 #include "llvm/CodeGen/MachineFunctionPass.h"
81 #include "llvm/CodeGen/MachineInstr.h"
82 #include "llvm/CodeGen/MachineInstrBuilder.h"
83 #include "llvm/CodeGen/MachineLoopInfo.h"
84 #include "llvm/CodeGen/MachineMemOperand.h"
85 #include "llvm/CodeGen/MachineOperand.h"
86 #include "llvm/CodeGen/MachineRegisterInfo.h"
87 #include "llvm/CodeGen/RegisterClassInfo.h"
88 #include "llvm/CodeGen/RegisterPressure.h"
89 #include "llvm/CodeGen/ScheduleDAG.h"
90 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
91 #include "llvm/CodeGen/ScheduleDAGMutation.h"
92 #include "llvm/CodeGen/TargetInstrInfo.h"
93 #include "llvm/CodeGen/TargetOpcodes.h"
94 #include "llvm/CodeGen/TargetRegisterInfo.h"
95 #include "llvm/CodeGen/TargetSubtargetInfo.h"
96 #include "llvm/IR/Attributes.h"
97 #include "llvm/IR/DebugLoc.h"
98 #include "llvm/IR/Function.h"
99 #include "llvm/MC/LaneBitmask.h"
100 #include "llvm/MC/MCInstrDesc.h"
101 #include "llvm/MC/MCInstrItineraries.h"
102 #include "llvm/MC/MCRegisterInfo.h"
103 #include "llvm/Pass.h"
104 #include "llvm/Support/CommandLine.h"
105 #include "llvm/Support/Compiler.h"
106 #include "llvm/Support/Debug.h"
107 #include "llvm/Support/MathExtras.h"
108 #include "llvm/Support/raw_ostream.h"
109 #include <algorithm>
110 #include <cassert>
111 #include <climits>
112 #include <cstdint>
113 #include <deque>
114 #include <functional>
115 #include <iterator>
116 #include <map>
117 #include <memory>
118 #include <tuple>
119 #include <utility>
120 #include <vector>
121 
122 using namespace llvm;
123 
124 #define DEBUG_TYPE "pipeliner"
125 
126 STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
127 STATISTIC(NumPipelined, "Number of loops software pipelined");
128 STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
129 
130 /// A command line option to turn software pipelining on or off.
131 static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
132                                cl::ZeroOrMore,
133                                cl::desc("Enable Software Pipelining"));
134 
135 /// A command line option to enable SWP at -Os.
136 static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
137                                       cl::desc("Enable SWP at Os."), cl::Hidden,
138                                       cl::init(false));
139 
140 /// A command line argument to limit minimum initial interval for pipelining.
141 static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
142                               cl::desc("Size limit for the MII."),
143                               cl::Hidden, cl::init(27));
144 
145 /// A command line argument to limit the number of stages in the pipeline.
146 static cl::opt<int>
147     SwpMaxStages("pipeliner-max-stages",
148                  cl::desc("Maximum stages allowed in the generated scheduled."),
149                  cl::Hidden, cl::init(3));
150 
151 /// A command line option to disable the pruning of chain dependences due to
152 /// an unrelated Phi.
153 static cl::opt<bool>
154     SwpPruneDeps("pipeliner-prune-deps",
155                  cl::desc("Prune dependences between unrelated Phi nodes."),
156                  cl::Hidden, cl::init(true));
157 
158 /// A command line option to disable the pruning of loop carried order
159 /// dependences.
160 static cl::opt<bool>
161     SwpPruneLoopCarried("pipeliner-prune-loop-carried",
162                         cl::desc("Prune loop carried order dependences."),
163                         cl::Hidden, cl::init(true));
164 
165 #ifndef NDEBUG
166 static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
167 #endif
168 
169 static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
170                                      cl::ReallyHidden, cl::init(false),
171                                      cl::ZeroOrMore, cl::desc("Ignore RecMII"));
172 
173 namespace {
174 
175 class NodeSet;
176 class SMSchedule;
177 
178 /// The main class in the implementation of the target independent
179 /// software pipeliner pass.
180 class MachinePipeliner : public MachineFunctionPass {
181 public:
182   MachineFunction *MF = nullptr;
183   const MachineLoopInfo *MLI = nullptr;
184   const MachineDominatorTree *MDT = nullptr;
185   const InstrItineraryData *InstrItins;
186   const TargetInstrInfo *TII = nullptr;
187   RegisterClassInfo RegClassInfo;
188 
189 #ifndef NDEBUG
190   static int NumTries;
191 #endif
192 
193   /// Cache the target analysis information about the loop.
194   struct LoopInfo {
195     MachineBasicBlock *TBB = nullptr;
196     MachineBasicBlock *FBB = nullptr;
197     SmallVector<MachineOperand, 4> BrCond;
198     MachineInstr *LoopInductionVar = nullptr;
199     MachineInstr *LoopCompare = nullptr;
200   };
201   LoopInfo LI;
202 
203   static char ID;
204 
205   MachinePipeliner() : MachineFunctionPass(ID) {
206     initializeMachinePipelinerPass(*PassRegistry::getPassRegistry());
207   }
208 
209   bool runOnMachineFunction(MachineFunction &MF) override;
210 
211   void getAnalysisUsage(AnalysisUsage &AU) const override {
212     AU.addRequired<AAResultsWrapperPass>();
213     AU.addPreserved<AAResultsWrapperPass>();
214     AU.addRequired<MachineLoopInfo>();
215     AU.addRequired<MachineDominatorTree>();
216     AU.addRequired<LiveIntervals>();
217     MachineFunctionPass::getAnalysisUsage(AU);
218   }
219 
220 private:
221   void preprocessPhiNodes(MachineBasicBlock &B);
222   bool canPipelineLoop(MachineLoop &L);
223   bool scheduleLoop(MachineLoop &L);
224   bool swingModuloScheduler(MachineLoop &L);
225 };
226 
227 /// This class builds the dependence graph for the instructions in a loop,
228 /// and attempts to schedule the instructions using the SMS algorithm.
229 class SwingSchedulerDAG : public ScheduleDAGInstrs {
230   MachinePipeliner &Pass;
231   /// The minimum initiation interval between iterations for this schedule.
232   unsigned MII = 0;
233   /// Set to true if a valid pipelined schedule is found for the loop.
234   bool Scheduled = false;
235   MachineLoop &Loop;
236   LiveIntervals &LIS;
237   const RegisterClassInfo &RegClassInfo;
238 
239   /// A toplogical ordering of the SUnits, which is needed for changing
240   /// dependences and iterating over the SUnits.
241   ScheduleDAGTopologicalSort Topo;
242 
243   struct NodeInfo {
244     int ASAP = 0;
245     int ALAP = 0;
246     int ZeroLatencyDepth = 0;
247     int ZeroLatencyHeight = 0;
248 
249     NodeInfo() = default;
250   };
251   /// Computed properties for each node in the graph.
252   std::vector<NodeInfo> ScheduleInfo;
253 
254   enum OrderKind { BottomUp = 0, TopDown = 1 };
255   /// Computed node ordering for scheduling.
256   SetVector<SUnit *> NodeOrder;
257 
258   using NodeSetType = SmallVector<NodeSet, 8>;
259   using ValueMapTy = DenseMap<unsigned, unsigned>;
260   using MBBVectorTy = SmallVectorImpl<MachineBasicBlock *>;
261   using InstrMapTy = DenseMap<MachineInstr *, MachineInstr *>;
262 
263   /// Instructions to change when emitting the final schedule.
264   DenseMap<SUnit *, std::pair<unsigned, int64_t>> InstrChanges;
265 
266   /// We may create a new instruction, so remember it because it
267   /// must be deleted when the pass is finished.
268   SmallPtrSet<MachineInstr *, 4> NewMIs;
269 
270   /// Ordered list of DAG postprocessing steps.
271   std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
272 
273   /// Helper class to implement Johnson's circuit finding algorithm.
274   class Circuits {
275     std::vector<SUnit> &SUnits;
276     SetVector<SUnit *> Stack;
277     BitVector Blocked;
278     SmallVector<SmallPtrSet<SUnit *, 4>, 10> B;
279     SmallVector<SmallVector<int, 4>, 16> AdjK;
280     unsigned NumPaths;
281     static unsigned MaxPaths;
282 
283   public:
284     Circuits(std::vector<SUnit> &SUs)
285         : SUnits(SUs), Blocked(SUs.size()), B(SUs.size()), AdjK(SUs.size()) {}
286 
287     /// Reset the data structures used in the circuit algorithm.
288     void reset() {
289       Stack.clear();
290       Blocked.reset();
291       B.assign(SUnits.size(), SmallPtrSet<SUnit *, 4>());
292       NumPaths = 0;
293     }
294 
295     void createAdjacencyStructure(SwingSchedulerDAG *DAG);
296     bool circuit(int V, int S, NodeSetType &NodeSets, bool HasBackedge = false);
297     void unblock(int U);
298   };
299 
300 public:
301   SwingSchedulerDAG(MachinePipeliner &P, MachineLoop &L, LiveIntervals &lis,
302                     const RegisterClassInfo &rci)
303       : ScheduleDAGInstrs(*P.MF, P.MLI, false), Pass(P), Loop(L), LIS(lis),
304         RegClassInfo(rci), Topo(SUnits, &ExitSU) {
305     P.MF->getSubtarget().getSMSMutations(Mutations);
306   }
307 
308   void schedule() override;
309   void finishBlock() override;
310 
311   /// Return true if the loop kernel has been scheduled.
312   bool hasNewSchedule() { return Scheduled; }
313 
314   /// Return the earliest time an instruction may be scheduled.
315   int getASAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ASAP; }
316 
317   /// Return the latest time an instruction my be scheduled.
318   int getALAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ALAP; }
319 
320   /// The mobility function, which the number of slots in which
321   /// an instruction may be scheduled.
322   int getMOV(SUnit *Node) { return getALAP(Node) - getASAP(Node); }
323 
324   /// The depth, in the dependence graph, for a node.
325   unsigned getDepth(SUnit *Node) { return Node->getDepth(); }
326 
327   /// The maximum unweighted length of a path from an arbitrary node to the
328   /// given node in which each edge has latency 0
329   int getZeroLatencyDepth(SUnit *Node) {
330     return ScheduleInfo[Node->NodeNum].ZeroLatencyDepth;
331   }
332 
333   /// The height, in the dependence graph, for a node.
334   unsigned getHeight(SUnit *Node) { return Node->getHeight(); }
335 
336   /// The maximum unweighted length of a path from the given node to an
337   /// arbitrary node in which each edge has latency 0
338   int getZeroLatencyHeight(SUnit *Node) {
339     return ScheduleInfo[Node->NodeNum].ZeroLatencyHeight;
340   }
341 
342   /// Return true if the dependence is a back-edge in the data dependence graph.
343   /// Since the DAG doesn't contain cycles, we represent a cycle in the graph
344   /// using an anti dependence from a Phi to an instruction.
345   bool isBackedge(SUnit *Source, const SDep &Dep) {
346     if (Dep.getKind() != SDep::Anti)
347       return false;
348     return Source->getInstr()->isPHI() || Dep.getSUnit()->getInstr()->isPHI();
349   }
350 
351   bool isLoopCarriedDep(SUnit *Source, const SDep &Dep, bool isSucc = true);
352 
353   /// The distance function, which indicates that operation V of iteration I
354   /// depends on operations U of iteration I-distance.
355   unsigned getDistance(SUnit *U, SUnit *V, const SDep &Dep) {
356     // Instructions that feed a Phi have a distance of 1. Computing larger
357     // values for arrays requires data dependence information.
358     if (V->getInstr()->isPHI() && Dep.getKind() == SDep::Anti)
359       return 1;
360     return 0;
361   }
362 
363   /// Set the Minimum Initiation Interval for this schedule attempt.
364   void setMII(unsigned mii) { MII = mii; }
365 
366   void applyInstrChange(MachineInstr *MI, SMSchedule &Schedule);
367 
368   void fixupRegisterOverlaps(std::deque<SUnit *> &Instrs);
369 
370   /// Return the new base register that was stored away for the changed
371   /// instruction.
372   unsigned getInstrBaseReg(SUnit *SU) {
373     DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
374         InstrChanges.find(SU);
375     if (It != InstrChanges.end())
376       return It->second.first;
377     return 0;
378   }
379 
380   void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) {
381     Mutations.push_back(std::move(Mutation));
382   }
383 
384 private:
385   void addLoopCarriedDependences(AliasAnalysis *AA);
386   void updatePhiDependences();
387   void changeDependences();
388   unsigned calculateResMII();
389   unsigned calculateRecMII(NodeSetType &RecNodeSets);
390   void findCircuits(NodeSetType &NodeSets);
391   void fuseRecs(NodeSetType &NodeSets);
392   void removeDuplicateNodes(NodeSetType &NodeSets);
393   void computeNodeFunctions(NodeSetType &NodeSets);
394   void registerPressureFilter(NodeSetType &NodeSets);
395   void colocateNodeSets(NodeSetType &NodeSets);
396   void checkNodeSets(NodeSetType &NodeSets);
397   void groupRemainingNodes(NodeSetType &NodeSets);
398   void addConnectedNodes(SUnit *SU, NodeSet &NewSet,
399                          SetVector<SUnit *> &NodesAdded);
400   void computeNodeOrder(NodeSetType &NodeSets);
401   void checkValidNodeOrder(const NodeSetType &Circuits) const;
402   bool schedulePipeline(SMSchedule &Schedule);
403   void generatePipelinedLoop(SMSchedule &Schedule);
404   void generateProlog(SMSchedule &Schedule, unsigned LastStage,
405                       MachineBasicBlock *KernelBB, ValueMapTy *VRMap,
406                       MBBVectorTy &PrologBBs);
407   void generateEpilog(SMSchedule &Schedule, unsigned LastStage,
408                       MachineBasicBlock *KernelBB, ValueMapTy *VRMap,
409                       MBBVectorTy &EpilogBBs, MBBVectorTy &PrologBBs);
410   void generateExistingPhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1,
411                             MachineBasicBlock *BB2, MachineBasicBlock *KernelBB,
412                             SMSchedule &Schedule, ValueMapTy *VRMap,
413                             InstrMapTy &InstrMap, unsigned LastStageNum,
414                             unsigned CurStageNum, bool IsLast);
415   void generatePhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1,
416                     MachineBasicBlock *BB2, MachineBasicBlock *KernelBB,
417                     SMSchedule &Schedule, ValueMapTy *VRMap,
418                     InstrMapTy &InstrMap, unsigned LastStageNum,
419                     unsigned CurStageNum, bool IsLast);
420   void removeDeadInstructions(MachineBasicBlock *KernelBB,
421                               MBBVectorTy &EpilogBBs);
422   void splitLifetimes(MachineBasicBlock *KernelBB, MBBVectorTy &EpilogBBs,
423                       SMSchedule &Schedule);
424   void addBranches(MBBVectorTy &PrologBBs, MachineBasicBlock *KernelBB,
425                    MBBVectorTy &EpilogBBs, SMSchedule &Schedule,
426                    ValueMapTy *VRMap);
427   bool computeDelta(MachineInstr &MI, unsigned &Delta);
428   void updateMemOperands(MachineInstr &NewMI, MachineInstr &OldMI,
429                          unsigned Num);
430   MachineInstr *cloneInstr(MachineInstr *OldMI, unsigned CurStageNum,
431                            unsigned InstStageNum);
432   MachineInstr *cloneAndChangeInstr(MachineInstr *OldMI, unsigned CurStageNum,
433                                     unsigned InstStageNum,
434                                     SMSchedule &Schedule);
435   void updateInstruction(MachineInstr *NewMI, bool LastDef,
436                          unsigned CurStageNum, unsigned InstStageNum,
437                          SMSchedule &Schedule, ValueMapTy *VRMap);
438   MachineInstr *findDefInLoop(unsigned Reg);
439   unsigned getPrevMapVal(unsigned StageNum, unsigned PhiStage, unsigned LoopVal,
440                          unsigned LoopStage, ValueMapTy *VRMap,
441                          MachineBasicBlock *BB);
442   void rewritePhiValues(MachineBasicBlock *NewBB, unsigned StageNum,
443                         SMSchedule &Schedule, ValueMapTy *VRMap,
444                         InstrMapTy &InstrMap);
445   void rewriteScheduledInstr(MachineBasicBlock *BB, SMSchedule &Schedule,
446                              InstrMapTy &InstrMap, unsigned CurStageNum,
447                              unsigned PhiNum, MachineInstr *Phi,
448                              unsigned OldReg, unsigned NewReg,
449                              unsigned PrevReg = 0);
450   bool canUseLastOffsetValue(MachineInstr *MI, unsigned &BasePos,
451                              unsigned &OffsetPos, unsigned &NewBase,
452                              int64_t &NewOffset);
453   void postprocessDAG();
454 };
455 
456 /// A NodeSet contains a set of SUnit DAG nodes with additional information
457 /// that assigns a priority to the set.
458 class NodeSet {
459   SetVector<SUnit *> Nodes;
460   bool HasRecurrence = false;
461   unsigned RecMII = 0;
462   int MaxMOV = 0;
463   unsigned MaxDepth = 0;
464   unsigned Colocate = 0;
465   SUnit *ExceedPressure = nullptr;
466   unsigned Latency = 0;
467 
468 public:
469   using iterator = SetVector<SUnit *>::const_iterator;
470 
471   NodeSet() = default;
472   NodeSet(iterator S, iterator E) : Nodes(S, E), HasRecurrence(true) {
473     Latency = 0;
474     for (unsigned i = 0, e = Nodes.size(); i < e; ++i)
475       for (const SDep &Succ : Nodes[i]->Succs)
476         if (Nodes.count(Succ.getSUnit()))
477           Latency += Succ.getLatency();
478   }
479 
480   bool insert(SUnit *SU) { return Nodes.insert(SU); }
481 
482   void insert(iterator S, iterator E) { Nodes.insert(S, E); }
483 
484   template <typename UnaryPredicate> bool remove_if(UnaryPredicate P) {
485     return Nodes.remove_if(P);
486   }
487 
488   unsigned count(SUnit *SU) const { return Nodes.count(SU); }
489 
490   bool hasRecurrence() { return HasRecurrence; };
491 
492   unsigned size() const { return Nodes.size(); }
493 
494   bool empty() const { return Nodes.empty(); }
495 
496   SUnit *getNode(unsigned i) const { return Nodes[i]; };
497 
498   void setRecMII(unsigned mii) { RecMII = mii; };
499 
500   void setColocate(unsigned c) { Colocate = c; };
501 
502   void setExceedPressure(SUnit *SU) { ExceedPressure = SU; }
503 
504   bool isExceedSU(SUnit *SU) { return ExceedPressure == SU; }
505 
506   int compareRecMII(NodeSet &RHS) { return RecMII - RHS.RecMII; }
507 
508   int getRecMII() { return RecMII; }
509 
510   /// Summarize node functions for the entire node set.
511   void computeNodeSetInfo(SwingSchedulerDAG *SSD) {
512     for (SUnit *SU : *this) {
513       MaxMOV = std::max(MaxMOV, SSD->getMOV(SU));
514       MaxDepth = std::max(MaxDepth, SSD->getDepth(SU));
515     }
516   }
517 
518   unsigned getLatency() { return Latency; }
519 
520   unsigned getMaxDepth() { return MaxDepth; }
521 
522   void clear() {
523     Nodes.clear();
524     RecMII = 0;
525     HasRecurrence = false;
526     MaxMOV = 0;
527     MaxDepth = 0;
528     Colocate = 0;
529     ExceedPressure = nullptr;
530   }
531 
532   operator SetVector<SUnit *> &() { return Nodes; }
533 
534   /// Sort the node sets by importance. First, rank them by recurrence MII,
535   /// then by mobility (least mobile done first), and finally by depth.
536   /// Each node set may contain a colocate value which is used as the first
537   /// tie breaker, if it's set.
538   bool operator>(const NodeSet &RHS) const {
539     if (RecMII == RHS.RecMII) {
540       if (Colocate != 0 && RHS.Colocate != 0 && Colocate != RHS.Colocate)
541         return Colocate < RHS.Colocate;
542       if (MaxMOV == RHS.MaxMOV)
543         return MaxDepth > RHS.MaxDepth;
544       return MaxMOV < RHS.MaxMOV;
545     }
546     return RecMII > RHS.RecMII;
547   }
548 
549   bool operator==(const NodeSet &RHS) const {
550     return RecMII == RHS.RecMII && MaxMOV == RHS.MaxMOV &&
551            MaxDepth == RHS.MaxDepth;
552   }
553 
554   bool operator!=(const NodeSet &RHS) const { return !operator==(RHS); }
555 
556   iterator begin() { return Nodes.begin(); }
557   iterator end() { return Nodes.end(); }
558 
559   void print(raw_ostream &os) const {
560     os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
561        << " depth " << MaxDepth << " col " << Colocate << "\n";
562     for (const auto &I : Nodes)
563       os << "   SU(" << I->NodeNum << ") " << *(I->getInstr());
564     os << "\n";
565   }
566 
567 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
568   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
569 #endif
570 };
571 
572 /// This class repesents the scheduled code.  The main data structure is a
573 /// map from scheduled cycle to instructions.  During scheduling, the
574 /// data structure explicitly represents all stages/iterations.   When
575 /// the algorithm finshes, the schedule is collapsed into a single stage,
576 /// which represents instructions from different loop iterations.
577 ///
578 /// The SMS algorithm allows negative values for cycles, so the first cycle
579 /// in the schedule is the smallest cycle value.
580 class SMSchedule {
581 private:
582   /// Map from execution cycle to instructions.
583   DenseMap<int, std::deque<SUnit *>> ScheduledInstrs;
584 
585   /// Map from instruction to execution cycle.
586   std::map<SUnit *, int> InstrToCycle;
587 
588   /// Map for each register and the max difference between its uses and def.
589   /// The first element in the pair is the max difference in stages. The
590   /// second is true if the register defines a Phi value and loop value is
591   /// scheduled before the Phi.
592   std::map<unsigned, std::pair<unsigned, bool>> RegToStageDiff;
593 
594   /// Keep track of the first cycle value in the schedule.  It starts
595   /// as zero, but the algorithm allows negative values.
596   int FirstCycle = 0;
597 
598   /// Keep track of the last cycle value in the schedule.
599   int LastCycle = 0;
600 
601   /// The initiation interval (II) for the schedule.
602   int InitiationInterval = 0;
603 
604   /// Target machine information.
605   const TargetSubtargetInfo &ST;
606 
607   /// Virtual register information.
608   MachineRegisterInfo &MRI;
609 
610   std::unique_ptr<DFAPacketizer> Resources;
611 
612 public:
613   SMSchedule(MachineFunction *mf)
614       : ST(mf->getSubtarget()), MRI(mf->getRegInfo()),
615         Resources(ST.getInstrInfo()->CreateTargetScheduleState(ST)) {}
616 
617   void reset() {
618     ScheduledInstrs.clear();
619     InstrToCycle.clear();
620     RegToStageDiff.clear();
621     FirstCycle = 0;
622     LastCycle = 0;
623     InitiationInterval = 0;
624   }
625 
626   /// Set the initiation interval for this schedule.
627   void setInitiationInterval(int ii) { InitiationInterval = ii; }
628 
629   /// Return the first cycle in the completed schedule.  This
630   /// can be a negative value.
631   int getFirstCycle() const { return FirstCycle; }
632 
633   /// Return the last cycle in the finalized schedule.
634   int getFinalCycle() const { return FirstCycle + InitiationInterval - 1; }
635 
636   /// Return the cycle of the earliest scheduled instruction in the dependence
637   /// chain.
638   int earliestCycleInChain(const SDep &Dep);
639 
640   /// Return the cycle of the latest scheduled instruction in the dependence
641   /// chain.
642   int latestCycleInChain(const SDep &Dep);
643 
644   void computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
645                     int *MinEnd, int *MaxStart, int II, SwingSchedulerDAG *DAG);
646   bool insert(SUnit *SU, int StartCycle, int EndCycle, int II);
647 
648   /// Iterators for the cycle to instruction map.
649   using sched_iterator = DenseMap<int, std::deque<SUnit *>>::iterator;
650   using const_sched_iterator =
651       DenseMap<int, std::deque<SUnit *>>::const_iterator;
652 
653   /// Return true if the instruction is scheduled at the specified stage.
654   bool isScheduledAtStage(SUnit *SU, unsigned StageNum) {
655     return (stageScheduled(SU) == (int)StageNum);
656   }
657 
658   /// Return the stage for a scheduled instruction.  Return -1 if
659   /// the instruction has not been scheduled.
660   int stageScheduled(SUnit *SU) const {
661     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
662     if (it == InstrToCycle.end())
663       return -1;
664     return (it->second - FirstCycle) / InitiationInterval;
665   }
666 
667   /// Return the cycle for a scheduled instruction. This function normalizes
668   /// the first cycle to be 0.
669   unsigned cycleScheduled(SUnit *SU) const {
670     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
671     assert(it != InstrToCycle.end() && "Instruction hasn't been scheduled.");
672     return (it->second - FirstCycle) % InitiationInterval;
673   }
674 
675   /// Return the maximum stage count needed for this schedule.
676   unsigned getMaxStageCount() {
677     return (LastCycle - FirstCycle) / InitiationInterval;
678   }
679 
680   /// Return the max. number of stages/iterations that can occur between a
681   /// register definition and its uses.
682   unsigned getStagesForReg(int Reg, unsigned CurStage) {
683     std::pair<unsigned, bool> Stages = RegToStageDiff[Reg];
684     if (CurStage > getMaxStageCount() && Stages.first == 0 && Stages.second)
685       return 1;
686     return Stages.first;
687   }
688 
689   /// The number of stages for a Phi is a little different than other
690   /// instructions. The minimum value computed in RegToStageDiff is 1
691   /// because we assume the Phi is needed for at least 1 iteration.
692   /// This is not the case if the loop value is scheduled prior to the
693   /// Phi in the same stage.  This function returns the number of stages
694   /// or iterations needed between the Phi definition and any uses.
695   unsigned getStagesForPhi(int Reg) {
696     std::pair<unsigned, bool> Stages = RegToStageDiff[Reg];
697     if (Stages.second)
698       return Stages.first;
699     return Stages.first - 1;
700   }
701 
702   /// Return the instructions that are scheduled at the specified cycle.
703   std::deque<SUnit *> &getInstructions(int cycle) {
704     return ScheduledInstrs[cycle];
705   }
706 
707   bool isValidSchedule(SwingSchedulerDAG *SSD);
708   void finalizeSchedule(SwingSchedulerDAG *SSD);
709   void orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
710                        std::deque<SUnit *> &Insts);
711   bool isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi);
712   bool isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD, MachineInstr *Inst,
713                              MachineOperand &MO);
714   void print(raw_ostream &os) const;
715   void dump() const;
716 };
717 
718 } // end anonymous namespace
719 
720 unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
721 char MachinePipeliner::ID = 0;
722 #ifndef NDEBUG
723 int MachinePipeliner::NumTries = 0;
724 #endif
725 char &llvm::MachinePipelinerID = MachinePipeliner::ID;
726 
727 INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
728                       "Modulo Software Pipelining", false, false)
729 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
730 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
731 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
732 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
733 INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
734                     "Modulo Software Pipelining", false, false)
735 
736 /// The "main" function for implementing Swing Modulo Scheduling.
737 bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
738   if (skipFunction(mf.getFunction()))
739     return false;
740 
741   if (!EnableSWP)
742     return false;
743 
744   if (mf.getFunction().getAttributes().hasAttribute(
745           AttributeList::FunctionIndex, Attribute::OptimizeForSize) &&
746       !EnableSWPOptSize.getPosition())
747     return false;
748 
749   MF = &mf;
750   MLI = &getAnalysis<MachineLoopInfo>();
751   MDT = &getAnalysis<MachineDominatorTree>();
752   TII = MF->getSubtarget().getInstrInfo();
753   RegClassInfo.runOnMachineFunction(*MF);
754 
755   for (auto &L : *MLI)
756     scheduleLoop(*L);
757 
758   return false;
759 }
760 
761 /// Attempt to perform the SMS algorithm on the specified loop. This function is
762 /// the main entry point for the algorithm.  The function identifies candidate
763 /// loops, calculates the minimum initiation interval, and attempts to schedule
764 /// the loop.
765 bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
766   bool Changed = false;
767   for (auto &InnerLoop : L)
768     Changed |= scheduleLoop(*InnerLoop);
769 
770 #ifndef NDEBUG
771   // Stop trying after reaching the limit (if any).
772   int Limit = SwpLoopLimit;
773   if (Limit >= 0) {
774     if (NumTries >= SwpLoopLimit)
775       return Changed;
776     NumTries++;
777   }
778 #endif
779 
780   if (!canPipelineLoop(L))
781     return Changed;
782 
783   ++NumTrytoPipeline;
784 
785   Changed = swingModuloScheduler(L);
786 
787   return Changed;
788 }
789 
790 /// Return true if the loop can be software pipelined.  The algorithm is
791 /// restricted to loops with a single basic block.  Make sure that the
792 /// branch in the loop can be analyzed.
793 bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
794   if (L.getNumBlocks() != 1)
795     return false;
796 
797   // Check if the branch can't be understood because we can't do pipelining
798   // if that's the case.
799   LI.TBB = nullptr;
800   LI.FBB = nullptr;
801   LI.BrCond.clear();
802   if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond))
803     return false;
804 
805   LI.LoopInductionVar = nullptr;
806   LI.LoopCompare = nullptr;
807   if (TII->analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare))
808     return false;
809 
810   if (!L.getLoopPreheader())
811     return false;
812 
813   // Remove any subregisters from inputs to phi nodes.
814   preprocessPhiNodes(*L.getHeader());
815   return true;
816 }
817 
818 void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
819   MachineRegisterInfo &MRI = MF->getRegInfo();
820   SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
821 
822   for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) {
823     MachineOperand &DefOp = PI.getOperand(0);
824     assert(DefOp.getSubReg() == 0);
825     auto *RC = MRI.getRegClass(DefOp.getReg());
826 
827     for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
828       MachineOperand &RegOp = PI.getOperand(i);
829       if (RegOp.getSubReg() == 0)
830         continue;
831 
832       // If the operand uses a subregister, replace it with a new register
833       // without subregisters, and generate a copy to the new register.
834       unsigned NewReg = MRI.createVirtualRegister(RC);
835       MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
836       MachineBasicBlock::iterator At = PredB.getFirstTerminator();
837       const DebugLoc &DL = PredB.findDebugLoc(At);
838       auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
839                     .addReg(RegOp.getReg(), getRegState(RegOp),
840                             RegOp.getSubReg());
841       Slots.insertMachineInstrInMaps(*Copy);
842       RegOp.setReg(NewReg);
843       RegOp.setSubReg(0);
844     }
845   }
846 }
847 
848 /// The SMS algorithm consists of the following main steps:
849 /// 1. Computation and analysis of the dependence graph.
850 /// 2. Ordering of the nodes (instructions).
851 /// 3. Attempt to Schedule the loop.
852 bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
853   assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
854 
855   SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo);
856 
857   MachineBasicBlock *MBB = L.getHeader();
858   // The kernel should not include any terminator instructions.  These
859   // will be added back later.
860   SMS.startBlock(MBB);
861 
862   // Compute the number of 'real' instructions in the basic block by
863   // ignoring terminators.
864   unsigned size = MBB->size();
865   for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
866                                    E = MBB->instr_end();
867        I != E; ++I, --size)
868     ;
869 
870   SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
871   SMS.schedule();
872   SMS.exitRegion();
873 
874   SMS.finishBlock();
875   return SMS.hasNewSchedule();
876 }
877 
878 /// We override the schedule function in ScheduleDAGInstrs to implement the
879 /// scheduling part of the Swing Modulo Scheduling algorithm.
880 void SwingSchedulerDAG::schedule() {
881   AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
882   buildSchedGraph(AA);
883   addLoopCarriedDependences(AA);
884   updatePhiDependences();
885   Topo.InitDAGTopologicalSorting();
886   postprocessDAG();
887   changeDependences();
888   DEBUG({
889     for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
890       SUnits[su].dumpAll(this);
891   });
892 
893   NodeSetType NodeSets;
894   findCircuits(NodeSets);
895   NodeSetType Circuits = NodeSets;
896 
897   // Calculate the MII.
898   unsigned ResMII = calculateResMII();
899   unsigned RecMII = calculateRecMII(NodeSets);
900 
901   fuseRecs(NodeSets);
902 
903   // This flag is used for testing and can cause correctness problems.
904   if (SwpIgnoreRecMII)
905     RecMII = 0;
906 
907   MII = std::max(ResMII, RecMII);
908   DEBUG(dbgs() << "MII = " << MII << " (rec=" << RecMII << ", res=" << ResMII
909                << ")\n");
910 
911   // Can't schedule a loop without a valid MII.
912   if (MII == 0)
913     return;
914 
915   // Don't pipeline large loops.
916   if (SwpMaxMii != -1 && (int)MII > SwpMaxMii)
917     return;
918 
919   computeNodeFunctions(NodeSets);
920 
921   registerPressureFilter(NodeSets);
922 
923   colocateNodeSets(NodeSets);
924 
925   checkNodeSets(NodeSets);
926 
927   DEBUG({
928     for (auto &I : NodeSets) {
929       dbgs() << "  Rec NodeSet ";
930       I.dump();
931     }
932   });
933 
934   llvm::sort(NodeSets.begin(), NodeSets.end(), std::greater<NodeSet>());
935 
936   groupRemainingNodes(NodeSets);
937 
938   removeDuplicateNodes(NodeSets);
939 
940   DEBUG({
941     for (auto &I : NodeSets) {
942       dbgs() << "  NodeSet ";
943       I.dump();
944     }
945   });
946 
947   computeNodeOrder(NodeSets);
948 
949   // check for node order issues
950   checkValidNodeOrder(Circuits);
951 
952   SMSchedule Schedule(Pass.MF);
953   Scheduled = schedulePipeline(Schedule);
954 
955   if (!Scheduled)
956     return;
957 
958   unsigned numStages = Schedule.getMaxStageCount();
959   // No need to generate pipeline if there are no overlapped iterations.
960   if (numStages == 0)
961     return;
962 
963   // Check that the maximum stage count is less than user-defined limit.
964   if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages)
965     return;
966 
967   generatePipelinedLoop(Schedule);
968   ++NumPipelined;
969 }
970 
971 /// Clean up after the software pipeliner runs.
972 void SwingSchedulerDAG::finishBlock() {
973   for (MachineInstr *I : NewMIs)
974     MF.DeleteMachineInstr(I);
975   NewMIs.clear();
976 
977   // Call the superclass.
978   ScheduleDAGInstrs::finishBlock();
979 }
980 
981 /// Return the register values for  the operands of a Phi instruction.
982 /// This function assume the instruction is a Phi.
983 static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
984                        unsigned &InitVal, unsigned &LoopVal) {
985   assert(Phi.isPHI() && "Expecting a Phi.");
986 
987   InitVal = 0;
988   LoopVal = 0;
989   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
990     if (Phi.getOperand(i + 1).getMBB() != Loop)
991       InitVal = Phi.getOperand(i).getReg();
992     else
993       LoopVal = Phi.getOperand(i).getReg();
994 
995   assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
996 }
997 
998 /// Return the Phi register value that comes from the incoming block.
999 static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
1000   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
1001     if (Phi.getOperand(i + 1).getMBB() != LoopBB)
1002       return Phi.getOperand(i).getReg();
1003   return 0;
1004 }
1005 
1006 /// Return the Phi register value that comes the loop block.
1007 static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
1008   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
1009     if (Phi.getOperand(i + 1).getMBB() == LoopBB)
1010       return Phi.getOperand(i).getReg();
1011   return 0;
1012 }
1013 
1014 /// Return true if SUb can be reached from SUa following the chain edges.
1015 static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
1016   SmallPtrSet<SUnit *, 8> Visited;
1017   SmallVector<SUnit *, 8> Worklist;
1018   Worklist.push_back(SUa);
1019   while (!Worklist.empty()) {
1020     const SUnit *SU = Worklist.pop_back_val();
1021     for (auto &SI : SU->Succs) {
1022       SUnit *SuccSU = SI.getSUnit();
1023       if (SI.getKind() == SDep::Order) {
1024         if (Visited.count(SuccSU))
1025           continue;
1026         if (SuccSU == SUb)
1027           return true;
1028         Worklist.push_back(SuccSU);
1029         Visited.insert(SuccSU);
1030       }
1031     }
1032   }
1033   return false;
1034 }
1035 
1036 /// Return true if the instruction causes a chain between memory
1037 /// references before and after it.
1038 static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
1039   return MI.isCall() || MI.hasUnmodeledSideEffects() ||
1040          (MI.hasOrderedMemoryRef() &&
1041           (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
1042 }
1043 
1044 /// Return the underlying objects for the memory references of an instruction.
1045 /// This function calls the code in ValueTracking, but first checks that the
1046 /// instruction has a memory operand.
1047 static void getUnderlyingObjects(MachineInstr *MI,
1048                                  SmallVectorImpl<Value *> &Objs,
1049                                  const DataLayout &DL) {
1050   if (!MI->hasOneMemOperand())
1051     return;
1052   MachineMemOperand *MM = *MI->memoperands_begin();
1053   if (!MM->getValue())
1054     return;
1055   GetUnderlyingObjects(const_cast<Value *>(MM->getValue()), Objs, DL);
1056   for (Value *V : Objs) {
1057     if (!isIdentifiedObject(V)) {
1058       Objs.clear();
1059       return;
1060     }
1061     Objs.push_back(V);
1062   }
1063 }
1064 
1065 /// Add a chain edge between a load and store if the store can be an
1066 /// alias of the load on a subsequent iteration, i.e., a loop carried
1067 /// dependence. This code is very similar to the code in ScheduleDAGInstrs
1068 /// but that code doesn't create loop carried dependences.
1069 void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
1070   MapVector<Value *, SmallVector<SUnit *, 4>> PendingLoads;
1071   Value *UnknownValue =
1072     UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
1073   for (auto &SU : SUnits) {
1074     MachineInstr &MI = *SU.getInstr();
1075     if (isDependenceBarrier(MI, AA))
1076       PendingLoads.clear();
1077     else if (MI.mayLoad()) {
1078       SmallVector<Value *, 4> Objs;
1079       getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
1080       if (Objs.empty())
1081         Objs.push_back(UnknownValue);
1082       for (auto V : Objs) {
1083         SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
1084         SUs.push_back(&SU);
1085       }
1086     } else if (MI.mayStore()) {
1087       SmallVector<Value *, 4> Objs;
1088       getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
1089       if (Objs.empty())
1090         Objs.push_back(UnknownValue);
1091       for (auto V : Objs) {
1092         MapVector<Value *, SmallVector<SUnit *, 4>>::iterator I =
1093             PendingLoads.find(V);
1094         if (I == PendingLoads.end())
1095           continue;
1096         for (auto Load : I->second) {
1097           if (isSuccOrder(Load, &SU))
1098             continue;
1099           MachineInstr &LdMI = *Load->getInstr();
1100           // First, perform the cheaper check that compares the base register.
1101           // If they are the same and the load offset is less than the store
1102           // offset, then mark the dependence as loop carried potentially.
1103           unsigned BaseReg1, BaseReg2;
1104           int64_t Offset1, Offset2;
1105           if (TII->getMemOpBaseRegImmOfs(LdMI, BaseReg1, Offset1, TRI) &&
1106               TII->getMemOpBaseRegImmOfs(MI, BaseReg2, Offset2, TRI)) {
1107             if (BaseReg1 == BaseReg2 && (int)Offset1 < (int)Offset2) {
1108               assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI, AA) &&
1109                      "What happened to the chain edge?");
1110               SDep Dep(Load, SDep::Barrier);
1111               Dep.setLatency(1);
1112               SU.addPred(Dep);
1113               continue;
1114             }
1115           }
1116           // Second, the more expensive check that uses alias analysis on the
1117           // base registers. If they alias, and the load offset is less than
1118           // the store offset, the mark the dependence as loop carried.
1119           if (!AA) {
1120             SDep Dep(Load, SDep::Barrier);
1121             Dep.setLatency(1);
1122             SU.addPred(Dep);
1123             continue;
1124           }
1125           MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
1126           MachineMemOperand *MMO2 = *MI.memoperands_begin();
1127           if (!MMO1->getValue() || !MMO2->getValue()) {
1128             SDep Dep(Load, SDep::Barrier);
1129             Dep.setLatency(1);
1130             SU.addPred(Dep);
1131             continue;
1132           }
1133           if (MMO1->getValue() == MMO2->getValue() &&
1134               MMO1->getOffset() <= MMO2->getOffset()) {
1135             SDep Dep(Load, SDep::Barrier);
1136             Dep.setLatency(1);
1137             SU.addPred(Dep);
1138             continue;
1139           }
1140           AliasResult AAResult = AA->alias(
1141               MemoryLocation(MMO1->getValue(), MemoryLocation::UnknownSize,
1142                              MMO1->getAAInfo()),
1143               MemoryLocation(MMO2->getValue(), MemoryLocation::UnknownSize,
1144                              MMO2->getAAInfo()));
1145 
1146           if (AAResult != NoAlias) {
1147             SDep Dep(Load, SDep::Barrier);
1148             Dep.setLatency(1);
1149             SU.addPred(Dep);
1150           }
1151         }
1152       }
1153     }
1154   }
1155 }
1156 
1157 /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
1158 /// processes dependences for PHIs. This function adds true dependences
1159 /// from a PHI to a use, and a loop carried dependence from the use to the
1160 /// PHI. The loop carried dependence is represented as an anti dependence
1161 /// edge. This function also removes chain dependences between unrelated
1162 /// PHIs.
1163 void SwingSchedulerDAG::updatePhiDependences() {
1164   SmallVector<SDep, 4> RemoveDeps;
1165   const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
1166 
1167   // Iterate over each DAG node.
1168   for (SUnit &I : SUnits) {
1169     RemoveDeps.clear();
1170     // Set to true if the instruction has an operand defined by a Phi.
1171     unsigned HasPhiUse = 0;
1172     unsigned HasPhiDef = 0;
1173     MachineInstr *MI = I.getInstr();
1174     // Iterate over each operand, and we process the definitions.
1175     for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
1176                                     MOE = MI->operands_end();
1177          MOI != MOE; ++MOI) {
1178       if (!MOI->isReg())
1179         continue;
1180       unsigned Reg = MOI->getReg();
1181       if (MOI->isDef()) {
1182         // If the register is used by a Phi, then create an anti dependence.
1183         for (MachineRegisterInfo::use_instr_iterator
1184                  UI = MRI.use_instr_begin(Reg),
1185                  UE = MRI.use_instr_end();
1186              UI != UE; ++UI) {
1187           MachineInstr *UseMI = &*UI;
1188           SUnit *SU = getSUnit(UseMI);
1189           if (SU != nullptr && UseMI->isPHI()) {
1190             if (!MI->isPHI()) {
1191               SDep Dep(SU, SDep::Anti, Reg);
1192               Dep.setLatency(1);
1193               I.addPred(Dep);
1194             } else {
1195               HasPhiDef = Reg;
1196               // Add a chain edge to a dependent Phi that isn't an existing
1197               // predecessor.
1198               if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
1199                 I.addPred(SDep(SU, SDep::Barrier));
1200             }
1201           }
1202         }
1203       } else if (MOI->isUse()) {
1204         // If the register is defined by a Phi, then create a true dependence.
1205         MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
1206         if (DefMI == nullptr)
1207           continue;
1208         SUnit *SU = getSUnit(DefMI);
1209         if (SU != nullptr && DefMI->isPHI()) {
1210           if (!MI->isPHI()) {
1211             SDep Dep(SU, SDep::Data, Reg);
1212             Dep.setLatency(0);
1213             ST.adjustSchedDependency(SU, &I, Dep);
1214             I.addPred(Dep);
1215           } else {
1216             HasPhiUse = Reg;
1217             // Add a chain edge to a dependent Phi that isn't an existing
1218             // predecessor.
1219             if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
1220               I.addPred(SDep(SU, SDep::Barrier));
1221           }
1222         }
1223       }
1224     }
1225     // Remove order dependences from an unrelated Phi.
1226     if (!SwpPruneDeps)
1227       continue;
1228     for (auto &PI : I.Preds) {
1229       MachineInstr *PMI = PI.getSUnit()->getInstr();
1230       if (PMI->isPHI() && PI.getKind() == SDep::Order) {
1231         if (I.getInstr()->isPHI()) {
1232           if (PMI->getOperand(0).getReg() == HasPhiUse)
1233             continue;
1234           if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
1235             continue;
1236         }
1237         RemoveDeps.push_back(PI);
1238       }
1239     }
1240     for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
1241       I.removePred(RemoveDeps[i]);
1242   }
1243 }
1244 
1245 /// Iterate over each DAG node and see if we can change any dependences
1246 /// in order to reduce the recurrence MII.
1247 void SwingSchedulerDAG::changeDependences() {
1248   // See if an instruction can use a value from the previous iteration.
1249   // If so, we update the base and offset of the instruction and change
1250   // the dependences.
1251   for (SUnit &I : SUnits) {
1252     unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
1253     int64_t NewOffset = 0;
1254     if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
1255                                NewOffset))
1256       continue;
1257 
1258     // Get the MI and SUnit for the instruction that defines the original base.
1259     unsigned OrigBase = I.getInstr()->getOperand(BasePos).getReg();
1260     MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
1261     if (!DefMI)
1262       continue;
1263     SUnit *DefSU = getSUnit(DefMI);
1264     if (!DefSU)
1265       continue;
1266     // Get the MI and SUnit for the instruction that defins the new base.
1267     MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
1268     if (!LastMI)
1269       continue;
1270     SUnit *LastSU = getSUnit(LastMI);
1271     if (!LastSU)
1272       continue;
1273 
1274     if (Topo.IsReachable(&I, LastSU))
1275       continue;
1276 
1277     // Remove the dependence. The value now depends on a prior iteration.
1278     SmallVector<SDep, 4> Deps;
1279     for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E;
1280          ++P)
1281       if (P->getSUnit() == DefSU)
1282         Deps.push_back(*P);
1283     for (int i = 0, e = Deps.size(); i != e; i++) {
1284       Topo.RemovePred(&I, Deps[i].getSUnit());
1285       I.removePred(Deps[i]);
1286     }
1287     // Remove the chain dependence between the instructions.
1288     Deps.clear();
1289     for (auto &P : LastSU->Preds)
1290       if (P.getSUnit() == &I && P.getKind() == SDep::Order)
1291         Deps.push_back(P);
1292     for (int i = 0, e = Deps.size(); i != e; i++) {
1293       Topo.RemovePred(LastSU, Deps[i].getSUnit());
1294       LastSU->removePred(Deps[i]);
1295     }
1296 
1297     // Add a dependence between the new instruction and the instruction
1298     // that defines the new base.
1299     SDep Dep(&I, SDep::Anti, NewBase);
1300     LastSU->addPred(Dep);
1301 
1302     // Remember the base and offset information so that we can update the
1303     // instruction during code generation.
1304     InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
1305   }
1306 }
1307 
1308 namespace {
1309 
1310 // FuncUnitSorter - Comparison operator used to sort instructions by
1311 // the number of functional unit choices.
1312 struct FuncUnitSorter {
1313   const InstrItineraryData *InstrItins;
1314   DenseMap<unsigned, unsigned> Resources;
1315 
1316   FuncUnitSorter(const InstrItineraryData *IID) : InstrItins(IID) {}
1317 
1318   // Compute the number of functional unit alternatives needed
1319   // at each stage, and take the minimum value. We prioritize the
1320   // instructions by the least number of choices first.
1321   unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const {
1322     unsigned schedClass = Inst->getDesc().getSchedClass();
1323     unsigned min = UINT_MAX;
1324     for (const InstrStage *IS = InstrItins->beginStage(schedClass),
1325                           *IE = InstrItins->endStage(schedClass);
1326          IS != IE; ++IS) {
1327       unsigned funcUnits = IS->getUnits();
1328       unsigned numAlternatives = countPopulation(funcUnits);
1329       if (numAlternatives < min) {
1330         min = numAlternatives;
1331         F = funcUnits;
1332       }
1333     }
1334     return min;
1335   }
1336 
1337   // Compute the critical resources needed by the instruction. This
1338   // function records the functional units needed by instructions that
1339   // must use only one functional unit. We use this as a tie breaker
1340   // for computing the resource MII. The instrutions that require
1341   // the same, highly used, functional unit have high priority.
1342   void calcCriticalResources(MachineInstr &MI) {
1343     unsigned SchedClass = MI.getDesc().getSchedClass();
1344     for (const InstrStage *IS = InstrItins->beginStage(SchedClass),
1345                           *IE = InstrItins->endStage(SchedClass);
1346          IS != IE; ++IS) {
1347       unsigned FuncUnits = IS->getUnits();
1348       if (countPopulation(FuncUnits) == 1)
1349         Resources[FuncUnits]++;
1350     }
1351   }
1352 
1353   /// Return true if IS1 has less priority than IS2.
1354   bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
1355     unsigned F1 = 0, F2 = 0;
1356     unsigned MFUs1 = minFuncUnits(IS1, F1);
1357     unsigned MFUs2 = minFuncUnits(IS2, F2);
1358     if (MFUs1 == 1 && MFUs2 == 1)
1359       return Resources.lookup(F1) < Resources.lookup(F2);
1360     return MFUs1 > MFUs2;
1361   }
1362 };
1363 
1364 } // end anonymous namespace
1365 
1366 /// Calculate the resource constrained minimum initiation interval for the
1367 /// specified loop. We use the DFA to model the resources needed for
1368 /// each instruction, and we ignore dependences. A different DFA is created
1369 /// for each cycle that is required. When adding a new instruction, we attempt
1370 /// to add it to each existing DFA, until a legal space is found. If the
1371 /// instruction cannot be reserved in an existing DFA, we create a new one.
1372 unsigned SwingSchedulerDAG::calculateResMII() {
1373   SmallVector<DFAPacketizer *, 8> Resources;
1374   MachineBasicBlock *MBB = Loop.getHeader();
1375   Resources.push_back(TII->CreateTargetScheduleState(MF.getSubtarget()));
1376 
1377   // Sort the instructions by the number of available choices for scheduling,
1378   // least to most. Use the number of critical resources as the tie breaker.
1379   FuncUnitSorter FUS =
1380       FuncUnitSorter(MF.getSubtarget().getInstrItineraryData());
1381   for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
1382                                    E = MBB->getFirstTerminator();
1383        I != E; ++I)
1384     FUS.calcCriticalResources(*I);
1385   PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
1386       FuncUnitOrder(FUS);
1387 
1388   for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
1389                                    E = MBB->getFirstTerminator();
1390        I != E; ++I)
1391     FuncUnitOrder.push(&*I);
1392 
1393   while (!FuncUnitOrder.empty()) {
1394     MachineInstr *MI = FuncUnitOrder.top();
1395     FuncUnitOrder.pop();
1396     if (TII->isZeroCost(MI->getOpcode()))
1397       continue;
1398     // Attempt to reserve the instruction in an existing DFA. At least one
1399     // DFA is needed for each cycle.
1400     unsigned NumCycles = getSUnit(MI)->Latency;
1401     unsigned ReservedCycles = 0;
1402     SmallVectorImpl<DFAPacketizer *>::iterator RI = Resources.begin();
1403     SmallVectorImpl<DFAPacketizer *>::iterator RE = Resources.end();
1404     for (unsigned C = 0; C < NumCycles; ++C)
1405       while (RI != RE) {
1406         if ((*RI++)->canReserveResources(*MI)) {
1407           ++ReservedCycles;
1408           break;
1409         }
1410       }
1411     // Start reserving resources using existing DFAs.
1412     for (unsigned C = 0; C < ReservedCycles; ++C) {
1413       --RI;
1414       (*RI)->reserveResources(*MI);
1415     }
1416     // Add new DFAs, if needed, to reserve resources.
1417     for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
1418       DFAPacketizer *NewResource =
1419           TII->CreateTargetScheduleState(MF.getSubtarget());
1420       assert(NewResource->canReserveResources(*MI) && "Reserve error.");
1421       NewResource->reserveResources(*MI);
1422       Resources.push_back(NewResource);
1423     }
1424   }
1425   int Resmii = Resources.size();
1426   // Delete the memory for each of the DFAs that were created earlier.
1427   for (DFAPacketizer *RI : Resources) {
1428     DFAPacketizer *D = RI;
1429     delete D;
1430   }
1431   Resources.clear();
1432   return Resmii;
1433 }
1434 
1435 /// Calculate the recurrence-constrainted minimum initiation interval.
1436 /// Iterate over each circuit.  Compute the delay(c) and distance(c)
1437 /// for each circuit. The II needs to satisfy the inequality
1438 /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
1439 /// II that satistifies the inequality, and the RecMII is the maximum
1440 /// of those values.
1441 unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1442   unsigned RecMII = 0;
1443 
1444   for (NodeSet &Nodes : NodeSets) {
1445     if (Nodes.empty())
1446       continue;
1447 
1448     unsigned Delay = Nodes.getLatency();
1449     unsigned Distance = 1;
1450 
1451     // ii = ceil(delay / distance)
1452     unsigned CurMII = (Delay + Distance - 1) / Distance;
1453     Nodes.setRecMII(CurMII);
1454     if (CurMII > RecMII)
1455       RecMII = CurMII;
1456   }
1457 
1458   return RecMII;
1459 }
1460 
1461 /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1462 /// but we do this to find the circuits, and then change them back.
1463 static void swapAntiDependences(std::vector<SUnit> &SUnits) {
1464   SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
1465   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1466     SUnit *SU = &SUnits[i];
1467     for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end();
1468          IP != EP; ++IP) {
1469       if (IP->getKind() != SDep::Anti)
1470         continue;
1471       DepsAdded.push_back(std::make_pair(SU, *IP));
1472     }
1473   }
1474   for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(),
1475                                                           E = DepsAdded.end();
1476        I != E; ++I) {
1477     // Remove this anti dependency and add one in the reverse direction.
1478     SUnit *SU = I->first;
1479     SDep &D = I->second;
1480     SUnit *TargetSU = D.getSUnit();
1481     unsigned Reg = D.getReg();
1482     unsigned Lat = D.getLatency();
1483     SU->removePred(D);
1484     SDep Dep(SU, SDep::Anti, Reg);
1485     Dep.setLatency(Lat);
1486     TargetSU->addPred(Dep);
1487   }
1488 }
1489 
1490 /// Create the adjacency structure of the nodes in the graph.
1491 void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1492     SwingSchedulerDAG *DAG) {
1493   BitVector Added(SUnits.size());
1494   DenseMap<int, int> OutputDeps;
1495   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1496     Added.reset();
1497     // Add any successor to the adjacency matrix and exclude duplicates.
1498     for (auto &SI : SUnits[i].Succs) {
1499       // Only create a back-edge on the first and last nodes of a dependence
1500       // chain. This records any chains and adds them later.
1501       if (SI.getKind() == SDep::Output) {
1502         int N = SI.getSUnit()->NodeNum;
1503         int BackEdge = i;
1504         auto Dep = OutputDeps.find(BackEdge);
1505         if (Dep != OutputDeps.end()) {
1506           BackEdge = Dep->second;
1507           OutputDeps.erase(Dep);
1508         }
1509         OutputDeps[N] = BackEdge;
1510       }
1511       // Do not process a boundary node and a back-edge is processed only
1512       // if it goes to a Phi.
1513       if (SI.getSUnit()->isBoundaryNode() ||
1514           (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
1515         continue;
1516       int N = SI.getSUnit()->NodeNum;
1517       if (!Added.test(N)) {
1518         AdjK[i].push_back(N);
1519         Added.set(N);
1520       }
1521     }
1522     // A chain edge between a store and a load is treated as a back-edge in the
1523     // adjacency matrix.
1524     for (auto &PI : SUnits[i].Preds) {
1525       if (!SUnits[i].getInstr()->mayStore() ||
1526           !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
1527         continue;
1528       if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1529         int N = PI.getSUnit()->NodeNum;
1530         if (!Added.test(N)) {
1531           AdjK[i].push_back(N);
1532           Added.set(N);
1533         }
1534       }
1535     }
1536   }
1537   // Add back-eges in the adjacency matrix for the output dependences.
1538   for (auto &OD : OutputDeps)
1539     if (!Added.test(OD.second)) {
1540       AdjK[OD.first].push_back(OD.second);
1541       Added.set(OD.second);
1542     }
1543 }
1544 
1545 /// Identify an elementary circuit in the dependence graph starting at the
1546 /// specified node.
1547 bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
1548                                           bool HasBackedge) {
1549   SUnit *SV = &SUnits[V];
1550   bool F = false;
1551   Stack.insert(SV);
1552   Blocked.set(V);
1553 
1554   for (auto W : AdjK[V]) {
1555     if (NumPaths > MaxPaths)
1556       break;
1557     if (W < S)
1558       continue;
1559     if (W == S) {
1560       if (!HasBackedge)
1561         NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
1562       F = true;
1563       ++NumPaths;
1564       break;
1565     } else if (!Blocked.test(W)) {
1566       if (circuit(W, S, NodeSets, W < V ? true : HasBackedge))
1567         F = true;
1568     }
1569   }
1570 
1571   if (F)
1572     unblock(V);
1573   else {
1574     for (auto W : AdjK[V]) {
1575       if (W < S)
1576         continue;
1577       if (B[W].count(SV) == 0)
1578         B[W].insert(SV);
1579     }
1580   }
1581   Stack.pop_back();
1582   return F;
1583 }
1584 
1585 /// Unblock a node in the circuit finding algorithm.
1586 void SwingSchedulerDAG::Circuits::unblock(int U) {
1587   Blocked.reset(U);
1588   SmallPtrSet<SUnit *, 4> &BU = B[U];
1589   while (!BU.empty()) {
1590     SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
1591     assert(SI != BU.end() && "Invalid B set.");
1592     SUnit *W = *SI;
1593     BU.erase(W);
1594     if (Blocked.test(W->NodeNum))
1595       unblock(W->NodeNum);
1596   }
1597 }
1598 
1599 /// Identify all the elementary circuits in the dependence graph using
1600 /// Johnson's circuit algorithm.
1601 void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1602   // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1603   // but we do this to find the circuits, and then change them back.
1604   swapAntiDependences(SUnits);
1605 
1606   Circuits Cir(SUnits);
1607   // Create the adjacency structure.
1608   Cir.createAdjacencyStructure(this);
1609   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1610     Cir.reset();
1611     Cir.circuit(i, i, NodeSets);
1612   }
1613 
1614   // Change the dependences back so that we've created a DAG again.
1615   swapAntiDependences(SUnits);
1616 }
1617 
1618 /// Return true for DAG nodes that we ignore when computing the cost functions.
1619 /// We ignore the back-edge recurrence in order to avoid unbounded recurison
1620 /// in the calculation of the ASAP, ALAP, etc functions.
1621 static bool ignoreDependence(const SDep &D, bool isPred) {
1622   if (D.isArtificial())
1623     return true;
1624   return D.getKind() == SDep::Anti && isPred;
1625 }
1626 
1627 /// Compute several functions need to order the nodes for scheduling.
1628 ///  ASAP - Earliest time to schedule a node.
1629 ///  ALAP - Latest time to schedule a node.
1630 ///  MOV - Mobility function, difference between ALAP and ASAP.
1631 ///  D - Depth of each node.
1632 ///  H - Height of each node.
1633 void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
1634   ScheduleInfo.resize(SUnits.size());
1635 
1636   DEBUG({
1637     for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1638                                                     E = Topo.end();
1639          I != E; ++I) {
1640       SUnit *SU = &SUnits[*I];
1641       SU->dump(this);
1642     }
1643   });
1644 
1645   int maxASAP = 0;
1646   // Compute ASAP and ZeroLatencyDepth.
1647   for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1648                                                   E = Topo.end();
1649        I != E; ++I) {
1650     int asap = 0;
1651     int zeroLatencyDepth = 0;
1652     SUnit *SU = &SUnits[*I];
1653     for (SUnit::const_pred_iterator IP = SU->Preds.begin(),
1654                                     EP = SU->Preds.end();
1655          IP != EP; ++IP) {
1656       SUnit *pred = IP->getSUnit();
1657       if (IP->getLatency() == 0)
1658         zeroLatencyDepth =
1659             std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
1660       if (ignoreDependence(*IP, true))
1661         continue;
1662       asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() -
1663                                   getDistance(pred, SU, *IP) * MII));
1664     }
1665     maxASAP = std::max(maxASAP, asap);
1666     ScheduleInfo[*I].ASAP = asap;
1667     ScheduleInfo[*I].ZeroLatencyDepth = zeroLatencyDepth;
1668   }
1669 
1670   // Compute ALAP, ZeroLatencyHeight, and MOV.
1671   for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(),
1672                                                           E = Topo.rend();
1673        I != E; ++I) {
1674     int alap = maxASAP;
1675     int zeroLatencyHeight = 0;
1676     SUnit *SU = &SUnits[*I];
1677     for (SUnit::const_succ_iterator IS = SU->Succs.begin(),
1678                                     ES = SU->Succs.end();
1679          IS != ES; ++IS) {
1680       SUnit *succ = IS->getSUnit();
1681       if (IS->getLatency() == 0)
1682         zeroLatencyHeight =
1683             std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
1684       if (ignoreDependence(*IS, true))
1685         continue;
1686       alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() +
1687                                   getDistance(SU, succ, *IS) * MII));
1688     }
1689 
1690     ScheduleInfo[*I].ALAP = alap;
1691     ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight;
1692   }
1693 
1694   // After computing the node functions, compute the summary for each node set.
1695   for (NodeSet &I : NodeSets)
1696     I.computeNodeSetInfo(this);
1697 
1698   DEBUG({
1699     for (unsigned i = 0; i < SUnits.size(); i++) {
1700       dbgs() << "\tNode " << i << ":\n";
1701       dbgs() << "\t   ASAP = " << getASAP(&SUnits[i]) << "\n";
1702       dbgs() << "\t   ALAP = " << getALAP(&SUnits[i]) << "\n";
1703       dbgs() << "\t   MOV  = " << getMOV(&SUnits[i]) << "\n";
1704       dbgs() << "\t   D    = " << getDepth(&SUnits[i]) << "\n";
1705       dbgs() << "\t   H    = " << getHeight(&SUnits[i]) << "\n";
1706       dbgs() << "\t   ZLD  = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
1707       dbgs() << "\t   ZLH  = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
1708     }
1709   });
1710 }
1711 
1712 /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1713 /// as the predecessors of the elements of NodeOrder that are not also in
1714 /// NodeOrder.
1715 static bool pred_L(SetVector<SUnit *> &NodeOrder,
1716                    SmallSetVector<SUnit *, 8> &Preds,
1717                    const NodeSet *S = nullptr) {
1718   Preds.clear();
1719   for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1720        I != E; ++I) {
1721     for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end();
1722          PI != PE; ++PI) {
1723       if (S && S->count(PI->getSUnit()) == 0)
1724         continue;
1725       if (ignoreDependence(*PI, true))
1726         continue;
1727       if (NodeOrder.count(PI->getSUnit()) == 0)
1728         Preds.insert(PI->getSUnit());
1729     }
1730     // Back-edges are predecessors with an anti-dependence.
1731     for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(),
1732                                     ES = (*I)->Succs.end();
1733          IS != ES; ++IS) {
1734       if (IS->getKind() != SDep::Anti)
1735         continue;
1736       if (S && S->count(IS->getSUnit()) == 0)
1737         continue;
1738       if (NodeOrder.count(IS->getSUnit()) == 0)
1739         Preds.insert(IS->getSUnit());
1740     }
1741   }
1742   return !Preds.empty();
1743 }
1744 
1745 /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1746 /// as the successors of the elements of NodeOrder that are not also in
1747 /// NodeOrder.
1748 static bool succ_L(SetVector<SUnit *> &NodeOrder,
1749                    SmallSetVector<SUnit *, 8> &Succs,
1750                    const NodeSet *S = nullptr) {
1751   Succs.clear();
1752   for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1753        I != E; ++I) {
1754     for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end();
1755          SI != SE; ++SI) {
1756       if (S && S->count(SI->getSUnit()) == 0)
1757         continue;
1758       if (ignoreDependence(*SI, false))
1759         continue;
1760       if (NodeOrder.count(SI->getSUnit()) == 0)
1761         Succs.insert(SI->getSUnit());
1762     }
1763     for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(),
1764                                     PE = (*I)->Preds.end();
1765          PI != PE; ++PI) {
1766       if (PI->getKind() != SDep::Anti)
1767         continue;
1768       if (S && S->count(PI->getSUnit()) == 0)
1769         continue;
1770       if (NodeOrder.count(PI->getSUnit()) == 0)
1771         Succs.insert(PI->getSUnit());
1772     }
1773   }
1774   return !Succs.empty();
1775 }
1776 
1777 /// Return true if there is a path from the specified node to any of the nodes
1778 /// in DestNodes. Keep track and return the nodes in any path.
1779 static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
1780                         SetVector<SUnit *> &DestNodes,
1781                         SetVector<SUnit *> &Exclude,
1782                         SmallPtrSet<SUnit *, 8> &Visited) {
1783   if (Cur->isBoundaryNode())
1784     return false;
1785   if (Exclude.count(Cur) != 0)
1786     return false;
1787   if (DestNodes.count(Cur) != 0)
1788     return true;
1789   if (!Visited.insert(Cur).second)
1790     return Path.count(Cur) != 0;
1791   bool FoundPath = false;
1792   for (auto &SI : Cur->Succs)
1793     FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
1794   for (auto &PI : Cur->Preds)
1795     if (PI.getKind() == SDep::Anti)
1796       FoundPath |=
1797           computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
1798   if (FoundPath)
1799     Path.insert(Cur);
1800   return FoundPath;
1801 }
1802 
1803 /// Return true if Set1 is a subset of Set2.
1804 template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
1805   for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I)
1806     if (Set2.count(*I) == 0)
1807       return false;
1808   return true;
1809 }
1810 
1811 /// Compute the live-out registers for the instructions in a node-set.
1812 /// The live-out registers are those that are defined in the node-set,
1813 /// but not used. Except for use operands of Phis.
1814 static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
1815                             NodeSet &NS) {
1816   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1817   MachineRegisterInfo &MRI = MF.getRegInfo();
1818   SmallVector<RegisterMaskPair, 8> LiveOutRegs;
1819   SmallSet<unsigned, 4> Uses;
1820   for (SUnit *SU : NS) {
1821     const MachineInstr *MI = SU->getInstr();
1822     if (MI->isPHI())
1823       continue;
1824     for (const MachineOperand &MO : MI->operands())
1825       if (MO.isReg() && MO.isUse()) {
1826         unsigned Reg = MO.getReg();
1827         if (TargetRegisterInfo::isVirtualRegister(Reg))
1828           Uses.insert(Reg);
1829         else if (MRI.isAllocatable(Reg))
1830           for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1831             Uses.insert(*Units);
1832       }
1833   }
1834   for (SUnit *SU : NS)
1835     for (const MachineOperand &MO : SU->getInstr()->operands())
1836       if (MO.isReg() && MO.isDef() && !MO.isDead()) {
1837         unsigned Reg = MO.getReg();
1838         if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1839           if (!Uses.count(Reg))
1840             LiveOutRegs.push_back(RegisterMaskPair(Reg,
1841                                                    LaneBitmask::getNone()));
1842         } else if (MRI.isAllocatable(Reg)) {
1843           for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1844             if (!Uses.count(*Units))
1845               LiveOutRegs.push_back(RegisterMaskPair(*Units,
1846                                                      LaneBitmask::getNone()));
1847         }
1848       }
1849   RPTracker.addLiveRegs(LiveOutRegs);
1850 }
1851 
1852 /// A heuristic to filter nodes in recurrent node-sets if the register
1853 /// pressure of a set is too high.
1854 void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
1855   for (auto &NS : NodeSets) {
1856     // Skip small node-sets since they won't cause register pressure problems.
1857     if (NS.size() <= 2)
1858       continue;
1859     IntervalPressure RecRegPressure;
1860     RegPressureTracker RecRPTracker(RecRegPressure);
1861     RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
1862     computeLiveOuts(MF, RecRPTracker, NS);
1863     RecRPTracker.closeBottom();
1864 
1865     std::vector<SUnit *> SUnits(NS.begin(), NS.end());
1866     llvm::sort(SUnits.begin(), SUnits.end(),
1867                [](const SUnit *A, const SUnit *B) {
1868       return A->NodeNum > B->NodeNum;
1869     });
1870 
1871     for (auto &SU : SUnits) {
1872       // Since we're computing the register pressure for a subset of the
1873       // instructions in a block, we need to set the tracker for each
1874       // instruction in the node-set. The tracker is set to the instruction
1875       // just after the one we're interested in.
1876       MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
1877       RecRPTracker.setPos(std::next(CurInstI));
1878 
1879       RegPressureDelta RPDelta;
1880       ArrayRef<PressureChange> CriticalPSets;
1881       RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
1882                                              CriticalPSets,
1883                                              RecRegPressure.MaxSetPressure);
1884       if (RPDelta.Excess.isValid()) {
1885         DEBUG(dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
1886                      << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
1887                      << ":" << RPDelta.Excess.getUnitInc());
1888         NS.setExceedPressure(SU);
1889         break;
1890       }
1891       RecRPTracker.recede();
1892     }
1893   }
1894 }
1895 
1896 /// A heuristic to colocate node sets that have the same set of
1897 /// successors.
1898 void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
1899   unsigned Colocate = 0;
1900   for (int i = 0, e = NodeSets.size(); i < e; ++i) {
1901     NodeSet &N1 = NodeSets[i];
1902     SmallSetVector<SUnit *, 8> S1;
1903     if (N1.empty() || !succ_L(N1, S1))
1904       continue;
1905     for (int j = i + 1; j < e; ++j) {
1906       NodeSet &N2 = NodeSets[j];
1907       if (N1.compareRecMII(N2) != 0)
1908         continue;
1909       SmallSetVector<SUnit *, 8> S2;
1910       if (N2.empty() || !succ_L(N2, S2))
1911         continue;
1912       if (isSubset(S1, S2) && S1.size() == S2.size()) {
1913         N1.setColocate(++Colocate);
1914         N2.setColocate(Colocate);
1915         break;
1916       }
1917     }
1918   }
1919 }
1920 
1921 /// Check if the existing node-sets are profitable. If not, then ignore the
1922 /// recurrent node-sets, and attempt to schedule all nodes together. This is
1923 /// a heuristic. If the MII is large and all the recurrent node-sets are small,
1924 /// then it's best to try to schedule all instructions together instead of
1925 /// starting with the recurrent node-sets.
1926 void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
1927   // Look for loops with a large MII.
1928   if (MII < 17)
1929     return;
1930   // Check if the node-set contains only a simple add recurrence.
1931   for (auto &NS : NodeSets) {
1932     if (NS.getRecMII() > 2)
1933       return;
1934     if (NS.getMaxDepth() > MII)
1935       return;
1936   }
1937   NodeSets.clear();
1938   DEBUG(dbgs() << "Clear recurrence node-sets\n");
1939   return;
1940 }
1941 
1942 /// Add the nodes that do not belong to a recurrence set into groups
1943 /// based upon connected componenets.
1944 void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
1945   SetVector<SUnit *> NodesAdded;
1946   SmallPtrSet<SUnit *, 8> Visited;
1947   // Add the nodes that are on a path between the previous node sets and
1948   // the current node set.
1949   for (NodeSet &I : NodeSets) {
1950     SmallSetVector<SUnit *, 8> N;
1951     // Add the nodes from the current node set to the previous node set.
1952     if (succ_L(I, N)) {
1953       SetVector<SUnit *> Path;
1954       for (SUnit *NI : N) {
1955         Visited.clear();
1956         computePath(NI, Path, NodesAdded, I, Visited);
1957       }
1958       if (!Path.empty())
1959         I.insert(Path.begin(), Path.end());
1960     }
1961     // Add the nodes from the previous node set to the current node set.
1962     N.clear();
1963     if (succ_L(NodesAdded, N)) {
1964       SetVector<SUnit *> Path;
1965       for (SUnit *NI : N) {
1966         Visited.clear();
1967         computePath(NI, Path, I, NodesAdded, Visited);
1968       }
1969       if (!Path.empty())
1970         I.insert(Path.begin(), Path.end());
1971     }
1972     NodesAdded.insert(I.begin(), I.end());
1973   }
1974 
1975   // Create a new node set with the connected nodes of any successor of a node
1976   // in a recurrent set.
1977   NodeSet NewSet;
1978   SmallSetVector<SUnit *, 8> N;
1979   if (succ_L(NodesAdded, N))
1980     for (SUnit *I : N)
1981       addConnectedNodes(I, NewSet, NodesAdded);
1982   if (!NewSet.empty())
1983     NodeSets.push_back(NewSet);
1984 
1985   // Create a new node set with the connected nodes of any predecessor of a node
1986   // in a recurrent set.
1987   NewSet.clear();
1988   if (pred_L(NodesAdded, N))
1989     for (SUnit *I : N)
1990       addConnectedNodes(I, NewSet, NodesAdded);
1991   if (!NewSet.empty())
1992     NodeSets.push_back(NewSet);
1993 
1994   // Create new nodes sets with the connected nodes any any remaining node that
1995   // has no predecessor.
1996   for (unsigned i = 0; i < SUnits.size(); ++i) {
1997     SUnit *SU = &SUnits[i];
1998     if (NodesAdded.count(SU) == 0) {
1999       NewSet.clear();
2000       addConnectedNodes(SU, NewSet, NodesAdded);
2001       if (!NewSet.empty())
2002         NodeSets.push_back(NewSet);
2003     }
2004   }
2005 }
2006 
2007 /// Add the node to the set, and add all is its connected nodes to the set.
2008 void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
2009                                           SetVector<SUnit *> &NodesAdded) {
2010   NewSet.insert(SU);
2011   NodesAdded.insert(SU);
2012   for (auto &SI : SU->Succs) {
2013     SUnit *Successor = SI.getSUnit();
2014     if (!SI.isArtificial() && NodesAdded.count(Successor) == 0)
2015       addConnectedNodes(Successor, NewSet, NodesAdded);
2016   }
2017   for (auto &PI : SU->Preds) {
2018     SUnit *Predecessor = PI.getSUnit();
2019     if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
2020       addConnectedNodes(Predecessor, NewSet, NodesAdded);
2021   }
2022 }
2023 
2024 /// Return true if Set1 contains elements in Set2. The elements in common
2025 /// are returned in a different container.
2026 static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
2027                         SmallSetVector<SUnit *, 8> &Result) {
2028   Result.clear();
2029   for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
2030     SUnit *SU = Set1[i];
2031     if (Set2.count(SU) != 0)
2032       Result.insert(SU);
2033   }
2034   return !Result.empty();
2035 }
2036 
2037 /// Merge the recurrence node sets that have the same initial node.
2038 void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
2039   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
2040        ++I) {
2041     NodeSet &NI = *I;
2042     for (NodeSetType::iterator J = I + 1; J != E;) {
2043       NodeSet &NJ = *J;
2044       if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
2045         if (NJ.compareRecMII(NI) > 0)
2046           NI.setRecMII(NJ.getRecMII());
2047         for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI;
2048              ++NII)
2049           I->insert(*NII);
2050         NodeSets.erase(J);
2051         E = NodeSets.end();
2052       } else {
2053         ++J;
2054       }
2055     }
2056   }
2057 }
2058 
2059 /// Remove nodes that have been scheduled in previous NodeSets.
2060 void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
2061   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
2062        ++I)
2063     for (NodeSetType::iterator J = I + 1; J != E;) {
2064       J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
2065 
2066       if (J->empty()) {
2067         NodeSets.erase(J);
2068         E = NodeSets.end();
2069       } else {
2070         ++J;
2071       }
2072     }
2073 }
2074 
2075 /// Compute an ordered list of the dependence graph nodes, which
2076 /// indicates the order that the nodes will be scheduled.  This is a
2077 /// two-level algorithm. First, a partial order is created, which
2078 /// consists of a list of sets ordered from highest to lowest priority.
2079 void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
2080   SmallSetVector<SUnit *, 8> R;
2081   NodeOrder.clear();
2082 
2083   for (auto &Nodes : NodeSets) {
2084     DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
2085     OrderKind Order;
2086     SmallSetVector<SUnit *, 8> N;
2087     if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) {
2088       R.insert(N.begin(), N.end());
2089       Order = BottomUp;
2090       DEBUG(dbgs() << "  Bottom up (preds) ");
2091     } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) {
2092       R.insert(N.begin(), N.end());
2093       Order = TopDown;
2094       DEBUG(dbgs() << "  Top down (succs) ");
2095     } else if (isIntersect(N, Nodes, R)) {
2096       // If some of the successors are in the existing node-set, then use the
2097       // top-down ordering.
2098       Order = TopDown;
2099       DEBUG(dbgs() << "  Top down (intersect) ");
2100     } else if (NodeSets.size() == 1) {
2101       for (auto &N : Nodes)
2102         if (N->Succs.size() == 0)
2103           R.insert(N);
2104       Order = BottomUp;
2105       DEBUG(dbgs() << "  Bottom up (all) ");
2106     } else {
2107       // Find the node with the highest ASAP.
2108       SUnit *maxASAP = nullptr;
2109       for (SUnit *SU : Nodes) {
2110         if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
2111             (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
2112           maxASAP = SU;
2113       }
2114       R.insert(maxASAP);
2115       Order = BottomUp;
2116       DEBUG(dbgs() << "  Bottom up (default) ");
2117     }
2118 
2119     while (!R.empty()) {
2120       if (Order == TopDown) {
2121         // Choose the node with the maximum height.  If more than one, choose
2122         // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
2123         // choose the node with the lowest MOV.
2124         while (!R.empty()) {
2125           SUnit *maxHeight = nullptr;
2126           for (SUnit *I : R) {
2127             if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
2128               maxHeight = I;
2129             else if (getHeight(I) == getHeight(maxHeight) &&
2130                      getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
2131               maxHeight = I;
2132             else if (getHeight(I) == getHeight(maxHeight) &&
2133                      getZeroLatencyHeight(I) ==
2134                          getZeroLatencyHeight(maxHeight) &&
2135                      getMOV(I) < getMOV(maxHeight))
2136               maxHeight = I;
2137           }
2138           NodeOrder.insert(maxHeight);
2139           DEBUG(dbgs() << maxHeight->NodeNum << " ");
2140           R.remove(maxHeight);
2141           for (const auto &I : maxHeight->Succs) {
2142             if (Nodes.count(I.getSUnit()) == 0)
2143               continue;
2144             if (NodeOrder.count(I.getSUnit()) != 0)
2145               continue;
2146             if (ignoreDependence(I, false))
2147               continue;
2148             R.insert(I.getSUnit());
2149           }
2150           // Back-edges are predecessors with an anti-dependence.
2151           for (const auto &I : maxHeight->Preds) {
2152             if (I.getKind() != SDep::Anti)
2153               continue;
2154             if (Nodes.count(I.getSUnit()) == 0)
2155               continue;
2156             if (NodeOrder.count(I.getSUnit()) != 0)
2157               continue;
2158             R.insert(I.getSUnit());
2159           }
2160         }
2161         Order = BottomUp;
2162         DEBUG(dbgs() << "\n   Switching order to bottom up ");
2163         SmallSetVector<SUnit *, 8> N;
2164         if (pred_L(NodeOrder, N, &Nodes))
2165           R.insert(N.begin(), N.end());
2166       } else {
2167         // Choose the node with the maximum depth.  If more than one, choose
2168         // the node with the maximum ZeroLatencyDepth. If still more than one,
2169         // choose the node with the lowest MOV.
2170         while (!R.empty()) {
2171           SUnit *maxDepth = nullptr;
2172           for (SUnit *I : R) {
2173             if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
2174               maxDepth = I;
2175             else if (getDepth(I) == getDepth(maxDepth) &&
2176                      getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
2177               maxDepth = I;
2178             else if (getDepth(I) == getDepth(maxDepth) &&
2179                      getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
2180                      getMOV(I) < getMOV(maxDepth))
2181               maxDepth = I;
2182           }
2183           NodeOrder.insert(maxDepth);
2184           DEBUG(dbgs() << maxDepth->NodeNum << " ");
2185           R.remove(maxDepth);
2186           if (Nodes.isExceedSU(maxDepth)) {
2187             Order = TopDown;
2188             R.clear();
2189             R.insert(Nodes.getNode(0));
2190             break;
2191           }
2192           for (const auto &I : maxDepth->Preds) {
2193             if (Nodes.count(I.getSUnit()) == 0)
2194               continue;
2195             if (NodeOrder.count(I.getSUnit()) != 0)
2196               continue;
2197             R.insert(I.getSUnit());
2198           }
2199           // Back-edges are predecessors with an anti-dependence.
2200           for (const auto &I : maxDepth->Succs) {
2201             if (I.getKind() != SDep::Anti)
2202               continue;
2203             if (Nodes.count(I.getSUnit()) == 0)
2204               continue;
2205             if (NodeOrder.count(I.getSUnit()) != 0)
2206               continue;
2207             R.insert(I.getSUnit());
2208           }
2209         }
2210         Order = TopDown;
2211         DEBUG(dbgs() << "\n   Switching order to top down ");
2212         SmallSetVector<SUnit *, 8> N;
2213         if (succ_L(NodeOrder, N, &Nodes))
2214           R.insert(N.begin(), N.end());
2215       }
2216     }
2217     DEBUG(dbgs() << "\nDone with Nodeset\n");
2218   }
2219 
2220   DEBUG({
2221     dbgs() << "Node order: ";
2222     for (SUnit *I : NodeOrder)
2223       dbgs() << " " << I->NodeNum << " ";
2224     dbgs() << "\n";
2225   });
2226 }
2227 
2228 /// Process the nodes in the computed order and create the pipelined schedule
2229 /// of the instructions, if possible. Return true if a schedule is found.
2230 bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
2231   if (NodeOrder.empty())
2232     return false;
2233 
2234   bool scheduleFound = false;
2235   // Keep increasing II until a valid schedule is found.
2236   for (unsigned II = MII; II < MII + 10 && !scheduleFound; ++II) {
2237     Schedule.reset();
2238     Schedule.setInitiationInterval(II);
2239     DEBUG(dbgs() << "Try to schedule with " << II << "\n");
2240 
2241     SetVector<SUnit *>::iterator NI = NodeOrder.begin();
2242     SetVector<SUnit *>::iterator NE = NodeOrder.end();
2243     do {
2244       SUnit *SU = *NI;
2245 
2246       // Compute the schedule time for the instruction, which is based
2247       // upon the scheduled time for any predecessors/successors.
2248       int EarlyStart = INT_MIN;
2249       int LateStart = INT_MAX;
2250       // These values are set when the size of the schedule window is limited
2251       // due to chain dependences.
2252       int SchedEnd = INT_MAX;
2253       int SchedStart = INT_MIN;
2254       Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
2255                             II, this);
2256       DEBUG({
2257         dbgs() << "Inst (" << SU->NodeNum << ") ";
2258         SU->getInstr()->dump();
2259         dbgs() << "\n";
2260       });
2261       DEBUG({
2262         dbgs() << "\tes: " << EarlyStart << " ls: " << LateStart
2263                << " me: " << SchedEnd << " ms: " << SchedStart << "\n";
2264       });
2265 
2266       if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
2267           SchedStart > LateStart)
2268         scheduleFound = false;
2269       else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
2270         SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
2271         scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
2272       } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
2273         SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
2274         scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
2275       } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
2276         SchedEnd =
2277             std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
2278         // When scheduling a Phi it is better to start at the late cycle and go
2279         // backwards. The default order may insert the Phi too far away from
2280         // its first dependence.
2281         if (SU->getInstr()->isPHI())
2282           scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
2283         else
2284           scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
2285       } else {
2286         int FirstCycle = Schedule.getFirstCycle();
2287         scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
2288                                         FirstCycle + getASAP(SU) + II - 1, II);
2289       }
2290       // Even if we find a schedule, make sure the schedule doesn't exceed the
2291       // allowable number of stages. We keep trying if this happens.
2292       if (scheduleFound)
2293         if (SwpMaxStages > -1 &&
2294             Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
2295           scheduleFound = false;
2296 
2297       DEBUG({
2298         if (!scheduleFound)
2299           dbgs() << "\tCan't schedule\n";
2300       });
2301     } while (++NI != NE && scheduleFound);
2302 
2303     // If a schedule is found, check if it is a valid schedule too.
2304     if (scheduleFound)
2305       scheduleFound = Schedule.isValidSchedule(this);
2306   }
2307 
2308   DEBUG(dbgs() << "Schedule Found? " << scheduleFound << "\n");
2309 
2310   if (scheduleFound)
2311     Schedule.finalizeSchedule(this);
2312   else
2313     Schedule.reset();
2314 
2315   return scheduleFound && Schedule.getMaxStageCount() > 0;
2316 }
2317 
2318 /// Given a schedule for the loop, generate a new version of the loop,
2319 /// and replace the old version.  This function generates a prolog
2320 /// that contains the initial iterations in the pipeline, and kernel
2321 /// loop, and the epilogue that contains the code for the final
2322 /// iterations.
2323 void SwingSchedulerDAG::generatePipelinedLoop(SMSchedule &Schedule) {
2324   // Create a new basic block for the kernel and add it to the CFG.
2325   MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
2326 
2327   unsigned MaxStageCount = Schedule.getMaxStageCount();
2328 
2329   // Remember the registers that are used in different stages. The index is
2330   // the iteration, or stage, that the instruction is scheduled in.  This is
2331   // a map between register names in the orignal block and the names created
2332   // in each stage of the pipelined loop.
2333   ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
2334   InstrMapTy InstrMap;
2335 
2336   SmallVector<MachineBasicBlock *, 4> PrologBBs;
2337   // Generate the prolog instructions that set up the pipeline.
2338   generateProlog(Schedule, MaxStageCount, KernelBB, VRMap, PrologBBs);
2339   MF.insert(BB->getIterator(), KernelBB);
2340 
2341   // Rearrange the instructions to generate the new, pipelined loop,
2342   // and update register names as needed.
2343   for (int Cycle = Schedule.getFirstCycle(),
2344            LastCycle = Schedule.getFinalCycle();
2345        Cycle <= LastCycle; ++Cycle) {
2346     std::deque<SUnit *> &CycleInstrs = Schedule.getInstructions(Cycle);
2347     // This inner loop schedules each instruction in the cycle.
2348     for (SUnit *CI : CycleInstrs) {
2349       if (CI->getInstr()->isPHI())
2350         continue;
2351       unsigned StageNum = Schedule.stageScheduled(getSUnit(CI->getInstr()));
2352       MachineInstr *NewMI = cloneInstr(CI->getInstr(), MaxStageCount, StageNum);
2353       updateInstruction(NewMI, false, MaxStageCount, StageNum, Schedule, VRMap);
2354       KernelBB->push_back(NewMI);
2355       InstrMap[NewMI] = CI->getInstr();
2356     }
2357   }
2358 
2359   // Copy any terminator instructions to the new kernel, and update
2360   // names as needed.
2361   for (MachineBasicBlock::iterator I = BB->getFirstTerminator(),
2362                                    E = BB->instr_end();
2363        I != E; ++I) {
2364     MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
2365     updateInstruction(NewMI, false, MaxStageCount, 0, Schedule, VRMap);
2366     KernelBB->push_back(NewMI);
2367     InstrMap[NewMI] = &*I;
2368   }
2369 
2370   KernelBB->transferSuccessors(BB);
2371   KernelBB->replaceSuccessor(BB, KernelBB);
2372 
2373   generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule,
2374                        VRMap, InstrMap, MaxStageCount, MaxStageCount, false);
2375   generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule, VRMap,
2376                InstrMap, MaxStageCount, MaxStageCount, false);
2377 
2378   DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
2379 
2380   SmallVector<MachineBasicBlock *, 4> EpilogBBs;
2381   // Generate the epilog instructions to complete the pipeline.
2382   generateEpilog(Schedule, MaxStageCount, KernelBB, VRMap, EpilogBBs,
2383                  PrologBBs);
2384 
2385   // We need this step because the register allocation doesn't handle some
2386   // situations well, so we insert copies to help out.
2387   splitLifetimes(KernelBB, EpilogBBs, Schedule);
2388 
2389   // Remove dead instructions due to loop induction variables.
2390   removeDeadInstructions(KernelBB, EpilogBBs);
2391 
2392   // Add branches between prolog and epilog blocks.
2393   addBranches(PrologBBs, KernelBB, EpilogBBs, Schedule, VRMap);
2394 
2395   // Remove the original loop since it's no longer referenced.
2396   for (auto &I : *BB)
2397     LIS.RemoveMachineInstrFromMaps(I);
2398   BB->clear();
2399   BB->eraseFromParent();
2400 
2401   delete[] VRMap;
2402 }
2403 
2404 /// Generate the pipeline prolog code.
2405 void SwingSchedulerDAG::generateProlog(SMSchedule &Schedule, unsigned LastStage,
2406                                        MachineBasicBlock *KernelBB,
2407                                        ValueMapTy *VRMap,
2408                                        MBBVectorTy &PrologBBs) {
2409   MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader();
2410   assert(PreheaderBB != nullptr &&
2411          "Need to add code to handle loops w/o preheader");
2412   MachineBasicBlock *PredBB = PreheaderBB;
2413   InstrMapTy InstrMap;
2414 
2415   // Generate a basic block for each stage, not including the last stage,
2416   // which will be generated in the kernel. Each basic block may contain
2417   // instructions from multiple stages/iterations.
2418   for (unsigned i = 0; i < LastStage; ++i) {
2419     // Create and insert the prolog basic block prior to the original loop
2420     // basic block.  The original loop is removed later.
2421     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
2422     PrologBBs.push_back(NewBB);
2423     MF.insert(BB->getIterator(), NewBB);
2424     NewBB->transferSuccessors(PredBB);
2425     PredBB->addSuccessor(NewBB);
2426     PredBB = NewBB;
2427 
2428     // Generate instructions for each appropriate stage. Process instructions
2429     // in original program order.
2430     for (int StageNum = i; StageNum >= 0; --StageNum) {
2431       for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2432                                        BBE = BB->getFirstTerminator();
2433            BBI != BBE; ++BBI) {
2434         if (Schedule.isScheduledAtStage(getSUnit(&*BBI), (unsigned)StageNum)) {
2435           if (BBI->isPHI())
2436             continue;
2437           MachineInstr *NewMI =
2438               cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum, Schedule);
2439           updateInstruction(NewMI, false, i, (unsigned)StageNum, Schedule,
2440                             VRMap);
2441           NewBB->push_back(NewMI);
2442           InstrMap[NewMI] = &*BBI;
2443         }
2444       }
2445     }
2446     rewritePhiValues(NewBB, i, Schedule, VRMap, InstrMap);
2447     DEBUG({
2448       dbgs() << "prolog:\n";
2449       NewBB->dump();
2450     });
2451   }
2452 
2453   PredBB->replaceSuccessor(BB, KernelBB);
2454 
2455   // Check if we need to remove the branch from the preheader to the original
2456   // loop, and replace it with a branch to the new loop.
2457   unsigned numBranches = TII->removeBranch(*PreheaderBB);
2458   if (numBranches) {
2459     SmallVector<MachineOperand, 0> Cond;
2460     TII->insertBranch(*PreheaderBB, PrologBBs[0], nullptr, Cond, DebugLoc());
2461   }
2462 }
2463 
2464 /// Generate the pipeline epilog code. The epilog code finishes the iterations
2465 /// that were started in either the prolog or the kernel.  We create a basic
2466 /// block for each stage that needs to complete.
2467 void SwingSchedulerDAG::generateEpilog(SMSchedule &Schedule, unsigned LastStage,
2468                                        MachineBasicBlock *KernelBB,
2469                                        ValueMapTy *VRMap,
2470                                        MBBVectorTy &EpilogBBs,
2471                                        MBBVectorTy &PrologBBs) {
2472   // We need to change the branch from the kernel to the first epilog block, so
2473   // this call to analyze branch uses the kernel rather than the original BB.
2474   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2475   SmallVector<MachineOperand, 4> Cond;
2476   bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
2477   assert(!checkBranch && "generateEpilog must be able to analyze the branch");
2478   if (checkBranch)
2479     return;
2480 
2481   MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
2482   if (*LoopExitI == KernelBB)
2483     ++LoopExitI;
2484   assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
2485   MachineBasicBlock *LoopExitBB = *LoopExitI;
2486 
2487   MachineBasicBlock *PredBB = KernelBB;
2488   MachineBasicBlock *EpilogStart = LoopExitBB;
2489   InstrMapTy InstrMap;
2490 
2491   // Generate a basic block for each stage, not including the last stage,
2492   // which was generated for the kernel.  Each basic block may contain
2493   // instructions from multiple stages/iterations.
2494   int EpilogStage = LastStage + 1;
2495   for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
2496     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
2497     EpilogBBs.push_back(NewBB);
2498     MF.insert(BB->getIterator(), NewBB);
2499 
2500     PredBB->replaceSuccessor(LoopExitBB, NewBB);
2501     NewBB->addSuccessor(LoopExitBB);
2502 
2503     if (EpilogStart == LoopExitBB)
2504       EpilogStart = NewBB;
2505 
2506     // Add instructions to the epilog depending on the current block.
2507     // Process instructions in original program order.
2508     for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
2509       for (auto &BBI : *BB) {
2510         if (BBI.isPHI())
2511           continue;
2512         MachineInstr *In = &BBI;
2513         if (Schedule.isScheduledAtStage(getSUnit(In), StageNum)) {
2514           // Instructions with memoperands in the epilog are updated with
2515           // conservative values.
2516           MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0);
2517           updateInstruction(NewMI, i == 1, EpilogStage, 0, Schedule, VRMap);
2518           NewBB->push_back(NewMI);
2519           InstrMap[NewMI] = In;
2520         }
2521       }
2522     }
2523     generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule,
2524                          VRMap, InstrMap, LastStage, EpilogStage, i == 1);
2525     generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, VRMap,
2526                  InstrMap, LastStage, EpilogStage, i == 1);
2527     PredBB = NewBB;
2528 
2529     DEBUG({
2530       dbgs() << "epilog:\n";
2531       NewBB->dump();
2532     });
2533   }
2534 
2535   // Fix any Phi nodes in the loop exit block.
2536   for (MachineInstr &MI : *LoopExitBB) {
2537     if (!MI.isPHI())
2538       break;
2539     for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
2540       MachineOperand &MO = MI.getOperand(i);
2541       if (MO.getMBB() == BB)
2542         MO.setMBB(PredBB);
2543     }
2544   }
2545 
2546   // Create a branch to the new epilog from the kernel.
2547   // Remove the original branch and add a new branch to the epilog.
2548   TII->removeBranch(*KernelBB);
2549   TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
2550   // Add a branch to the loop exit.
2551   if (EpilogBBs.size() > 0) {
2552     MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
2553     SmallVector<MachineOperand, 4> Cond1;
2554     TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
2555   }
2556 }
2557 
2558 /// Replace all uses of FromReg that appear outside the specified
2559 /// basic block with ToReg.
2560 static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
2561                                     MachineBasicBlock *MBB,
2562                                     MachineRegisterInfo &MRI,
2563                                     LiveIntervals &LIS) {
2564   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(FromReg),
2565                                          E = MRI.use_end();
2566        I != E;) {
2567     MachineOperand &O = *I;
2568     ++I;
2569     if (O.getParent()->getParent() != MBB)
2570       O.setReg(ToReg);
2571   }
2572   if (!LIS.hasInterval(ToReg))
2573     LIS.createEmptyInterval(ToReg);
2574 }
2575 
2576 /// Return true if the register has a use that occurs outside the
2577 /// specified loop.
2578 static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
2579                             MachineRegisterInfo &MRI) {
2580   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(Reg),
2581                                          E = MRI.use_end();
2582        I != E; ++I)
2583     if (I->getParent()->getParent() != BB)
2584       return true;
2585   return false;
2586 }
2587 
2588 /// Generate Phis for the specific block in the generated pipelined code.
2589 /// This function looks at the Phis from the original code to guide the
2590 /// creation of new Phis.
2591 void SwingSchedulerDAG::generateExistingPhis(
2592     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2593     MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2594     InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2595     bool IsLast) {
2596   // Compute the stage number for the initial value of the Phi, which
2597   // comes from the prolog. The prolog to use depends on to which kernel/
2598   // epilog that we're adding the Phi.
2599   unsigned PrologStage = 0;
2600   unsigned PrevStage = 0;
2601   bool InKernel = (LastStageNum == CurStageNum);
2602   if (InKernel) {
2603     PrologStage = LastStageNum - 1;
2604     PrevStage = CurStageNum;
2605   } else {
2606     PrologStage = LastStageNum - (CurStageNum - LastStageNum);
2607     PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
2608   }
2609 
2610   for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2611                                    BBE = BB->getFirstNonPHI();
2612        BBI != BBE; ++BBI) {
2613     unsigned Def = BBI->getOperand(0).getReg();
2614 
2615     unsigned InitVal = 0;
2616     unsigned LoopVal = 0;
2617     getPhiRegs(*BBI, BB, InitVal, LoopVal);
2618 
2619     unsigned PhiOp1 = 0;
2620     // The Phi value from the loop body typically is defined in the loop, but
2621     // not always. So, we need to check if the value is defined in the loop.
2622     unsigned PhiOp2 = LoopVal;
2623     if (VRMap[LastStageNum].count(LoopVal))
2624       PhiOp2 = VRMap[LastStageNum][LoopVal];
2625 
2626     int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2627     int LoopValStage =
2628         Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
2629     unsigned NumStages = Schedule.getStagesForReg(Def, CurStageNum);
2630     if (NumStages == 0) {
2631       // We don't need to generate a Phi anymore, but we need to rename any uses
2632       // of the Phi value.
2633       unsigned NewReg = VRMap[PrevStage][LoopVal];
2634       rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, 0, &*BBI,
2635                             Def, InitVal, NewReg);
2636       if (VRMap[CurStageNum].count(LoopVal))
2637         VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
2638     }
2639     // Adjust the number of Phis needed depending on the number of prologs left,
2640     // and the distance from where the Phi is first scheduled. The number of
2641     // Phis cannot exceed the number of prolog stages. Each stage can
2642     // potentially define two values.
2643     unsigned MaxPhis = PrologStage + 2;
2644     if (!InKernel && (int)PrologStage <= LoopValStage)
2645       MaxPhis = std::max((int)MaxPhis - (int)LoopValStage, 1);
2646     unsigned NumPhis = std::min(NumStages, MaxPhis);
2647 
2648     unsigned NewReg = 0;
2649     unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
2650     // In the epilog, we may need to look back one stage to get the correct
2651     // Phi name because the epilog and prolog blocks execute the same stage.
2652     // The correct name is from the previous block only when the Phi has
2653     // been completely scheduled prior to the epilog, and Phi value is not
2654     // needed in multiple stages.
2655     int StageDiff = 0;
2656     if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
2657         NumPhis == 1)
2658       StageDiff = 1;
2659     // Adjust the computations below when the phi and the loop definition
2660     // are scheduled in different stages.
2661     if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
2662       StageDiff = StageScheduled - LoopValStage;
2663     for (unsigned np = 0; np < NumPhis; ++np) {
2664       // If the Phi hasn't been scheduled, then use the initial Phi operand
2665       // value. Otherwise, use the scheduled version of the instruction. This
2666       // is a little complicated when a Phi references another Phi.
2667       if (np > PrologStage || StageScheduled >= (int)LastStageNum)
2668         PhiOp1 = InitVal;
2669       // Check if the Phi has already been scheduled in a prolog stage.
2670       else if (PrologStage >= AccessStage + StageDiff + np &&
2671                VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
2672         PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
2673       // Check if the Phi has already been scheduled, but the loop intruction
2674       // is either another Phi, or doesn't occur in the loop.
2675       else if (PrologStage >= AccessStage + StageDiff + np) {
2676         // If the Phi references another Phi, we need to examine the other
2677         // Phi to get the correct value.
2678         PhiOp1 = LoopVal;
2679         MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
2680         int Indirects = 1;
2681         while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
2682           int PhiStage = Schedule.stageScheduled(getSUnit(InstOp1));
2683           if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
2684             PhiOp1 = getInitPhiReg(*InstOp1, BB);
2685           else
2686             PhiOp1 = getLoopPhiReg(*InstOp1, BB);
2687           InstOp1 = MRI.getVRegDef(PhiOp1);
2688           int PhiOpStage = Schedule.stageScheduled(getSUnit(InstOp1));
2689           int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
2690           if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
2691               VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
2692             PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
2693             break;
2694           }
2695           ++Indirects;
2696         }
2697       } else
2698         PhiOp1 = InitVal;
2699       // If this references a generated Phi in the kernel, get the Phi operand
2700       // from the incoming block.
2701       if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
2702         if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2703           PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2704 
2705       MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
2706       bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
2707       // In the epilog, a map lookup is needed to get the value from the kernel,
2708       // or previous epilog block. How is does this depends on if the
2709       // instruction is scheduled in the previous block.
2710       if (!InKernel) {
2711         int StageDiffAdj = 0;
2712         if (LoopValStage != -1 && StageScheduled > LoopValStage)
2713           StageDiffAdj = StageScheduled - LoopValStage;
2714         // Use the loop value defined in the kernel, unless the kernel
2715         // contains the last definition of the Phi.
2716         if (np == 0 && PrevStage == LastStageNum &&
2717             (StageScheduled != 0 || LoopValStage != 0) &&
2718             VRMap[PrevStage - StageDiffAdj].count(LoopVal))
2719           PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
2720         // Use the value defined by the Phi. We add one because we switch
2721         // from looking at the loop value to the Phi definition.
2722         else if (np > 0 && PrevStage == LastStageNum &&
2723                  VRMap[PrevStage - np + 1].count(Def))
2724           PhiOp2 = VRMap[PrevStage - np + 1][Def];
2725         // Use the loop value defined in the kernel.
2726         else if ((unsigned)LoopValStage + StageDiffAdj > PrologStage + 1 &&
2727                  VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
2728           PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
2729         // Use the value defined by the Phi, unless we're generating the first
2730         // epilog and the Phi refers to a Phi in a different stage.
2731         else if (VRMap[PrevStage - np].count(Def) &&
2732                  (!LoopDefIsPhi || PrevStage != LastStageNum))
2733           PhiOp2 = VRMap[PrevStage - np][Def];
2734       }
2735 
2736       // Check if we can reuse an existing Phi. This occurs when a Phi
2737       // references another Phi, and the other Phi is scheduled in an
2738       // earlier stage. We can try to reuse an existing Phi up until the last
2739       // stage of the current Phi.
2740       if (LoopDefIsPhi && (int)(PrologStage - np) >= StageScheduled) {
2741         int LVNumStages = Schedule.getStagesForPhi(LoopVal);
2742         int StageDiff = (StageScheduled - LoopValStage);
2743         LVNumStages -= StageDiff;
2744         // Make sure the loop value Phi has been processed already.
2745         if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) {
2746           NewReg = PhiOp2;
2747           unsigned ReuseStage = CurStageNum;
2748           if (Schedule.isLoopCarried(this, *PhiInst))
2749             ReuseStage -= LVNumStages;
2750           // Check if the Phi to reuse has been generated yet. If not, then
2751           // there is nothing to reuse.
2752           if (VRMap[ReuseStage - np].count(LoopVal)) {
2753             NewReg = VRMap[ReuseStage - np][LoopVal];
2754 
2755             rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2756                                   &*BBI, Def, NewReg);
2757             // Update the map with the new Phi name.
2758             VRMap[CurStageNum - np][Def] = NewReg;
2759             PhiOp2 = NewReg;
2760             if (VRMap[LastStageNum - np - 1].count(LoopVal))
2761               PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
2762 
2763             if (IsLast && np == NumPhis - 1)
2764               replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2765             continue;
2766           }
2767         } else if (InKernel && StageDiff > 0 &&
2768                    VRMap[CurStageNum - StageDiff - np].count(LoopVal))
2769           PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
2770       }
2771 
2772       const TargetRegisterClass *RC = MRI.getRegClass(Def);
2773       NewReg = MRI.createVirtualRegister(RC);
2774 
2775       MachineInstrBuilder NewPhi =
2776           BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2777                   TII->get(TargetOpcode::PHI), NewReg);
2778       NewPhi.addReg(PhiOp1).addMBB(BB1);
2779       NewPhi.addReg(PhiOp2).addMBB(BB2);
2780       if (np == 0)
2781         InstrMap[NewPhi] = &*BBI;
2782 
2783       // We define the Phis after creating the new pipelined code, so
2784       // we need to rename the Phi values in scheduled instructions.
2785 
2786       unsigned PrevReg = 0;
2787       if (InKernel && VRMap[PrevStage - np].count(LoopVal))
2788         PrevReg = VRMap[PrevStage - np][LoopVal];
2789       rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2790                             Def, NewReg, PrevReg);
2791       // If the Phi has been scheduled, use the new name for rewriting.
2792       if (VRMap[CurStageNum - np].count(Def)) {
2793         unsigned R = VRMap[CurStageNum - np][Def];
2794         rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2795                               R, NewReg);
2796       }
2797 
2798       // Check if we need to rename any uses that occurs after the loop. The
2799       // register to replace depends on whether the Phi is scheduled in the
2800       // epilog.
2801       if (IsLast && np == NumPhis - 1)
2802         replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2803 
2804       // In the kernel, a dependent Phi uses the value from this Phi.
2805       if (InKernel)
2806         PhiOp2 = NewReg;
2807 
2808       // Update the map with the new Phi name.
2809       VRMap[CurStageNum - np][Def] = NewReg;
2810     }
2811 
2812     while (NumPhis++ < NumStages) {
2813       rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, NumPhis,
2814                             &*BBI, Def, NewReg, 0);
2815     }
2816 
2817     // Check if we need to rename a Phi that has been eliminated due to
2818     // scheduling.
2819     if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
2820       replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
2821   }
2822 }
2823 
2824 /// Generate Phis for the specified block in the generated pipelined code.
2825 /// These are new Phis needed because the definition is scheduled after the
2826 /// use in the pipelened sequence.
2827 void SwingSchedulerDAG::generatePhis(
2828     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2829     MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2830     InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2831     bool IsLast) {
2832   // Compute the stage number that contains the initial Phi value, and
2833   // the Phi from the previous stage.
2834   unsigned PrologStage = 0;
2835   unsigned PrevStage = 0;
2836   unsigned StageDiff = CurStageNum - LastStageNum;
2837   bool InKernel = (StageDiff == 0);
2838   if (InKernel) {
2839     PrologStage = LastStageNum - 1;
2840     PrevStage = CurStageNum;
2841   } else {
2842     PrologStage = LastStageNum - StageDiff;
2843     PrevStage = LastStageNum + StageDiff - 1;
2844   }
2845 
2846   for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
2847                                    BBE = BB->instr_end();
2848        BBI != BBE; ++BBI) {
2849     for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
2850       MachineOperand &MO = BBI->getOperand(i);
2851       if (!MO.isReg() || !MO.isDef() ||
2852           !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2853         continue;
2854 
2855       int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2856       assert(StageScheduled != -1 && "Expecting scheduled instruction.");
2857       unsigned Def = MO.getReg();
2858       unsigned NumPhis = Schedule.getStagesForReg(Def, CurStageNum);
2859       // An instruction scheduled in stage 0 and is used after the loop
2860       // requires a phi in the epilog for the last definition from either
2861       // the kernel or prolog.
2862       if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
2863           hasUseAfterLoop(Def, BB, MRI))
2864         NumPhis = 1;
2865       if (!InKernel && (unsigned)StageScheduled > PrologStage)
2866         continue;
2867 
2868       unsigned PhiOp2 = VRMap[PrevStage][Def];
2869       if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
2870         if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
2871           PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
2872       // The number of Phis can't exceed the number of prolog stages. The
2873       // prolog stage number is zero based.
2874       if (NumPhis > PrologStage + 1 - StageScheduled)
2875         NumPhis = PrologStage + 1 - StageScheduled;
2876       for (unsigned np = 0; np < NumPhis; ++np) {
2877         unsigned PhiOp1 = VRMap[PrologStage][Def];
2878         if (np <= PrologStage)
2879           PhiOp1 = VRMap[PrologStage - np][Def];
2880         if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) {
2881           if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2882             PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2883           if (InstOp1->isPHI() && InstOp1->getParent() == NewBB)
2884             PhiOp1 = getInitPhiReg(*InstOp1, NewBB);
2885         }
2886         if (!InKernel)
2887           PhiOp2 = VRMap[PrevStage - np][Def];
2888 
2889         const TargetRegisterClass *RC = MRI.getRegClass(Def);
2890         unsigned NewReg = MRI.createVirtualRegister(RC);
2891 
2892         MachineInstrBuilder NewPhi =
2893             BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2894                     TII->get(TargetOpcode::PHI), NewReg);
2895         NewPhi.addReg(PhiOp1).addMBB(BB1);
2896         NewPhi.addReg(PhiOp2).addMBB(BB2);
2897         if (np == 0)
2898           InstrMap[NewPhi] = &*BBI;
2899 
2900         // Rewrite uses and update the map. The actions depend upon whether
2901         // we generating code for the kernel or epilog blocks.
2902         if (InKernel) {
2903           rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2904                                 &*BBI, PhiOp1, NewReg);
2905           rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2906                                 &*BBI, PhiOp2, NewReg);
2907 
2908           PhiOp2 = NewReg;
2909           VRMap[PrevStage - np - 1][Def] = NewReg;
2910         } else {
2911           VRMap[CurStageNum - np][Def] = NewReg;
2912           if (np == NumPhis - 1)
2913             rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2914                                   &*BBI, Def, NewReg);
2915         }
2916         if (IsLast && np == NumPhis - 1)
2917           replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2918       }
2919     }
2920   }
2921 }
2922 
2923 /// Remove instructions that generate values with no uses.
2924 /// Typically, these are induction variable operations that generate values
2925 /// used in the loop itself.  A dead instruction has a definition with
2926 /// no uses, or uses that occur in the original loop only.
2927 void SwingSchedulerDAG::removeDeadInstructions(MachineBasicBlock *KernelBB,
2928                                                MBBVectorTy &EpilogBBs) {
2929   // For each epilog block, check that the value defined by each instruction
2930   // is used.  If not, delete it.
2931   for (MBBVectorTy::reverse_iterator MBB = EpilogBBs.rbegin(),
2932                                      MBE = EpilogBBs.rend();
2933        MBB != MBE; ++MBB)
2934     for (MachineBasicBlock::reverse_instr_iterator MI = (*MBB)->instr_rbegin(),
2935                                                    ME = (*MBB)->instr_rend();
2936          MI != ME;) {
2937       // From DeadMachineInstructionElem. Don't delete inline assembly.
2938       if (MI->isInlineAsm()) {
2939         ++MI;
2940         continue;
2941       }
2942       bool SawStore = false;
2943       // Check if it's safe to remove the instruction due to side effects.
2944       // We can, and want to, remove Phis here.
2945       if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
2946         ++MI;
2947         continue;
2948       }
2949       bool used = true;
2950       for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
2951                                       MOE = MI->operands_end();
2952            MOI != MOE; ++MOI) {
2953         if (!MOI->isReg() || !MOI->isDef())
2954           continue;
2955         unsigned reg = MOI->getReg();
2956         // Assume physical registers are used, unless they are marked dead.
2957         if (TargetRegisterInfo::isPhysicalRegister(reg)) {
2958           used = !MOI->isDead();
2959           if (used)
2960             break;
2961           continue;
2962         }
2963         unsigned realUses = 0;
2964         for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(reg),
2965                                                EI = MRI.use_end();
2966              UI != EI; ++UI) {
2967           // Check if there are any uses that occur only in the original
2968           // loop.  If so, that's not a real use.
2969           if (UI->getParent()->getParent() != BB) {
2970             realUses++;
2971             used = true;
2972             break;
2973           }
2974         }
2975         if (realUses > 0)
2976           break;
2977         used = false;
2978       }
2979       if (!used) {
2980         LIS.RemoveMachineInstrFromMaps(*MI);
2981         MI++->eraseFromParent();
2982         continue;
2983       }
2984       ++MI;
2985     }
2986   // In the kernel block, check if we can remove a Phi that generates a value
2987   // used in an instruction removed in the epilog block.
2988   for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(),
2989                                    BBE = KernelBB->getFirstNonPHI();
2990        BBI != BBE;) {
2991     MachineInstr *MI = &*BBI;
2992     ++BBI;
2993     unsigned reg = MI->getOperand(0).getReg();
2994     if (MRI.use_begin(reg) == MRI.use_end()) {
2995       LIS.RemoveMachineInstrFromMaps(*MI);
2996       MI->eraseFromParent();
2997     }
2998   }
2999 }
3000 
3001 /// For loop carried definitions, we split the lifetime of a virtual register
3002 /// that has uses past the definition in the next iteration. A copy with a new
3003 /// virtual register is inserted before the definition, which helps with
3004 /// generating a better register assignment.
3005 ///
3006 ///   v1 = phi(a, v2)     v1 = phi(a, v2)
3007 ///   v2 = phi(b, v3)     v2 = phi(b, v3)
3008 ///   v3 = ..             v4 = copy v1
3009 ///   .. = V1             v3 = ..
3010 ///                       .. = v4
3011 void SwingSchedulerDAG::splitLifetimes(MachineBasicBlock *KernelBB,
3012                                        MBBVectorTy &EpilogBBs,
3013                                        SMSchedule &Schedule) {
3014   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3015   for (auto &PHI : KernelBB->phis()) {
3016     unsigned Def = PHI.getOperand(0).getReg();
3017     // Check for any Phi definition that used as an operand of another Phi
3018     // in the same block.
3019     for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
3020                                                  E = MRI.use_instr_end();
3021          I != E; ++I) {
3022       if (I->isPHI() && I->getParent() == KernelBB) {
3023         // Get the loop carried definition.
3024         unsigned LCDef = getLoopPhiReg(PHI, KernelBB);
3025         if (!LCDef)
3026           continue;
3027         MachineInstr *MI = MRI.getVRegDef(LCDef);
3028         if (!MI || MI->getParent() != KernelBB || MI->isPHI())
3029           continue;
3030         // Search through the rest of the block looking for uses of the Phi
3031         // definition. If one occurs, then split the lifetime.
3032         unsigned SplitReg = 0;
3033         for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
3034                                     KernelBB->instr_end()))
3035           if (BBJ.readsRegister(Def)) {
3036             // We split the lifetime when we find the first use.
3037             if (SplitReg == 0) {
3038               SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
3039               BuildMI(*KernelBB, MI, MI->getDebugLoc(),
3040                       TII->get(TargetOpcode::COPY), SplitReg)
3041                   .addReg(Def);
3042             }
3043             BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
3044           }
3045         if (!SplitReg)
3046           continue;
3047         // Search through each of the epilog blocks for any uses to be renamed.
3048         for (auto &Epilog : EpilogBBs)
3049           for (auto &I : *Epilog)
3050             if (I.readsRegister(Def))
3051               I.substituteRegister(Def, SplitReg, 0, *TRI);
3052         break;
3053       }
3054     }
3055   }
3056 }
3057 
3058 /// Remove the incoming block from the Phis in a basic block.
3059 static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
3060   for (MachineInstr &MI : *BB) {
3061     if (!MI.isPHI())
3062       break;
3063     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
3064       if (MI.getOperand(i + 1).getMBB() == Incoming) {
3065         MI.RemoveOperand(i + 1);
3066         MI.RemoveOperand(i);
3067         break;
3068       }
3069   }
3070 }
3071 
3072 /// Create branches from each prolog basic block to the appropriate epilog
3073 /// block.  These edges are needed if the loop ends before reaching the
3074 /// kernel.
3075 void SwingSchedulerDAG::addBranches(MBBVectorTy &PrologBBs,
3076                                     MachineBasicBlock *KernelBB,
3077                                     MBBVectorTy &EpilogBBs,
3078                                     SMSchedule &Schedule, ValueMapTy *VRMap) {
3079   assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
3080   MachineInstr *IndVar = Pass.LI.LoopInductionVar;
3081   MachineInstr *Cmp = Pass.LI.LoopCompare;
3082   MachineBasicBlock *LastPro = KernelBB;
3083   MachineBasicBlock *LastEpi = KernelBB;
3084 
3085   // Start from the blocks connected to the kernel and work "out"
3086   // to the first prolog and the last epilog blocks.
3087   SmallVector<MachineInstr *, 4> PrevInsts;
3088   unsigned MaxIter = PrologBBs.size() - 1;
3089   unsigned LC = UINT_MAX;
3090   unsigned LCMin = UINT_MAX;
3091   for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
3092     // Add branches to the prolog that go to the corresponding
3093     // epilog, and the fall-thru prolog/kernel block.
3094     MachineBasicBlock *Prolog = PrologBBs[j];
3095     MachineBasicBlock *Epilog = EpilogBBs[i];
3096     // We've executed one iteration, so decrement the loop count and check for
3097     // the loop end.
3098     SmallVector<MachineOperand, 4> Cond;
3099     // Check if the LOOP0 has already been removed. If so, then there is no need
3100     // to reduce the trip count.
3101     if (LC != 0)
3102       LC = TII->reduceLoopCount(*Prolog, IndVar, *Cmp, Cond, PrevInsts, j,
3103                                 MaxIter);
3104 
3105     // Record the value of the first trip count, which is used to determine if
3106     // branches and blocks can be removed for constant trip counts.
3107     if (LCMin == UINT_MAX)
3108       LCMin = LC;
3109 
3110     unsigned numAdded = 0;
3111     if (TargetRegisterInfo::isVirtualRegister(LC)) {
3112       Prolog->addSuccessor(Epilog);
3113       numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
3114     } else if (j >= LCMin) {
3115       Prolog->addSuccessor(Epilog);
3116       Prolog->removeSuccessor(LastPro);
3117       LastEpi->removeSuccessor(Epilog);
3118       numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
3119       removePhis(Epilog, LastEpi);
3120       // Remove the blocks that are no longer referenced.
3121       if (LastPro != LastEpi) {
3122         LastEpi->clear();
3123         LastEpi->eraseFromParent();
3124       }
3125       LastPro->clear();
3126       LastPro->eraseFromParent();
3127     } else {
3128       numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
3129       removePhis(Epilog, Prolog);
3130     }
3131     LastPro = Prolog;
3132     LastEpi = Epilog;
3133     for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
3134                                                    E = Prolog->instr_rend();
3135          I != E && numAdded > 0; ++I, --numAdded)
3136       updateInstruction(&*I, false, j, 0, Schedule, VRMap);
3137   }
3138 }
3139 
3140 /// Return true if we can compute the amount the instruction changes
3141 /// during each iteration. Set Delta to the amount of the change.
3142 bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
3143   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3144   unsigned BaseReg;
3145   int64_t Offset;
3146   if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI))
3147     return false;
3148 
3149   MachineRegisterInfo &MRI = MF.getRegInfo();
3150   // Check if there is a Phi. If so, get the definition in the loop.
3151   MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
3152   if (BaseDef && BaseDef->isPHI()) {
3153     BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
3154     BaseDef = MRI.getVRegDef(BaseReg);
3155   }
3156   if (!BaseDef)
3157     return false;
3158 
3159   int D = 0;
3160   if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
3161     return false;
3162 
3163   Delta = D;
3164   return true;
3165 }
3166 
3167 /// Update the memory operand with a new offset when the pipeliner
3168 /// generates a new copy of the instruction that refers to a
3169 /// different memory location.
3170 void SwingSchedulerDAG::updateMemOperands(MachineInstr &NewMI,
3171                                           MachineInstr &OldMI, unsigned Num) {
3172   if (Num == 0)
3173     return;
3174   // If the instruction has memory operands, then adjust the offset
3175   // when the instruction appears in different stages.
3176   unsigned NumRefs = NewMI.memoperands_end() - NewMI.memoperands_begin();
3177   if (NumRefs == 0)
3178     return;
3179   MachineInstr::mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NumRefs);
3180   unsigned Refs = 0;
3181   for (MachineMemOperand *MMO : NewMI.memoperands()) {
3182     if (MMO->isVolatile() || (MMO->isInvariant() && MMO->isDereferenceable()) ||
3183         (!MMO->getValue())) {
3184       NewMemRefs[Refs++] = MMO;
3185       continue;
3186     }
3187     unsigned Delta;
3188     if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
3189       int64_t AdjOffset = Delta * Num;
3190       NewMemRefs[Refs++] =
3191           MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize());
3192     } else {
3193       NewMI.dropMemRefs();
3194       return;
3195     }
3196   }
3197   NewMI.setMemRefs(NewMemRefs, NewMemRefs + NumRefs);
3198 }
3199 
3200 /// Clone the instruction for the new pipelined loop and update the
3201 /// memory operands, if needed.
3202 MachineInstr *SwingSchedulerDAG::cloneInstr(MachineInstr *OldMI,
3203                                             unsigned CurStageNum,
3204                                             unsigned InstStageNum) {
3205   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
3206   // Check for tied operands in inline asm instructions. This should be handled
3207   // elsewhere, but I'm not sure of the best solution.
3208   if (OldMI->isInlineAsm())
3209     for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
3210       const auto &MO = OldMI->getOperand(i);
3211       if (MO.isReg() && MO.isUse())
3212         break;
3213       unsigned UseIdx;
3214       if (OldMI->isRegTiedToUseOperand(i, &UseIdx))
3215         NewMI->tieOperands(i, UseIdx);
3216     }
3217   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
3218   return NewMI;
3219 }
3220 
3221 /// Clone the instruction for the new pipelined loop. If needed, this
3222 /// function updates the instruction using the values saved in the
3223 /// InstrChanges structure.
3224 MachineInstr *SwingSchedulerDAG::cloneAndChangeInstr(MachineInstr *OldMI,
3225                                                      unsigned CurStageNum,
3226                                                      unsigned InstStageNum,
3227                                                      SMSchedule &Schedule) {
3228   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
3229   DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3230       InstrChanges.find(getSUnit(OldMI));
3231   if (It != InstrChanges.end()) {
3232     std::pair<unsigned, int64_t> RegAndOffset = It->second;
3233     unsigned BasePos, OffsetPos;
3234     if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
3235       return nullptr;
3236     int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
3237     MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
3238     if (Schedule.stageScheduled(getSUnit(LoopDef)) > (signed)InstStageNum)
3239       NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
3240     NewMI->getOperand(OffsetPos).setImm(NewOffset);
3241   }
3242   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
3243   return NewMI;
3244 }
3245 
3246 /// Update the machine instruction with new virtual registers.  This
3247 /// function may change the defintions and/or uses.
3248 void SwingSchedulerDAG::updateInstruction(MachineInstr *NewMI, bool LastDef,
3249                                           unsigned CurStageNum,
3250                                           unsigned InstrStageNum,
3251                                           SMSchedule &Schedule,
3252                                           ValueMapTy *VRMap) {
3253   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
3254     MachineOperand &MO = NewMI->getOperand(i);
3255     if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
3256       continue;
3257     unsigned reg = MO.getReg();
3258     if (MO.isDef()) {
3259       // Create a new virtual register for the definition.
3260       const TargetRegisterClass *RC = MRI.getRegClass(reg);
3261       unsigned NewReg = MRI.createVirtualRegister(RC);
3262       MO.setReg(NewReg);
3263       VRMap[CurStageNum][reg] = NewReg;
3264       if (LastDef)
3265         replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
3266     } else if (MO.isUse()) {
3267       MachineInstr *Def = MRI.getVRegDef(reg);
3268       // Compute the stage that contains the last definition for instruction.
3269       int DefStageNum = Schedule.stageScheduled(getSUnit(Def));
3270       unsigned StageNum = CurStageNum;
3271       if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
3272         // Compute the difference in stages between the defintion and the use.
3273         unsigned StageDiff = (InstrStageNum - DefStageNum);
3274         // Make an adjustment to get the last definition.
3275         StageNum -= StageDiff;
3276       }
3277       if (VRMap[StageNum].count(reg))
3278         MO.setReg(VRMap[StageNum][reg]);
3279     }
3280   }
3281 }
3282 
3283 /// Return the instruction in the loop that defines the register.
3284 /// If the definition is a Phi, then follow the Phi operand to
3285 /// the instruction in the loop.
3286 MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) {
3287   SmallPtrSet<MachineInstr *, 8> Visited;
3288   MachineInstr *Def = MRI.getVRegDef(Reg);
3289   while (Def->isPHI()) {
3290     if (!Visited.insert(Def).second)
3291       break;
3292     for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
3293       if (Def->getOperand(i + 1).getMBB() == BB) {
3294         Def = MRI.getVRegDef(Def->getOperand(i).getReg());
3295         break;
3296       }
3297   }
3298   return Def;
3299 }
3300 
3301 /// Return the new name for the value from the previous stage.
3302 unsigned SwingSchedulerDAG::getPrevMapVal(unsigned StageNum, unsigned PhiStage,
3303                                           unsigned LoopVal, unsigned LoopStage,
3304                                           ValueMapTy *VRMap,
3305                                           MachineBasicBlock *BB) {
3306   unsigned PrevVal = 0;
3307   if (StageNum > PhiStage) {
3308     MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
3309     if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
3310       // The name is defined in the previous stage.
3311       PrevVal = VRMap[StageNum - 1][LoopVal];
3312     else if (VRMap[StageNum].count(LoopVal))
3313       // The previous name is defined in the current stage when the instruction
3314       // order is swapped.
3315       PrevVal = VRMap[StageNum][LoopVal];
3316     else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
3317       // The loop value hasn't yet been scheduled.
3318       PrevVal = LoopVal;
3319     else if (StageNum == PhiStage + 1)
3320       // The loop value is another phi, which has not been scheduled.
3321       PrevVal = getInitPhiReg(*LoopInst, BB);
3322     else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
3323       // The loop value is another phi, which has been scheduled.
3324       PrevVal =
3325           getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
3326                         LoopStage, VRMap, BB);
3327   }
3328   return PrevVal;
3329 }
3330 
3331 /// Rewrite the Phi values in the specified block to use the mappings
3332 /// from the initial operand. Once the Phi is scheduled, we switch
3333 /// to using the loop value instead of the Phi value, so those names
3334 /// do not need to be rewritten.
3335 void SwingSchedulerDAG::rewritePhiValues(MachineBasicBlock *NewBB,
3336                                          unsigned StageNum,
3337                                          SMSchedule &Schedule,
3338                                          ValueMapTy *VRMap,
3339                                          InstrMapTy &InstrMap) {
3340   for (auto &PHI : BB->phis()) {
3341     unsigned InitVal = 0;
3342     unsigned LoopVal = 0;
3343     getPhiRegs(PHI, BB, InitVal, LoopVal);
3344     unsigned PhiDef = PHI.getOperand(0).getReg();
3345 
3346     unsigned PhiStage =
3347         (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(PhiDef)));
3348     unsigned LoopStage =
3349         (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
3350     unsigned NumPhis = Schedule.getStagesForPhi(PhiDef);
3351     if (NumPhis > StageNum)
3352       NumPhis = StageNum;
3353     for (unsigned np = 0; np <= NumPhis; ++np) {
3354       unsigned NewVal =
3355           getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
3356       if (!NewVal)
3357         NewVal = InitVal;
3358       rewriteScheduledInstr(NewBB, Schedule, InstrMap, StageNum - np, np, &PHI,
3359                             PhiDef, NewVal);
3360     }
3361   }
3362 }
3363 
3364 /// Rewrite a previously scheduled instruction to use the register value
3365 /// from the new instruction. Make sure the instruction occurs in the
3366 /// basic block, and we don't change the uses in the new instruction.
3367 void SwingSchedulerDAG::rewriteScheduledInstr(
3368     MachineBasicBlock *BB, SMSchedule &Schedule, InstrMapTy &InstrMap,
3369     unsigned CurStageNum, unsigned PhiNum, MachineInstr *Phi, unsigned OldReg,
3370     unsigned NewReg, unsigned PrevReg) {
3371   bool InProlog = (CurStageNum < Schedule.getMaxStageCount());
3372   int StagePhi = Schedule.stageScheduled(getSUnit(Phi)) + PhiNum;
3373   // Rewrite uses that have been scheduled already to use the new
3374   // Phi register.
3375   for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(OldReg),
3376                                          EI = MRI.use_end();
3377        UI != EI;) {
3378     MachineOperand &UseOp = *UI;
3379     MachineInstr *UseMI = UseOp.getParent();
3380     ++UI;
3381     if (UseMI->getParent() != BB)
3382       continue;
3383     if (UseMI->isPHI()) {
3384       if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
3385         continue;
3386       if (getLoopPhiReg(*UseMI, BB) != OldReg)
3387         continue;
3388     }
3389     InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
3390     assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
3391     SUnit *OrigMISU = getSUnit(OrigInstr->second);
3392     int StageSched = Schedule.stageScheduled(OrigMISU);
3393     int CycleSched = Schedule.cycleScheduled(OrigMISU);
3394     unsigned ReplaceReg = 0;
3395     // This is the stage for the scheduled instruction.
3396     if (StagePhi == StageSched && Phi->isPHI()) {
3397       int CyclePhi = Schedule.cycleScheduled(getSUnit(Phi));
3398       if (PrevReg && InProlog)
3399         ReplaceReg = PrevReg;
3400       else if (PrevReg && !Schedule.isLoopCarried(this, *Phi) &&
3401                (CyclePhi <= CycleSched || OrigMISU->getInstr()->isPHI()))
3402         ReplaceReg = PrevReg;
3403       else
3404         ReplaceReg = NewReg;
3405     }
3406     // The scheduled instruction occurs before the scheduled Phi, and the
3407     // Phi is not loop carried.
3408     if (!InProlog && StagePhi + 1 == StageSched &&
3409         !Schedule.isLoopCarried(this, *Phi))
3410       ReplaceReg = NewReg;
3411     if (StagePhi > StageSched && Phi->isPHI())
3412       ReplaceReg = NewReg;
3413     if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
3414       ReplaceReg = NewReg;
3415     if (ReplaceReg) {
3416       MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
3417       UseOp.setReg(ReplaceReg);
3418     }
3419   }
3420 }
3421 
3422 /// Check if we can change the instruction to use an offset value from the
3423 /// previous iteration. If so, return true and set the base and offset values
3424 /// so that we can rewrite the load, if necessary.
3425 ///   v1 = Phi(v0, v3)
3426 ///   v2 = load v1, 0
3427 ///   v3 = post_store v1, 4, x
3428 /// This function enables the load to be rewritten as v2 = load v3, 4.
3429 bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
3430                                               unsigned &BasePos,
3431                                               unsigned &OffsetPos,
3432                                               unsigned &NewBase,
3433                                               int64_t &Offset) {
3434   // Get the load instruction.
3435   if (TII->isPostIncrement(*MI))
3436     return false;
3437   unsigned BasePosLd, OffsetPosLd;
3438   if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
3439     return false;
3440   unsigned BaseReg = MI->getOperand(BasePosLd).getReg();
3441 
3442   // Look for the Phi instruction.
3443   MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
3444   MachineInstr *Phi = MRI.getVRegDef(BaseReg);
3445   if (!Phi || !Phi->isPHI())
3446     return false;
3447   // Get the register defined in the loop block.
3448   unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
3449   if (!PrevReg)
3450     return false;
3451 
3452   // Check for the post-increment load/store instruction.
3453   MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
3454   if (!PrevDef || PrevDef == MI)
3455     return false;
3456 
3457   if (!TII->isPostIncrement(*PrevDef))
3458     return false;
3459 
3460   unsigned BasePos1 = 0, OffsetPos1 = 0;
3461   if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
3462     return false;
3463 
3464   // Make sure that the instructions do not access the same memory location in
3465   // the next iteration.
3466   int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
3467   int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
3468   MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3469   NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
3470   bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
3471   MF.DeleteMachineInstr(NewMI);
3472   if (!Disjoint)
3473     return false;
3474 
3475   // Set the return value once we determine that we return true.
3476   BasePos = BasePosLd;
3477   OffsetPos = OffsetPosLd;
3478   NewBase = PrevReg;
3479   Offset = StoreOffset;
3480   return true;
3481 }
3482 
3483 /// Apply changes to the instruction if needed. The changes are need
3484 /// to improve the scheduling and depend up on the final schedule.
3485 void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
3486                                          SMSchedule &Schedule) {
3487   SUnit *SU = getSUnit(MI);
3488   DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3489       InstrChanges.find(SU);
3490   if (It != InstrChanges.end()) {
3491     std::pair<unsigned, int64_t> RegAndOffset = It->second;
3492     unsigned BasePos, OffsetPos;
3493     if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
3494       return;
3495     unsigned BaseReg = MI->getOperand(BasePos).getReg();
3496     MachineInstr *LoopDef = findDefInLoop(BaseReg);
3497     int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
3498     int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
3499     int BaseStageNum = Schedule.stageScheduled(SU);
3500     int BaseCycleNum = Schedule.cycleScheduled(SU);
3501     if (BaseStageNum < DefStageNum) {
3502       MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3503       int OffsetDiff = DefStageNum - BaseStageNum;
3504       if (DefCycleNum < BaseCycleNum) {
3505         NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
3506         if (OffsetDiff > 0)
3507           --OffsetDiff;
3508       }
3509       int64_t NewOffset =
3510           MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
3511       NewMI->getOperand(OffsetPos).setImm(NewOffset);
3512       SU->setInstr(NewMI);
3513       MISUnitMap[NewMI] = SU;
3514       NewMIs.insert(NewMI);
3515     }
3516   }
3517 }
3518 
3519 /// Return true for an order or output dependence that is loop carried
3520 /// potentially. A dependence is loop carried if the destination defines a valu
3521 /// that may be used or defined by the source in a subsequent iteration.
3522 bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
3523                                          bool isSucc) {
3524   if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
3525       Dep.isArtificial())
3526     return false;
3527 
3528   if (!SwpPruneLoopCarried)
3529     return true;
3530 
3531   if (Dep.getKind() == SDep::Output)
3532     return true;
3533 
3534   MachineInstr *SI = Source->getInstr();
3535   MachineInstr *DI = Dep.getSUnit()->getInstr();
3536   if (!isSucc)
3537     std::swap(SI, DI);
3538   assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
3539 
3540   // Assume ordered loads and stores may have a loop carried dependence.
3541   if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
3542       SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
3543     return true;
3544 
3545   // Only chain dependences between a load and store can be loop carried.
3546   if (!DI->mayStore() || !SI->mayLoad())
3547     return false;
3548 
3549   unsigned DeltaS, DeltaD;
3550   if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
3551     return true;
3552 
3553   unsigned BaseRegS, BaseRegD;
3554   int64_t OffsetS, OffsetD;
3555   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3556   if (!TII->getMemOpBaseRegImmOfs(*SI, BaseRegS, OffsetS, TRI) ||
3557       !TII->getMemOpBaseRegImmOfs(*DI, BaseRegD, OffsetD, TRI))
3558     return true;
3559 
3560   if (BaseRegS != BaseRegD)
3561     return true;
3562 
3563   // Check that the base register is incremented by a constant value for each
3564   // iteration.
3565   MachineInstr *Def = MRI.getVRegDef(BaseRegS);
3566   if (!Def || !Def->isPHI())
3567     return true;
3568   unsigned InitVal = 0;
3569   unsigned LoopVal = 0;
3570   getPhiRegs(*Def, BB, InitVal, LoopVal);
3571   MachineInstr *LoopDef = MRI.getVRegDef(LoopVal);
3572   int D = 0;
3573   if (!LoopDef || !TII->getIncrementValue(*LoopDef, D))
3574     return true;
3575 
3576   uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
3577   uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
3578 
3579   // This is the main test, which checks the offset values and the loop
3580   // increment value to determine if the accesses may be loop carried.
3581   if (OffsetS >= OffsetD)
3582     return OffsetS + AccessSizeS > DeltaS;
3583   else
3584     return OffsetD + AccessSizeD > DeltaD;
3585 
3586   return true;
3587 }
3588 
3589 void SwingSchedulerDAG::postprocessDAG() {
3590   for (auto &M : Mutations)
3591     M->apply(this);
3592 }
3593 
3594 /// Try to schedule the node at the specified StartCycle and continue
3595 /// until the node is schedule or the EndCycle is reached.  This function
3596 /// returns true if the node is scheduled.  This routine may search either
3597 /// forward or backward for a place to insert the instruction based upon
3598 /// the relative values of StartCycle and EndCycle.
3599 bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
3600   bool forward = true;
3601   if (StartCycle > EndCycle)
3602     forward = false;
3603 
3604   // The terminating condition depends on the direction.
3605   int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
3606   for (int curCycle = StartCycle; curCycle != termCycle;
3607        forward ? ++curCycle : --curCycle) {
3608 
3609     // Add the already scheduled instructions at the specified cycle to the DFA.
3610     Resources->clearResources();
3611     for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
3612          checkCycle <= LastCycle; checkCycle += II) {
3613       std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
3614 
3615       for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(),
3616                                          E = cycleInstrs.end();
3617            I != E; ++I) {
3618         if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
3619           continue;
3620         assert(Resources->canReserveResources(*(*I)->getInstr()) &&
3621                "These instructions have already been scheduled.");
3622         Resources->reserveResources(*(*I)->getInstr());
3623       }
3624     }
3625     if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
3626         Resources->canReserveResources(*SU->getInstr())) {
3627       DEBUG({
3628         dbgs() << "\tinsert at cycle " << curCycle << " ";
3629         SU->getInstr()->dump();
3630       });
3631 
3632       ScheduledInstrs[curCycle].push_back(SU);
3633       InstrToCycle.insert(std::make_pair(SU, curCycle));
3634       if (curCycle > LastCycle)
3635         LastCycle = curCycle;
3636       if (curCycle < FirstCycle)
3637         FirstCycle = curCycle;
3638       return true;
3639     }
3640     DEBUG({
3641       dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
3642       SU->getInstr()->dump();
3643     });
3644   }
3645   return false;
3646 }
3647 
3648 // Return the cycle of the earliest scheduled instruction in the chain.
3649 int SMSchedule::earliestCycleInChain(const SDep &Dep) {
3650   SmallPtrSet<SUnit *, 8> Visited;
3651   SmallVector<SDep, 8> Worklist;
3652   Worklist.push_back(Dep);
3653   int EarlyCycle = INT_MAX;
3654   while (!Worklist.empty()) {
3655     const SDep &Cur = Worklist.pop_back_val();
3656     SUnit *PrevSU = Cur.getSUnit();
3657     if (Visited.count(PrevSU))
3658       continue;
3659     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
3660     if (it == InstrToCycle.end())
3661       continue;
3662     EarlyCycle = std::min(EarlyCycle, it->second);
3663     for (const auto &PI : PrevSU->Preds)
3664       if (PI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
3665         Worklist.push_back(PI);
3666     Visited.insert(PrevSU);
3667   }
3668   return EarlyCycle;
3669 }
3670 
3671 // Return the cycle of the latest scheduled instruction in the chain.
3672 int SMSchedule::latestCycleInChain(const SDep &Dep) {
3673   SmallPtrSet<SUnit *, 8> Visited;
3674   SmallVector<SDep, 8> Worklist;
3675   Worklist.push_back(Dep);
3676   int LateCycle = INT_MIN;
3677   while (!Worklist.empty()) {
3678     const SDep &Cur = Worklist.pop_back_val();
3679     SUnit *SuccSU = Cur.getSUnit();
3680     if (Visited.count(SuccSU))
3681       continue;
3682     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
3683     if (it == InstrToCycle.end())
3684       continue;
3685     LateCycle = std::max(LateCycle, it->second);
3686     for (const auto &SI : SuccSU->Succs)
3687       if (SI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
3688         Worklist.push_back(SI);
3689     Visited.insert(SuccSU);
3690   }
3691   return LateCycle;
3692 }
3693 
3694 /// If an instruction has a use that spans multiple iterations, then
3695 /// return true. These instructions are characterized by having a back-ege
3696 /// to a Phi, which contains a reference to another Phi.
3697 static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
3698   for (auto &P : SU->Preds)
3699     if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
3700       for (auto &S : P.getSUnit()->Succs)
3701         if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
3702           return P.getSUnit();
3703   return nullptr;
3704 }
3705 
3706 /// Compute the scheduling start slot for the instruction.  The start slot
3707 /// depends on any predecessor or successor nodes scheduled already.
3708 void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
3709                               int *MinEnd, int *MaxStart, int II,
3710                               SwingSchedulerDAG *DAG) {
3711   // Iterate over each instruction that has been scheduled already.  The start
3712   // slot computuation depends on whether the previously scheduled instruction
3713   // is a predecessor or successor of the specified instruction.
3714   for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
3715 
3716     // Iterate over each instruction in the current cycle.
3717     for (SUnit *I : getInstructions(cycle)) {
3718       // Because we're processing a DAG for the dependences, we recognize
3719       // the back-edge in recurrences by anti dependences.
3720       for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
3721         const SDep &Dep = SU->Preds[i];
3722         if (Dep.getSUnit() == I) {
3723           if (!DAG->isBackedge(SU, Dep)) {
3724             int EarlyStart = cycle + Dep.getLatency() -
3725                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3726             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
3727             if (DAG->isLoopCarriedDep(SU, Dep, false)) {
3728               int End = earliestCycleInChain(Dep) + (II - 1);
3729               *MinEnd = std::min(*MinEnd, End);
3730             }
3731           } else {
3732             int LateStart = cycle - Dep.getLatency() +
3733                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3734             *MinLateStart = std::min(*MinLateStart, LateStart);
3735           }
3736         }
3737         // For instruction that requires multiple iterations, make sure that
3738         // the dependent instruction is not scheduled past the definition.
3739         SUnit *BE = multipleIterations(I, DAG);
3740         if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
3741             !SU->isPred(I))
3742           *MinLateStart = std::min(*MinLateStart, cycle);
3743       }
3744       for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
3745         if (SU->Succs[i].getSUnit() == I) {
3746           const SDep &Dep = SU->Succs[i];
3747           if (!DAG->isBackedge(SU, Dep)) {
3748             int LateStart = cycle - Dep.getLatency() +
3749                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3750             *MinLateStart = std::min(*MinLateStart, LateStart);
3751             if (DAG->isLoopCarriedDep(SU, Dep)) {
3752               int Start = latestCycleInChain(Dep) + 1 - II;
3753               *MaxStart = std::max(*MaxStart, Start);
3754             }
3755           } else {
3756             int EarlyStart = cycle + Dep.getLatency() -
3757                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3758             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
3759           }
3760         }
3761       }
3762     }
3763   }
3764 }
3765 
3766 /// Order the instructions within a cycle so that the definitions occur
3767 /// before the uses. Returns true if the instruction is added to the start
3768 /// of the list, or false if added to the end.
3769 void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
3770                                  std::deque<SUnit *> &Insts) {
3771   MachineInstr *MI = SU->getInstr();
3772   bool OrderBeforeUse = false;
3773   bool OrderAfterDef = false;
3774   bool OrderBeforeDef = false;
3775   unsigned MoveDef = 0;
3776   unsigned MoveUse = 0;
3777   int StageInst1 = stageScheduled(SU);
3778 
3779   unsigned Pos = 0;
3780   for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
3781        ++I, ++Pos) {
3782     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3783       MachineOperand &MO = MI->getOperand(i);
3784       if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
3785         continue;
3786 
3787       unsigned Reg = MO.getReg();
3788       unsigned BasePos, OffsetPos;
3789       if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
3790         if (MI->getOperand(BasePos).getReg() == Reg)
3791           if (unsigned NewReg = SSD->getInstrBaseReg(SU))
3792             Reg = NewReg;
3793       bool Reads, Writes;
3794       std::tie(Reads, Writes) =
3795           (*I)->getInstr()->readsWritesVirtualRegister(Reg);
3796       if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
3797         OrderBeforeUse = true;
3798         if (MoveUse == 0)
3799           MoveUse = Pos;
3800       } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
3801         // Add the instruction after the scheduled instruction.
3802         OrderAfterDef = true;
3803         MoveDef = Pos;
3804       } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
3805         if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
3806           OrderBeforeUse = true;
3807           if (MoveUse == 0)
3808             MoveUse = Pos;
3809         } else {
3810           OrderAfterDef = true;
3811           MoveDef = Pos;
3812         }
3813       } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
3814         OrderBeforeUse = true;
3815         if (MoveUse == 0)
3816           MoveUse = Pos;
3817         if (MoveUse != 0) {
3818           OrderAfterDef = true;
3819           MoveDef = Pos - 1;
3820         }
3821       } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
3822         // Add the instruction before the scheduled instruction.
3823         OrderBeforeUse = true;
3824         if (MoveUse == 0)
3825           MoveUse = Pos;
3826       } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
3827                  isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
3828         if (MoveUse == 0) {
3829           OrderBeforeDef = true;
3830           MoveUse = Pos;
3831         }
3832       }
3833     }
3834     // Check for order dependences between instructions. Make sure the source
3835     // is ordered before the destination.
3836     for (auto &S : SU->Succs) {
3837       if (S.getSUnit() != *I)
3838         continue;
3839       if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3840         OrderBeforeUse = true;
3841         if (Pos < MoveUse)
3842           MoveUse = Pos;
3843       }
3844     }
3845     for (auto &P : SU->Preds) {
3846       if (P.getSUnit() != *I)
3847         continue;
3848       if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3849         OrderAfterDef = true;
3850         MoveDef = Pos;
3851       }
3852     }
3853   }
3854 
3855   // A circular dependence.
3856   if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
3857     OrderBeforeUse = false;
3858 
3859   // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
3860   // to a loop-carried dependence.
3861   if (OrderBeforeDef)
3862     OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
3863 
3864   // The uncommon case when the instruction order needs to be updated because
3865   // there is both a use and def.
3866   if (OrderBeforeUse && OrderAfterDef) {
3867     SUnit *UseSU = Insts.at(MoveUse);
3868     SUnit *DefSU = Insts.at(MoveDef);
3869     if (MoveUse > MoveDef) {
3870       Insts.erase(Insts.begin() + MoveUse);
3871       Insts.erase(Insts.begin() + MoveDef);
3872     } else {
3873       Insts.erase(Insts.begin() + MoveDef);
3874       Insts.erase(Insts.begin() + MoveUse);
3875     }
3876     orderDependence(SSD, UseSU, Insts);
3877     orderDependence(SSD, SU, Insts);
3878     orderDependence(SSD, DefSU, Insts);
3879     return;
3880   }
3881   // Put the new instruction first if there is a use in the list. Otherwise,
3882   // put it at the end of the list.
3883   if (OrderBeforeUse)
3884     Insts.push_front(SU);
3885   else
3886     Insts.push_back(SU);
3887 }
3888 
3889 /// Return true if the scheduled Phi has a loop carried operand.
3890 bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
3891   if (!Phi.isPHI())
3892     return false;
3893   assert(Phi.isPHI() && "Expecing a Phi.");
3894   SUnit *DefSU = SSD->getSUnit(&Phi);
3895   unsigned DefCycle = cycleScheduled(DefSU);
3896   int DefStage = stageScheduled(DefSU);
3897 
3898   unsigned InitVal = 0;
3899   unsigned LoopVal = 0;
3900   getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
3901   SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
3902   if (!UseSU)
3903     return true;
3904   if (UseSU->getInstr()->isPHI())
3905     return true;
3906   unsigned LoopCycle = cycleScheduled(UseSU);
3907   int LoopStage = stageScheduled(UseSU);
3908   return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
3909 }
3910 
3911 /// Return true if the instruction is a definition that is loop carried
3912 /// and defines the use on the next iteration.
3913 ///        v1 = phi(v2, v3)
3914 ///  (Def) v3 = op v1
3915 ///  (MO)   = v1
3916 /// If MO appears before Def, then then v1 and v3 may get assigned to the same
3917 /// register.
3918 bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
3919                                        MachineInstr *Def, MachineOperand &MO) {
3920   if (!MO.isReg())
3921     return false;
3922   if (Def->isPHI())
3923     return false;
3924   MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
3925   if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
3926     return false;
3927   if (!isLoopCarried(SSD, *Phi))
3928     return false;
3929   unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
3930   for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
3931     MachineOperand &DMO = Def->getOperand(i);
3932     if (!DMO.isReg() || !DMO.isDef())
3933       continue;
3934     if (DMO.getReg() == LoopReg)
3935       return true;
3936   }
3937   return false;
3938 }
3939 
3940 // Check if the generated schedule is valid. This function checks if
3941 // an instruction that uses a physical register is scheduled in a
3942 // different stage than the definition. The pipeliner does not handle
3943 // physical register values that may cross a basic block boundary.
3944 bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
3945   for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
3946     SUnit &SU = SSD->SUnits[i];
3947     if (!SU.hasPhysRegDefs)
3948       continue;
3949     int StageDef = stageScheduled(&SU);
3950     assert(StageDef != -1 && "Instruction should have been scheduled.");
3951     for (auto &SI : SU.Succs)
3952       if (SI.isAssignedRegDep())
3953         if (ST.getRegisterInfo()->isPhysicalRegister(SI.getReg()))
3954           if (stageScheduled(SI.getSUnit()) != StageDef)
3955             return false;
3956   }
3957   return true;
3958 }
3959 
3960 /// A property of the node order in swing-modulo-scheduling is
3961 /// that for nodes outside circuits the following holds:
3962 /// none of them is scheduled after both a successor and a
3963 /// predecessor.
3964 /// The method below checks whether the property is met.
3965 /// If not, debug information is printed and statistics information updated.
3966 /// Note that we do not use an assert statement.
3967 /// The reason is that although an invalid node oder may prevent
3968 /// the pipeliner from finding a pipelined schedule for arbitrary II,
3969 /// it does not lead to the generation of incorrect code.
3970 void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
3971 
3972   // a sorted vector that maps each SUnit to its index in the NodeOrder
3973   typedef std::pair<SUnit *, unsigned> UnitIndex;
3974   std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
3975 
3976   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
3977     Indices.push_back(std::make_pair(NodeOrder[i], i));
3978 
3979   auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
3980     return std::get<0>(i1) < std::get<0>(i2);
3981   };
3982 
3983   // sort, so that we can perform a binary search
3984   llvm::sort(Indices.begin(), Indices.end(), CompareKey);
3985 
3986   bool Valid = true;
3987   (void)Valid;
3988   // for each SUnit in the NodeOrder, check whether
3989   // it appears after both a successor and a predecessor
3990   // of the SUnit. If this is the case, and the SUnit
3991   // is not part of circuit, then the NodeOrder is not
3992   // valid.
3993   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
3994     SUnit *SU = NodeOrder[i];
3995     unsigned Index = i;
3996 
3997     bool PredBefore = false;
3998     bool SuccBefore = false;
3999 
4000     SUnit *Succ;
4001     SUnit *Pred;
4002     (void)Succ;
4003     (void)Pred;
4004 
4005     for (SDep &PredEdge : SU->Preds) {
4006       SUnit *PredSU = PredEdge.getSUnit();
4007       unsigned PredIndex =
4008           std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(),
4009                                         std::make_pair(PredSU, 0), CompareKey));
4010       if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
4011         PredBefore = true;
4012         Pred = PredSU;
4013         break;
4014       }
4015     }
4016 
4017     for (SDep &SuccEdge : SU->Succs) {
4018       SUnit *SuccSU = SuccEdge.getSUnit();
4019       unsigned SuccIndex =
4020           std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(),
4021                                         std::make_pair(SuccSU, 0), CompareKey));
4022       if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
4023         SuccBefore = true;
4024         Succ = SuccSU;
4025         break;
4026       }
4027     }
4028 
4029     if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
4030       // instructions in circuits are allowed to be scheduled
4031       // after both a successor and predecessor.
4032       bool InCircuit = std::any_of(
4033           Circuits.begin(), Circuits.end(),
4034           [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
4035       if (InCircuit)
4036         DEBUG(dbgs() << "In a circuit, predecessor ";);
4037       else {
4038         Valid = false;
4039         NumNodeOrderIssues++;
4040         DEBUG(dbgs() << "Predecessor ";);
4041       }
4042       DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
4043                    << " are scheduled before node " << SU->NodeNum << "\n";);
4044     }
4045   }
4046 
4047   DEBUG({
4048     if (!Valid)
4049       dbgs() << "Invalid node order found!\n";
4050   });
4051 }
4052 
4053 /// Attempt to fix the degenerate cases when the instruction serialization
4054 /// causes the register lifetimes to overlap. For example,
4055 ///   p' = store_pi(p, b)
4056 ///      = load p, offset
4057 /// In this case p and p' overlap, which means that two registers are needed.
4058 /// Instead, this function changes the load to use p' and updates the offset.
4059 void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
4060   unsigned OverlapReg = 0;
4061   unsigned NewBaseReg = 0;
4062   for (SUnit *SU : Instrs) {
4063     MachineInstr *MI = SU->getInstr();
4064     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
4065       const MachineOperand &MO = MI->getOperand(i);
4066       // Look for an instruction that uses p. The instruction occurs in the
4067       // same cycle but occurs later in the serialized order.
4068       if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
4069         // Check that the instruction appears in the InstrChanges structure,
4070         // which contains instructions that can have the offset updated.
4071         DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
4072           InstrChanges.find(SU);
4073         if (It != InstrChanges.end()) {
4074           unsigned BasePos, OffsetPos;
4075           // Update the base register and adjust the offset.
4076           if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
4077             MachineInstr *NewMI = MF.CloneMachineInstr(MI);
4078             NewMI->getOperand(BasePos).setReg(NewBaseReg);
4079             int64_t NewOffset =
4080                 MI->getOperand(OffsetPos).getImm() - It->second.second;
4081             NewMI->getOperand(OffsetPos).setImm(NewOffset);
4082             SU->setInstr(NewMI);
4083             MISUnitMap[NewMI] = SU;
4084             NewMIs.insert(NewMI);
4085           }
4086         }
4087         OverlapReg = 0;
4088         NewBaseReg = 0;
4089         break;
4090       }
4091       // Look for an instruction of the form p' = op(p), which uses and defines
4092       // two virtual registers that get allocated to the same physical register.
4093       unsigned TiedUseIdx = 0;
4094       if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
4095         // OverlapReg is p in the example above.
4096         OverlapReg = MI->getOperand(TiedUseIdx).getReg();
4097         // NewBaseReg is p' in the example above.
4098         NewBaseReg = MI->getOperand(i).getReg();
4099         break;
4100       }
4101     }
4102   }
4103 }
4104 
4105 /// After the schedule has been formed, call this function to combine
4106 /// the instructions from the different stages/cycles.  That is, this
4107 /// function creates a schedule that represents a single iteration.
4108 void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
4109   // Move all instructions to the first stage from later stages.
4110   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
4111     for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
4112          ++stage) {
4113       std::deque<SUnit *> &cycleInstrs =
4114           ScheduledInstrs[cycle + (stage * InitiationInterval)];
4115       for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
4116                                                  E = cycleInstrs.rend();
4117            I != E; ++I)
4118         ScheduledInstrs[cycle].push_front(*I);
4119     }
4120   }
4121   // Iterate over the definitions in each instruction, and compute the
4122   // stage difference for each use.  Keep the maximum value.
4123   for (auto &I : InstrToCycle) {
4124     int DefStage = stageScheduled(I.first);
4125     MachineInstr *MI = I.first->getInstr();
4126     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
4127       MachineOperand &Op = MI->getOperand(i);
4128       if (!Op.isReg() || !Op.isDef())
4129         continue;
4130 
4131       unsigned Reg = Op.getReg();
4132       unsigned MaxDiff = 0;
4133       bool PhiIsSwapped = false;
4134       for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(Reg),
4135                                              EI = MRI.use_end();
4136            UI != EI; ++UI) {
4137         MachineOperand &UseOp = *UI;
4138         MachineInstr *UseMI = UseOp.getParent();
4139         SUnit *SUnitUse = SSD->getSUnit(UseMI);
4140         int UseStage = stageScheduled(SUnitUse);
4141         unsigned Diff = 0;
4142         if (UseStage != -1 && UseStage >= DefStage)
4143           Diff = UseStage - DefStage;
4144         if (MI->isPHI()) {
4145           if (isLoopCarried(SSD, *MI))
4146             ++Diff;
4147           else
4148             PhiIsSwapped = true;
4149         }
4150         MaxDiff = std::max(Diff, MaxDiff);
4151       }
4152       RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
4153     }
4154   }
4155 
4156   // Erase all the elements in the later stages. Only one iteration should
4157   // remain in the scheduled list, and it contains all the instructions.
4158   for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
4159     ScheduledInstrs.erase(cycle);
4160 
4161   // Change the registers in instruction as specified in the InstrChanges
4162   // map. We need to use the new registers to create the correct order.
4163   for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
4164     SUnit *SU = &SSD->SUnits[i];
4165     SSD->applyInstrChange(SU->getInstr(), *this);
4166   }
4167 
4168   // Reorder the instructions in each cycle to fix and improve the
4169   // generated code.
4170   for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
4171     std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
4172     std::deque<SUnit *> newOrderPhi;
4173     for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
4174       SUnit *SU = cycleInstrs[i];
4175       if (SU->getInstr()->isPHI())
4176         newOrderPhi.push_back(SU);
4177     }
4178     std::deque<SUnit *> newOrderI;
4179     for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
4180       SUnit *SU = cycleInstrs[i];
4181       if (!SU->getInstr()->isPHI())
4182         orderDependence(SSD, SU, newOrderI);
4183     }
4184     // Replace the old order with the new order.
4185     cycleInstrs.swap(newOrderPhi);
4186     cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
4187     SSD->fixupRegisterOverlaps(cycleInstrs);
4188   }
4189 
4190   DEBUG(dump(););
4191 }
4192 
4193 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4194 /// Print the schedule information to the given output.
4195 void SMSchedule::print(raw_ostream &os) const {
4196   // Iterate over each cycle.
4197   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
4198     // Iterate over each instruction in the cycle.
4199     const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
4200     for (SUnit *CI : cycleInstrs->second) {
4201       os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
4202       os << "(" << CI->NodeNum << ") ";
4203       CI->getInstr()->print(os);
4204       os << "\n";
4205     }
4206   }
4207 }
4208 
4209 /// Utility function used for debugging to print the schedule.
4210 LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
4211 #endif
4212