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