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