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