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