1254f889dSBrendon Cahoon //===-- MachinePipeliner.cpp - Machine Software Pipeliner Pass ------------===//
2254f889dSBrendon Cahoon //
3254f889dSBrendon Cahoon //                     The LLVM Compiler Infrastructure
4254f889dSBrendon Cahoon //
5254f889dSBrendon Cahoon // This file is distributed under the University of Illinois Open Source
6254f889dSBrendon Cahoon // License. See LICENSE.TXT for details.
7254f889dSBrendon Cahoon //
8254f889dSBrendon Cahoon //===----------------------------------------------------------------------===//
9254f889dSBrendon Cahoon //
10254f889dSBrendon Cahoon // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
11254f889dSBrendon Cahoon //
12254f889dSBrendon Cahoon // Software pipelining (SWP) is an instruction scheduling technique for loops
13254f889dSBrendon Cahoon // that overlap loop iterations and explioits ILP via a compiler transformation.
14254f889dSBrendon Cahoon //
15254f889dSBrendon Cahoon // Swing Modulo Scheduling is an implementation of software pipelining
16254f889dSBrendon Cahoon // that generates schedules that are near optimal in terms of initiation
17254f889dSBrendon Cahoon // interval, register requirements, and stage count. See the papers:
18254f889dSBrendon Cahoon //
19254f889dSBrendon Cahoon // "Swing Modulo Scheduling: A Lifetime-Sensitive Approach", by J. Llosa,
20254f889dSBrendon Cahoon // A. Gonzalez, E. Ayguade, and M. Valero. In PACT '96 Processings of the 1996
21254f889dSBrendon Cahoon // Conference on Parallel Architectures and Compilation Techiniques.
22254f889dSBrendon Cahoon //
23254f889dSBrendon Cahoon // "Lifetime-Sensitive Modulo Scheduling in a Production Environment", by J.
24254f889dSBrendon Cahoon // Llosa, E. Ayguade, A. Gonzalez, M. Valero, and J. Eckhardt. In IEEE
25254f889dSBrendon Cahoon // Transactions on Computers, Vol. 50, No. 3, 2001.
26254f889dSBrendon Cahoon //
27254f889dSBrendon Cahoon // "An Implementation of Swing Modulo Scheduling With Extensions for
28254f889dSBrendon Cahoon // Superblocks", by T. Lattner, Master's Thesis, University of Illinois at
29254f889dSBrendon Cahoon // Urbana-Chambpain, 2005.
30254f889dSBrendon Cahoon //
31254f889dSBrendon Cahoon //
32254f889dSBrendon Cahoon // The SMS algorithm consists of three main steps after computing the minimal
33254f889dSBrendon Cahoon // initiation interval (MII).
34254f889dSBrendon Cahoon // 1) Analyze the dependence graph and compute information about each
35254f889dSBrendon Cahoon //    instruction in the graph.
36254f889dSBrendon Cahoon // 2) Order the nodes (instructions) by priority based upon the heuristics
37254f889dSBrendon Cahoon //    described in the algorithm.
38254f889dSBrendon Cahoon // 3) Attempt to schedule the nodes in the specified order using the MII.
39254f889dSBrendon Cahoon //
40254f889dSBrendon Cahoon // This SMS implementation is a target-independent back-end pass. When enabled,
41254f889dSBrendon Cahoon // the pass runs just prior to the register allocation pass, while the machine
42254f889dSBrendon Cahoon // IR is in SSA form. If software pipelining is successful, then the original
43254f889dSBrendon Cahoon // loop is replaced by the optimized loop. The optimized loop contains one or
44254f889dSBrendon Cahoon // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
45254f889dSBrendon Cahoon // the instructions cannot be scheduled in a given MII, we increase the MII by
46254f889dSBrendon Cahoon // one and try again.
47254f889dSBrendon Cahoon //
48254f889dSBrendon Cahoon // The SMS implementation is an extension of the ScheduleDAGInstrs class. We
49254f889dSBrendon Cahoon // represent loop carried dependences in the DAG as order edges to the Phi
50254f889dSBrendon Cahoon // nodes. We also perform several passes over the DAG to eliminate unnecessary
51254f889dSBrendon Cahoon // edges that inhibit the ability to pipeline. The implementation uses the
52254f889dSBrendon Cahoon // DFAPacketizer class to compute the minimum initiation interval and the check
53254f889dSBrendon Cahoon // where an instruction may be inserted in the pipelined schedule.
54254f889dSBrendon Cahoon //
55254f889dSBrendon Cahoon // In order for the SMS pass to work, several target specific hooks need to be
56254f889dSBrendon Cahoon // implemented to get information about the loop structure and to rewrite
57254f889dSBrendon Cahoon // instructions.
58254f889dSBrendon Cahoon //
59254f889dSBrendon Cahoon //===----------------------------------------------------------------------===//
60254f889dSBrendon Cahoon 
61cdc71612SEugene Zelenko #include "llvm/ADT/ArrayRef.h"
62cdc71612SEugene Zelenko #include "llvm/ADT/BitVector.h"
63254f889dSBrendon Cahoon #include "llvm/ADT/DenseMap.h"
64cdc71612SEugene Zelenko #include "llvm/ADT/iterator_range.h"
65254f889dSBrendon Cahoon #include "llvm/ADT/MapVector.h"
66254f889dSBrendon Cahoon #include "llvm/ADT/PriorityQueue.h"
67254f889dSBrendon Cahoon #include "llvm/ADT/SetVector.h"
68254f889dSBrendon Cahoon #include "llvm/ADT/SmallPtrSet.h"
69254f889dSBrendon Cahoon #include "llvm/ADT/SmallSet.h"
70cdc71612SEugene Zelenko #include "llvm/ADT/SmallVector.h"
71254f889dSBrendon Cahoon #include "llvm/ADT/Statistic.h"
72254f889dSBrendon Cahoon #include "llvm/Analysis/AliasAnalysis.h"
73cdc71612SEugene Zelenko #include "llvm/Analysis/MemoryLocation.h"
74254f889dSBrendon Cahoon #include "llvm/Analysis/ValueTracking.h"
75254f889dSBrendon Cahoon #include "llvm/CodeGen/DFAPacketizer.h"
76254f889dSBrendon Cahoon #include "llvm/CodeGen/LiveIntervalAnalysis.h"
77254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineBasicBlock.h"
78254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineDominators.h"
79cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineFunction.h"
80cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineFunctionPass.h"
81cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineInstr.h"
82254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineInstrBuilder.h"
83cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineInstrBundle.h"
84254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineLoopInfo.h"
85cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineMemOperand.h"
86cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineOperand.h"
87254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineRegisterInfo.h"
88254f889dSBrendon Cahoon #include "llvm/CodeGen/RegisterClassInfo.h"
89254f889dSBrendon Cahoon #include "llvm/CodeGen/RegisterPressure.h"
90cdc71612SEugene Zelenko #include "llvm/CodeGen/ScheduleDAG.h"
91254f889dSBrendon Cahoon #include "llvm/CodeGen/ScheduleDAGInstrs.h"
92cdc71612SEugene Zelenko #include "llvm/IR/Attributes.h"
93cdc71612SEugene Zelenko #include "llvm/IR/DebugLoc.h"
94254f889dSBrendon Cahoon #include "llvm/MC/MCInstrItineraries.h"
95cdc71612SEugene Zelenko #include "llvm/PassAnalysisSupport.h"
96cdc71612SEugene Zelenko #include "llvm/PassRegistry.h"
97cdc71612SEugene Zelenko #include "llvm/PassSupport.h"
98254f889dSBrendon Cahoon #include "llvm/Support/CommandLine.h"
99254f889dSBrendon Cahoon #include "llvm/Support/Debug.h"
100cdc71612SEugene Zelenko #include "llvm/Support/MathExtras.h"
101254f889dSBrendon Cahoon #include "llvm/Support/raw_ostream.h"
102254f889dSBrendon Cahoon #include "llvm/Target/TargetInstrInfo.h"
103254f889dSBrendon Cahoon #include "llvm/Target/TargetRegisterInfo.h"
104254f889dSBrendon Cahoon #include "llvm/Target/TargetSubtargetInfo.h"
105cdc71612SEugene Zelenko #include <algorithm>
106cdc71612SEugene Zelenko #include <cassert>
107254f889dSBrendon Cahoon #include <climits>
108cdc71612SEugene Zelenko #include <cstdint>
109254f889dSBrendon Cahoon #include <deque>
110cdc71612SEugene Zelenko #include <functional>
111cdc71612SEugene Zelenko #include <iterator>
112254f889dSBrendon Cahoon #include <map>
113cdc71612SEugene Zelenko #include <tuple>
114cdc71612SEugene Zelenko #include <utility>
115cdc71612SEugene Zelenko #include <vector>
116254f889dSBrendon Cahoon 
117254f889dSBrendon Cahoon using namespace llvm;
118254f889dSBrendon Cahoon 
119254f889dSBrendon Cahoon #define DEBUG_TYPE "pipeliner"
120254f889dSBrendon Cahoon 
121254f889dSBrendon Cahoon STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
122254f889dSBrendon Cahoon STATISTIC(NumPipelined, "Number of loops software pipelined");
123254f889dSBrendon Cahoon 
124254f889dSBrendon Cahoon /// A command line option to turn software pipelining on or off.
125b7d3311cSBenjamin Kramer static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
126b7d3311cSBenjamin Kramer                                cl::ZeroOrMore,
127b7d3311cSBenjamin Kramer                                cl::desc("Enable Software Pipelining"));
128254f889dSBrendon Cahoon 
129254f889dSBrendon Cahoon /// A command line option to enable SWP at -Os.
130254f889dSBrendon Cahoon static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
131254f889dSBrendon Cahoon                                       cl::desc("Enable SWP at Os."), cl::Hidden,
132254f889dSBrendon Cahoon                                       cl::init(false));
133254f889dSBrendon Cahoon 
134254f889dSBrendon Cahoon /// A command line argument to limit minimum initial interval for pipelining.
135254f889dSBrendon Cahoon static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
136254f889dSBrendon Cahoon                               cl::desc("Size limit for the the MII."),
137254f889dSBrendon Cahoon                               cl::Hidden, cl::init(27));
138254f889dSBrendon Cahoon 
139254f889dSBrendon Cahoon /// A command line argument to limit the number of stages in the pipeline.
140254f889dSBrendon Cahoon static cl::opt<int>
141254f889dSBrendon Cahoon     SwpMaxStages("pipeliner-max-stages",
142254f889dSBrendon Cahoon                  cl::desc("Maximum stages allowed in the generated scheduled."),
143254f889dSBrendon Cahoon                  cl::Hidden, cl::init(3));
144254f889dSBrendon Cahoon 
145254f889dSBrendon Cahoon /// A command line option to disable the pruning of chain dependences due to
146254f889dSBrendon Cahoon /// an unrelated Phi.
147254f889dSBrendon Cahoon static cl::opt<bool>
148254f889dSBrendon Cahoon     SwpPruneDeps("pipeliner-prune-deps",
149254f889dSBrendon Cahoon                  cl::desc("Prune dependences between unrelated Phi nodes."),
150254f889dSBrendon Cahoon                  cl::Hidden, cl::init(true));
151254f889dSBrendon Cahoon 
152254f889dSBrendon Cahoon /// A command line option to disable the pruning of loop carried order
153254f889dSBrendon Cahoon /// dependences.
154254f889dSBrendon Cahoon static cl::opt<bool>
155254f889dSBrendon Cahoon     SwpPruneLoopCarried("pipeliner-prune-loop-carried",
156254f889dSBrendon Cahoon                         cl::desc("Prune loop carried order dependences."),
157254f889dSBrendon Cahoon                         cl::Hidden, cl::init(true));
158254f889dSBrendon Cahoon 
159254f889dSBrendon Cahoon #ifndef NDEBUG
160254f889dSBrendon Cahoon static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
161254f889dSBrendon Cahoon #endif
162254f889dSBrendon Cahoon 
163254f889dSBrendon Cahoon static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
164254f889dSBrendon Cahoon                                      cl::ReallyHidden, cl::init(false),
165254f889dSBrendon Cahoon                                      cl::ZeroOrMore, cl::desc("Ignore RecMII"));
166254f889dSBrendon Cahoon 
167254f889dSBrendon Cahoon namespace {
168254f889dSBrendon Cahoon 
169254f889dSBrendon Cahoon class NodeSet;
170254f889dSBrendon Cahoon class SMSchedule;
171254f889dSBrendon Cahoon class SwingSchedulerDAG;
172254f889dSBrendon Cahoon 
173254f889dSBrendon Cahoon /// The main class in the implementation of the target independent
174254f889dSBrendon Cahoon /// software pipeliner pass.
175254f889dSBrendon Cahoon class MachinePipeliner : public MachineFunctionPass {
176254f889dSBrendon Cahoon public:
177254f889dSBrendon Cahoon   MachineFunction *MF = nullptr;
178254f889dSBrendon Cahoon   const MachineLoopInfo *MLI = nullptr;
179254f889dSBrendon Cahoon   const MachineDominatorTree *MDT = nullptr;
180254f889dSBrendon Cahoon   const InstrItineraryData *InstrItins;
181254f889dSBrendon Cahoon   const TargetInstrInfo *TII = nullptr;
182254f889dSBrendon Cahoon   RegisterClassInfo RegClassInfo;
183254f889dSBrendon Cahoon 
184254f889dSBrendon Cahoon #ifndef NDEBUG
185254f889dSBrendon Cahoon   static int NumTries;
186254f889dSBrendon Cahoon #endif
187254f889dSBrendon Cahoon   /// Cache the target analysis information about the loop.
188254f889dSBrendon Cahoon   struct LoopInfo {
189254f889dSBrendon Cahoon     MachineBasicBlock *TBB = nullptr;
190254f889dSBrendon Cahoon     MachineBasicBlock *FBB = nullptr;
191254f889dSBrendon Cahoon     SmallVector<MachineOperand, 4> BrCond;
192254f889dSBrendon Cahoon     MachineInstr *LoopInductionVar = nullptr;
193254f889dSBrendon Cahoon     MachineInstr *LoopCompare = nullptr;
194254f889dSBrendon Cahoon   };
195254f889dSBrendon Cahoon   LoopInfo LI;
196254f889dSBrendon Cahoon 
197254f889dSBrendon Cahoon   static char ID;
198254f889dSBrendon Cahoon   MachinePipeliner() : MachineFunctionPass(ID) {
199254f889dSBrendon Cahoon     initializeMachinePipelinerPass(*PassRegistry::getPassRegistry());
200254f889dSBrendon Cahoon   }
201254f889dSBrendon Cahoon 
202cdc71612SEugene Zelenko   bool runOnMachineFunction(MachineFunction &MF) override;
203254f889dSBrendon Cahoon 
204cdc71612SEugene Zelenko   void getAnalysisUsage(AnalysisUsage &AU) const override {
205254f889dSBrendon Cahoon     AU.addRequired<AAResultsWrapperPass>();
206254f889dSBrendon Cahoon     AU.addPreserved<AAResultsWrapperPass>();
207254f889dSBrendon Cahoon     AU.addRequired<MachineLoopInfo>();
208254f889dSBrendon Cahoon     AU.addRequired<MachineDominatorTree>();
209254f889dSBrendon Cahoon     AU.addRequired<LiveIntervals>();
210254f889dSBrendon Cahoon     MachineFunctionPass::getAnalysisUsage(AU);
211254f889dSBrendon Cahoon   }
212254f889dSBrendon Cahoon 
213254f889dSBrendon Cahoon private:
214254f889dSBrendon Cahoon   bool canPipelineLoop(MachineLoop &L);
215254f889dSBrendon Cahoon   bool scheduleLoop(MachineLoop &L);
216254f889dSBrendon Cahoon   bool swingModuloScheduler(MachineLoop &L);
217254f889dSBrendon Cahoon };
218254f889dSBrendon Cahoon 
219254f889dSBrendon Cahoon /// This class builds the dependence graph for the instructions in a loop,
220254f889dSBrendon Cahoon /// and attempts to schedule the instructions using the SMS algorithm.
221254f889dSBrendon Cahoon class SwingSchedulerDAG : public ScheduleDAGInstrs {
222254f889dSBrendon Cahoon   MachinePipeliner &Pass;
223254f889dSBrendon Cahoon   /// The minimum initiation interval between iterations for this schedule.
224254f889dSBrendon Cahoon   unsigned MII;
225254f889dSBrendon Cahoon   /// Set to true if a valid pipelined schedule is found for the loop.
226254f889dSBrendon Cahoon   bool Scheduled;
227254f889dSBrendon Cahoon   MachineLoop &Loop;
228254f889dSBrendon Cahoon   LiveIntervals &LIS;
229254f889dSBrendon Cahoon   const RegisterClassInfo &RegClassInfo;
230254f889dSBrendon Cahoon 
231254f889dSBrendon Cahoon   /// A toplogical ordering of the SUnits, which is needed for changing
232254f889dSBrendon Cahoon   /// dependences and iterating over the SUnits.
233254f889dSBrendon Cahoon   ScheduleDAGTopologicalSort Topo;
234254f889dSBrendon Cahoon 
235254f889dSBrendon Cahoon   struct NodeInfo {
236254f889dSBrendon Cahoon     int ASAP;
237254f889dSBrendon Cahoon     int ALAP;
238254f889dSBrendon Cahoon     NodeInfo() : ASAP(0), ALAP(0) {}
239254f889dSBrendon Cahoon   };
240254f889dSBrendon Cahoon   /// Computed properties for each node in the graph.
241254f889dSBrendon Cahoon   std::vector<NodeInfo> ScheduleInfo;
242254f889dSBrendon Cahoon 
243254f889dSBrendon Cahoon   enum OrderKind { BottomUp = 0, TopDown = 1 };
244254f889dSBrendon Cahoon   /// Computed node ordering for scheduling.
245254f889dSBrendon Cahoon   SetVector<SUnit *> NodeOrder;
246254f889dSBrendon Cahoon 
247254f889dSBrendon Cahoon   typedef SmallVector<NodeSet, 8> NodeSetType;
248254f889dSBrendon Cahoon   typedef DenseMap<unsigned, unsigned> ValueMapTy;
249254f889dSBrendon Cahoon   typedef SmallVectorImpl<MachineBasicBlock *> MBBVectorTy;
250254f889dSBrendon Cahoon   typedef DenseMap<MachineInstr *, MachineInstr *> InstrMapTy;
251254f889dSBrendon Cahoon 
252254f889dSBrendon Cahoon   /// Instructions to change when emitting the final schedule.
253254f889dSBrendon Cahoon   DenseMap<SUnit *, std::pair<unsigned, int64_t>> InstrChanges;
254254f889dSBrendon Cahoon 
255254f889dSBrendon Cahoon   /// We may create a new instruction, so remember it because it
256254f889dSBrendon Cahoon   /// must be deleted when the pass is finished.
257254f889dSBrendon Cahoon   SmallPtrSet<MachineInstr *, 4> NewMIs;
258254f889dSBrendon Cahoon 
259254f889dSBrendon Cahoon   /// Helper class to implement Johnson's circuit finding algorithm.
260254f889dSBrendon Cahoon   class Circuits {
261254f889dSBrendon Cahoon     std::vector<SUnit> &SUnits;
262254f889dSBrendon Cahoon     SetVector<SUnit *> Stack;
263254f889dSBrendon Cahoon     BitVector Blocked;
264254f889dSBrendon Cahoon     SmallVector<SmallPtrSet<SUnit *, 4>, 10> B;
265254f889dSBrendon Cahoon     SmallVector<SmallVector<int, 4>, 16> AdjK;
266254f889dSBrendon Cahoon     unsigned NumPaths;
267254f889dSBrendon Cahoon     static unsigned MaxPaths;
268254f889dSBrendon Cahoon 
269254f889dSBrendon Cahoon   public:
270254f889dSBrendon Cahoon     Circuits(std::vector<SUnit> &SUs)
271254f889dSBrendon Cahoon         : SUnits(SUs), Stack(), Blocked(SUs.size()), B(SUs.size()),
272254f889dSBrendon Cahoon           AdjK(SUs.size()) {}
273254f889dSBrendon Cahoon     /// Reset the data structures used in the circuit algorithm.
274254f889dSBrendon Cahoon     void reset() {
275254f889dSBrendon Cahoon       Stack.clear();
276254f889dSBrendon Cahoon       Blocked.reset();
277254f889dSBrendon Cahoon       B.assign(SUnits.size(), SmallPtrSet<SUnit *, 4>());
278254f889dSBrendon Cahoon       NumPaths = 0;
279254f889dSBrendon Cahoon     }
280254f889dSBrendon Cahoon     void createAdjacencyStructure(SwingSchedulerDAG *DAG);
281254f889dSBrendon Cahoon     bool circuit(int V, int S, NodeSetType &NodeSets, bool HasBackedge = false);
282254f889dSBrendon Cahoon     void unblock(int U);
283254f889dSBrendon Cahoon   };
284254f889dSBrendon Cahoon 
285254f889dSBrendon Cahoon public:
286254f889dSBrendon Cahoon   SwingSchedulerDAG(MachinePipeliner &P, MachineLoop &L, LiveIntervals &lis,
287254f889dSBrendon Cahoon                     const RegisterClassInfo &rci)
288254f889dSBrendon Cahoon       : ScheduleDAGInstrs(*P.MF, P.MLI, false), Pass(P), MII(0),
289254f889dSBrendon Cahoon         Scheduled(false), Loop(L), LIS(lis), RegClassInfo(rci),
290254f889dSBrendon Cahoon         Topo(SUnits, &ExitSU) {}
291254f889dSBrendon Cahoon 
292cdc71612SEugene Zelenko   void schedule() override;
293cdc71612SEugene Zelenko   void finishBlock() override;
294254f889dSBrendon Cahoon 
295254f889dSBrendon Cahoon   /// Return true if the loop kernel has been scheduled.
296254f889dSBrendon Cahoon   bool hasNewSchedule() { return Scheduled; }
297254f889dSBrendon Cahoon 
298254f889dSBrendon Cahoon   /// Return the earliest time an instruction may be scheduled.
299254f889dSBrendon Cahoon   int getASAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ASAP; }
300254f889dSBrendon Cahoon 
301254f889dSBrendon Cahoon   /// Return the latest time an instruction my be scheduled.
302254f889dSBrendon Cahoon   int getALAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ALAP; }
303254f889dSBrendon Cahoon 
304254f889dSBrendon Cahoon   /// The mobility function, which the the number of slots in which
305254f889dSBrendon Cahoon   /// an instruction may be scheduled.
306254f889dSBrendon Cahoon   int getMOV(SUnit *Node) { return getALAP(Node) - getASAP(Node); }
307254f889dSBrendon Cahoon 
308254f889dSBrendon Cahoon   /// The depth, in the dependence graph, for a node.
309254f889dSBrendon Cahoon   int getDepth(SUnit *Node) { return Node->getDepth(); }
310254f889dSBrendon Cahoon 
311254f889dSBrendon Cahoon   /// The height, in the dependence graph, for a node.
312254f889dSBrendon Cahoon   int getHeight(SUnit *Node) { return Node->getHeight(); }
313254f889dSBrendon Cahoon 
314254f889dSBrendon Cahoon   /// Return true if the dependence is a back-edge in the data dependence graph.
315254f889dSBrendon Cahoon   /// Since the DAG doesn't contain cycles, we represent a cycle in the graph
316254f889dSBrendon Cahoon   /// using an anti dependence from a Phi to an instruction.
317254f889dSBrendon Cahoon   bool isBackedge(SUnit *Source, const SDep &Dep) {
318254f889dSBrendon Cahoon     if (Dep.getKind() != SDep::Anti)
319254f889dSBrendon Cahoon       return false;
320254f889dSBrendon Cahoon     return Source->getInstr()->isPHI() || Dep.getSUnit()->getInstr()->isPHI();
321254f889dSBrendon Cahoon   }
322254f889dSBrendon Cahoon 
323254f889dSBrendon Cahoon   /// Return true if the dependence is an order dependence between non-Phis.
324254f889dSBrendon Cahoon   static bool isOrder(SUnit *Source, const SDep &Dep) {
325254f889dSBrendon Cahoon     if (Dep.getKind() != SDep::Order)
326254f889dSBrendon Cahoon       return false;
327254f889dSBrendon Cahoon     return (!Source->getInstr()->isPHI() &&
328254f889dSBrendon Cahoon             !Dep.getSUnit()->getInstr()->isPHI());
329254f889dSBrendon Cahoon   }
330254f889dSBrendon Cahoon 
331254f889dSBrendon Cahoon   bool isLoopCarriedOrder(SUnit *Source, const SDep &Dep, bool isSucc = true);
332254f889dSBrendon Cahoon 
333254f889dSBrendon Cahoon   /// The latency of the dependence.
334254f889dSBrendon Cahoon   unsigned getLatency(SUnit *Source, const SDep &Dep) {
335254f889dSBrendon Cahoon     // Anti dependences represent recurrences, so use the latency of the
336254f889dSBrendon Cahoon     // instruction on the back-edge.
337254f889dSBrendon Cahoon     if (Dep.getKind() == SDep::Anti) {
338254f889dSBrendon Cahoon       if (Source->getInstr()->isPHI())
339254f889dSBrendon Cahoon         return Dep.getSUnit()->Latency;
340254f889dSBrendon Cahoon       if (Dep.getSUnit()->getInstr()->isPHI())
341254f889dSBrendon Cahoon         return Source->Latency;
342254f889dSBrendon Cahoon       return Dep.getLatency();
343254f889dSBrendon Cahoon     }
344254f889dSBrendon Cahoon     return Dep.getLatency();
345254f889dSBrendon Cahoon   }
346254f889dSBrendon Cahoon 
347254f889dSBrendon Cahoon   /// The distance function, which indicates that operation V of iteration I
348254f889dSBrendon Cahoon   /// depends on operations U of iteration I-distance.
349254f889dSBrendon Cahoon   unsigned getDistance(SUnit *U, SUnit *V, const SDep &Dep) {
350254f889dSBrendon Cahoon     // Instructions that feed a Phi have a distance of 1. Computing larger
351254f889dSBrendon Cahoon     // values for arrays requires data dependence information.
352254f889dSBrendon Cahoon     if (V->getInstr()->isPHI() && Dep.getKind() == SDep::Anti)
353254f889dSBrendon Cahoon       return 1;
354254f889dSBrendon Cahoon     return 0;
355254f889dSBrendon Cahoon   }
356254f889dSBrendon Cahoon 
357254f889dSBrendon Cahoon   /// Set the Minimum Initiation Interval for this schedule attempt.
358254f889dSBrendon Cahoon   void setMII(unsigned mii) { MII = mii; }
359254f889dSBrendon Cahoon 
360254f889dSBrendon Cahoon   MachineInstr *applyInstrChange(MachineInstr *MI, SMSchedule &Schedule,
361254f889dSBrendon Cahoon                                  bool UpdateDAG = false);
362254f889dSBrendon Cahoon 
363254f889dSBrendon Cahoon   /// Return the new base register that was stored away for the changed
364254f889dSBrendon Cahoon   /// instruction.
365254f889dSBrendon Cahoon   unsigned getInstrBaseReg(SUnit *SU) {
366254f889dSBrendon Cahoon     DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
367254f889dSBrendon Cahoon         InstrChanges.find(SU);
368254f889dSBrendon Cahoon     if (It != InstrChanges.end())
369254f889dSBrendon Cahoon       return It->second.first;
370254f889dSBrendon Cahoon     return 0;
371254f889dSBrendon Cahoon   }
372254f889dSBrendon Cahoon 
373254f889dSBrendon Cahoon private:
374254f889dSBrendon Cahoon   void addLoopCarriedDependences(AliasAnalysis *AA);
375254f889dSBrendon Cahoon   void updatePhiDependences();
376254f889dSBrendon Cahoon   void changeDependences();
377254f889dSBrendon Cahoon   unsigned calculateResMII();
378254f889dSBrendon Cahoon   unsigned calculateRecMII(NodeSetType &RecNodeSets);
379254f889dSBrendon Cahoon   void findCircuits(NodeSetType &NodeSets);
380254f889dSBrendon Cahoon   void fuseRecs(NodeSetType &NodeSets);
381254f889dSBrendon Cahoon   void removeDuplicateNodes(NodeSetType &NodeSets);
382254f889dSBrendon Cahoon   void computeNodeFunctions(NodeSetType &NodeSets);
383254f889dSBrendon Cahoon   void registerPressureFilter(NodeSetType &NodeSets);
384254f889dSBrendon Cahoon   void colocateNodeSets(NodeSetType &NodeSets);
385254f889dSBrendon Cahoon   void checkNodeSets(NodeSetType &NodeSets);
386254f889dSBrendon Cahoon   void groupRemainingNodes(NodeSetType &NodeSets);
387254f889dSBrendon Cahoon   void addConnectedNodes(SUnit *SU, NodeSet &NewSet,
388254f889dSBrendon Cahoon                          SetVector<SUnit *> &NodesAdded);
389254f889dSBrendon Cahoon   void computeNodeOrder(NodeSetType &NodeSets);
390254f889dSBrendon Cahoon   bool schedulePipeline(SMSchedule &Schedule);
391254f889dSBrendon Cahoon   void generatePipelinedLoop(SMSchedule &Schedule);
392254f889dSBrendon Cahoon   void generateProlog(SMSchedule &Schedule, unsigned LastStage,
393254f889dSBrendon Cahoon                       MachineBasicBlock *KernelBB, ValueMapTy *VRMap,
394254f889dSBrendon Cahoon                       MBBVectorTy &PrologBBs);
395254f889dSBrendon Cahoon   void generateEpilog(SMSchedule &Schedule, unsigned LastStage,
396254f889dSBrendon Cahoon                       MachineBasicBlock *KernelBB, ValueMapTy *VRMap,
397254f889dSBrendon Cahoon                       MBBVectorTy &EpilogBBs, MBBVectorTy &PrologBBs);
398254f889dSBrendon Cahoon   void generateExistingPhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1,
399254f889dSBrendon Cahoon                             MachineBasicBlock *BB2, MachineBasicBlock *KernelBB,
400254f889dSBrendon Cahoon                             SMSchedule &Schedule, ValueMapTy *VRMap,
401254f889dSBrendon Cahoon                             InstrMapTy &InstrMap, unsigned LastStageNum,
402254f889dSBrendon Cahoon                             unsigned CurStageNum, bool IsLast);
403254f889dSBrendon Cahoon   void generatePhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1,
404254f889dSBrendon Cahoon                     MachineBasicBlock *BB2, MachineBasicBlock *KernelBB,
405254f889dSBrendon Cahoon                     SMSchedule &Schedule, ValueMapTy *VRMap,
406254f889dSBrendon Cahoon                     InstrMapTy &InstrMap, unsigned LastStageNum,
407254f889dSBrendon Cahoon                     unsigned CurStageNum, bool IsLast);
408254f889dSBrendon Cahoon   void removeDeadInstructions(MachineBasicBlock *KernelBB,
409254f889dSBrendon Cahoon                               MBBVectorTy &EpilogBBs);
410254f889dSBrendon Cahoon   void splitLifetimes(MachineBasicBlock *KernelBB, MBBVectorTy &EpilogBBs,
411254f889dSBrendon Cahoon                       SMSchedule &Schedule);
412254f889dSBrendon Cahoon   void addBranches(MBBVectorTy &PrologBBs, MachineBasicBlock *KernelBB,
413254f889dSBrendon Cahoon                    MBBVectorTy &EpilogBBs, SMSchedule &Schedule,
414254f889dSBrendon Cahoon                    ValueMapTy *VRMap);
415254f889dSBrendon Cahoon   bool computeDelta(MachineInstr &MI, unsigned &Delta);
416254f889dSBrendon Cahoon   void updateMemOperands(MachineInstr &NewMI, MachineInstr &OldMI,
417254f889dSBrendon Cahoon                          unsigned Num);
418254f889dSBrendon Cahoon   MachineInstr *cloneInstr(MachineInstr *OldMI, unsigned CurStageNum,
419254f889dSBrendon Cahoon                            unsigned InstStageNum);
420254f889dSBrendon Cahoon   MachineInstr *cloneAndChangeInstr(MachineInstr *OldMI, unsigned CurStageNum,
421254f889dSBrendon Cahoon                                     unsigned InstStageNum,
422254f889dSBrendon Cahoon                                     SMSchedule &Schedule);
423254f889dSBrendon Cahoon   void updateInstruction(MachineInstr *NewMI, bool LastDef,
424254f889dSBrendon Cahoon                          unsigned CurStageNum, unsigned InstStageNum,
425254f889dSBrendon Cahoon                          SMSchedule &Schedule, ValueMapTy *VRMap);
426254f889dSBrendon Cahoon   MachineInstr *findDefInLoop(unsigned Reg);
427254f889dSBrendon Cahoon   unsigned getPrevMapVal(unsigned StageNum, unsigned PhiStage, unsigned LoopVal,
428254f889dSBrendon Cahoon                          unsigned LoopStage, ValueMapTy *VRMap,
429254f889dSBrendon Cahoon                          MachineBasicBlock *BB);
430254f889dSBrendon Cahoon   void rewritePhiValues(MachineBasicBlock *NewBB, unsigned StageNum,
431254f889dSBrendon Cahoon                         SMSchedule &Schedule, ValueMapTy *VRMap,
432254f889dSBrendon Cahoon                         InstrMapTy &InstrMap);
433254f889dSBrendon Cahoon   void rewriteScheduledInstr(MachineBasicBlock *BB, SMSchedule &Schedule,
434254f889dSBrendon Cahoon                              InstrMapTy &InstrMap, unsigned CurStageNum,
435254f889dSBrendon Cahoon                              unsigned PhiNum, MachineInstr *Phi,
436254f889dSBrendon Cahoon                              unsigned OldReg, unsigned NewReg,
437254f889dSBrendon Cahoon                              unsigned PrevReg = 0);
438254f889dSBrendon Cahoon   bool canUseLastOffsetValue(MachineInstr *MI, unsigned &BasePos,
439254f889dSBrendon Cahoon                              unsigned &OffsetPos, unsigned &NewBase,
440254f889dSBrendon Cahoon                              int64_t &NewOffset);
441254f889dSBrendon Cahoon };
442254f889dSBrendon Cahoon 
443254f889dSBrendon Cahoon /// A NodeSet contains a set of SUnit DAG nodes with additional information
444254f889dSBrendon Cahoon /// that assigns a priority to the set.
445254f889dSBrendon Cahoon class NodeSet {
446254f889dSBrendon Cahoon   SetVector<SUnit *> Nodes;
447254f889dSBrendon Cahoon   bool HasRecurrence;
448254f889dSBrendon Cahoon   unsigned RecMII = 0;
449254f889dSBrendon Cahoon   int MaxMOV = 0;
450254f889dSBrendon Cahoon   int MaxDepth = 0;
451254f889dSBrendon Cahoon   unsigned Colocate = 0;
452254f889dSBrendon Cahoon   SUnit *ExceedPressure = nullptr;
453254f889dSBrendon Cahoon 
454254f889dSBrendon Cahoon public:
455254f889dSBrendon Cahoon   typedef SetVector<SUnit *>::const_iterator iterator;
456254f889dSBrendon Cahoon 
457254f889dSBrendon Cahoon   NodeSet() : Nodes(), HasRecurrence(false) {}
458254f889dSBrendon Cahoon 
459254f889dSBrendon Cahoon   NodeSet(iterator S, iterator E) : Nodes(S, E), HasRecurrence(true) {}
460254f889dSBrendon Cahoon 
461254f889dSBrendon Cahoon   bool insert(SUnit *SU) { return Nodes.insert(SU); }
462254f889dSBrendon Cahoon 
463254f889dSBrendon Cahoon   void insert(iterator S, iterator E) { Nodes.insert(S, E); }
464254f889dSBrendon Cahoon 
465254f889dSBrendon Cahoon   template <typename UnaryPredicate> bool remove_if(UnaryPredicate P) {
466254f889dSBrendon Cahoon     return Nodes.remove_if(P);
467254f889dSBrendon Cahoon   }
468254f889dSBrendon Cahoon 
469254f889dSBrendon Cahoon   unsigned count(SUnit *SU) const { return Nodes.count(SU); }
470254f889dSBrendon Cahoon 
471254f889dSBrendon Cahoon   bool hasRecurrence() { return HasRecurrence; };
472254f889dSBrendon Cahoon 
473254f889dSBrendon Cahoon   unsigned size() const { return Nodes.size(); }
474254f889dSBrendon Cahoon 
475254f889dSBrendon Cahoon   bool empty() const { return Nodes.empty(); }
476254f889dSBrendon Cahoon 
477254f889dSBrendon Cahoon   SUnit *getNode(unsigned i) const { return Nodes[i]; };
478254f889dSBrendon Cahoon 
479254f889dSBrendon Cahoon   void setRecMII(unsigned mii) { RecMII = mii; };
480254f889dSBrendon Cahoon 
481254f889dSBrendon Cahoon   void setColocate(unsigned c) { Colocate = c; };
482254f889dSBrendon Cahoon 
483254f889dSBrendon Cahoon   void setExceedPressure(SUnit *SU) { ExceedPressure = SU; }
484254f889dSBrendon Cahoon 
485254f889dSBrendon Cahoon   bool isExceedSU(SUnit *SU) { return ExceedPressure == SU; }
486254f889dSBrendon Cahoon 
487254f889dSBrendon Cahoon   int compareRecMII(NodeSet &RHS) { return RecMII - RHS.RecMII; }
488254f889dSBrendon Cahoon 
489254f889dSBrendon Cahoon   int getRecMII() { return RecMII; }
490254f889dSBrendon Cahoon 
491254f889dSBrendon Cahoon   /// Summarize node functions for the entire node set.
492254f889dSBrendon Cahoon   void computeNodeSetInfo(SwingSchedulerDAG *SSD) {
493254f889dSBrendon Cahoon     for (SUnit *SU : *this) {
494254f889dSBrendon Cahoon       MaxMOV = std::max(MaxMOV, SSD->getMOV(SU));
495254f889dSBrendon Cahoon       MaxDepth = std::max(MaxDepth, SSD->getDepth(SU));
496254f889dSBrendon Cahoon     }
497254f889dSBrendon Cahoon   }
498254f889dSBrendon Cahoon 
499254f889dSBrendon Cahoon   void clear() {
500254f889dSBrendon Cahoon     Nodes.clear();
501254f889dSBrendon Cahoon     RecMII = 0;
502254f889dSBrendon Cahoon     HasRecurrence = false;
503254f889dSBrendon Cahoon     MaxMOV = 0;
504254f889dSBrendon Cahoon     MaxDepth = 0;
505254f889dSBrendon Cahoon     Colocate = 0;
506254f889dSBrendon Cahoon     ExceedPressure = nullptr;
507254f889dSBrendon Cahoon   }
508254f889dSBrendon Cahoon 
509254f889dSBrendon Cahoon   operator SetVector<SUnit *> &() { return Nodes; }
510254f889dSBrendon Cahoon 
511254f889dSBrendon Cahoon   /// Sort the node sets by importance. First, rank them by recurrence MII,
512254f889dSBrendon Cahoon   /// then by mobility (least mobile done first), and finally by depth.
513254f889dSBrendon Cahoon   /// Each node set may contain a colocate value which is used as the first
514254f889dSBrendon Cahoon   /// tie breaker, if it's set.
515254f889dSBrendon Cahoon   bool operator>(const NodeSet &RHS) const {
516254f889dSBrendon Cahoon     if (RecMII == RHS.RecMII) {
517254f889dSBrendon Cahoon       if (Colocate != 0 && RHS.Colocate != 0 && Colocate != RHS.Colocate)
518254f889dSBrendon Cahoon         return Colocate < RHS.Colocate;
519254f889dSBrendon Cahoon       if (MaxMOV == RHS.MaxMOV)
520254f889dSBrendon Cahoon         return MaxDepth > RHS.MaxDepth;
521254f889dSBrendon Cahoon       return MaxMOV < RHS.MaxMOV;
522254f889dSBrendon Cahoon     }
523254f889dSBrendon Cahoon     return RecMII > RHS.RecMII;
524254f889dSBrendon Cahoon   }
525254f889dSBrendon Cahoon 
526254f889dSBrendon Cahoon   bool operator==(const NodeSet &RHS) const {
527254f889dSBrendon Cahoon     return RecMII == RHS.RecMII && MaxMOV == RHS.MaxMOV &&
528254f889dSBrendon Cahoon            MaxDepth == RHS.MaxDepth;
529254f889dSBrendon Cahoon   }
530254f889dSBrendon Cahoon 
531254f889dSBrendon Cahoon   bool operator!=(const NodeSet &RHS) const { return !operator==(RHS); }
532254f889dSBrendon Cahoon 
533254f889dSBrendon Cahoon   iterator begin() { return Nodes.begin(); }
534254f889dSBrendon Cahoon   iterator end() { return Nodes.end(); }
535254f889dSBrendon Cahoon 
536254f889dSBrendon Cahoon   void print(raw_ostream &os) const {
537254f889dSBrendon Cahoon     os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
538254f889dSBrendon Cahoon        << " depth " << MaxDepth << " col " << Colocate << "\n";
539254f889dSBrendon Cahoon     for (const auto &I : Nodes)
540254f889dSBrendon Cahoon       os << "   SU(" << I->NodeNum << ") " << *(I->getInstr());
541254f889dSBrendon Cahoon     os << "\n";
542254f889dSBrendon Cahoon   }
543254f889dSBrendon Cahoon 
544254f889dSBrendon Cahoon   void dump() const { print(dbgs()); }
545254f889dSBrendon Cahoon };
546254f889dSBrendon Cahoon 
547254f889dSBrendon Cahoon /// This class repesents the scheduled code.  The main data structure is a
548254f889dSBrendon Cahoon /// map from scheduled cycle to instructions.  During scheduling, the
549254f889dSBrendon Cahoon /// data structure explicitly represents all stages/iterations.   When
550254f889dSBrendon Cahoon /// the algorithm finshes, the schedule is collapsed into a single stage,
551254f889dSBrendon Cahoon /// which represents instructions from different loop iterations.
552254f889dSBrendon Cahoon ///
553254f889dSBrendon Cahoon /// The SMS algorithm allows negative values for cycles, so the first cycle
554254f889dSBrendon Cahoon /// in the schedule is the smallest cycle value.
555254f889dSBrendon Cahoon class SMSchedule {
556254f889dSBrendon Cahoon private:
557254f889dSBrendon Cahoon   /// Map from execution cycle to instructions.
558254f889dSBrendon Cahoon   DenseMap<int, std::deque<SUnit *>> ScheduledInstrs;
559254f889dSBrendon Cahoon 
560254f889dSBrendon Cahoon   /// Map from instruction to execution cycle.
561254f889dSBrendon Cahoon   std::map<SUnit *, int> InstrToCycle;
562254f889dSBrendon Cahoon 
563254f889dSBrendon Cahoon   /// Map for each register and the max difference between its uses and def.
564254f889dSBrendon Cahoon   /// The first element in the pair is the max difference in stages. The
565254f889dSBrendon Cahoon   /// second is true if the register defines a Phi value and loop value is
566254f889dSBrendon Cahoon   /// scheduled before the Phi.
567254f889dSBrendon Cahoon   std::map<unsigned, std::pair<unsigned, bool>> RegToStageDiff;
568254f889dSBrendon Cahoon 
569254f889dSBrendon Cahoon   /// Keep track of the first cycle value in the schedule.  It starts
570254f889dSBrendon Cahoon   /// as zero, but the algorithm allows negative values.
571254f889dSBrendon Cahoon   int FirstCycle;
572254f889dSBrendon Cahoon 
573254f889dSBrendon Cahoon   /// Keep track of the last cycle value in the schedule.
574254f889dSBrendon Cahoon   int LastCycle;
575254f889dSBrendon Cahoon 
576254f889dSBrendon Cahoon   /// The initiation interval (II) for the schedule.
577254f889dSBrendon Cahoon   int InitiationInterval;
578254f889dSBrendon Cahoon 
579254f889dSBrendon Cahoon   /// Target machine information.
580254f889dSBrendon Cahoon   const TargetSubtargetInfo &ST;
581254f889dSBrendon Cahoon 
582254f889dSBrendon Cahoon   /// Virtual register information.
583254f889dSBrendon Cahoon   MachineRegisterInfo &MRI;
584254f889dSBrendon Cahoon 
585254f889dSBrendon Cahoon   DFAPacketizer *Resources;
586254f889dSBrendon Cahoon 
587254f889dSBrendon Cahoon public:
588254f889dSBrendon Cahoon   SMSchedule(MachineFunction *mf)
589254f889dSBrendon Cahoon       : ST(mf->getSubtarget()), MRI(mf->getRegInfo()),
590254f889dSBrendon Cahoon         Resources(ST.getInstrInfo()->CreateTargetScheduleState(ST)) {
591254f889dSBrendon Cahoon     FirstCycle = 0;
592254f889dSBrendon Cahoon     LastCycle = 0;
593254f889dSBrendon Cahoon     InitiationInterval = 0;
594254f889dSBrendon Cahoon   }
595254f889dSBrendon Cahoon 
596254f889dSBrendon Cahoon   ~SMSchedule() {
597254f889dSBrendon Cahoon     ScheduledInstrs.clear();
598254f889dSBrendon Cahoon     InstrToCycle.clear();
599254f889dSBrendon Cahoon     RegToStageDiff.clear();
600254f889dSBrendon Cahoon     delete Resources;
601254f889dSBrendon Cahoon   }
602254f889dSBrendon Cahoon 
603254f889dSBrendon Cahoon   void reset() {
604254f889dSBrendon Cahoon     ScheduledInstrs.clear();
605254f889dSBrendon Cahoon     InstrToCycle.clear();
606254f889dSBrendon Cahoon     RegToStageDiff.clear();
607254f889dSBrendon Cahoon     FirstCycle = 0;
608254f889dSBrendon Cahoon     LastCycle = 0;
609254f889dSBrendon Cahoon     InitiationInterval = 0;
610254f889dSBrendon Cahoon   }
611254f889dSBrendon Cahoon 
612254f889dSBrendon Cahoon   /// Set the initiation interval for this schedule.
613254f889dSBrendon Cahoon   void setInitiationInterval(int ii) { InitiationInterval = ii; }
614254f889dSBrendon Cahoon 
615254f889dSBrendon Cahoon   /// Return the first cycle in the completed schedule.  This
616254f889dSBrendon Cahoon   /// can be a negative value.
617254f889dSBrendon Cahoon   int getFirstCycle() const { return FirstCycle; }
618254f889dSBrendon Cahoon 
619254f889dSBrendon Cahoon   /// Return the last cycle in the finalized schedule.
620254f889dSBrendon Cahoon   int getFinalCycle() const { return FirstCycle + InitiationInterval - 1; }
621254f889dSBrendon Cahoon 
622254f889dSBrendon Cahoon   /// Return the cycle of the earliest scheduled instruction in the dependence
623254f889dSBrendon Cahoon   /// chain.
624254f889dSBrendon Cahoon   int earliestCycleInChain(const SDep &Dep);
625254f889dSBrendon Cahoon 
626254f889dSBrendon Cahoon   /// Return the cycle of the latest scheduled instruction in the dependence
627254f889dSBrendon Cahoon   /// chain.
628254f889dSBrendon Cahoon   int latestCycleInChain(const SDep &Dep);
629254f889dSBrendon Cahoon 
630254f889dSBrendon Cahoon   void computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
631254f889dSBrendon Cahoon                     int *MinEnd, int *MaxStart, int II, SwingSchedulerDAG *DAG);
632254f889dSBrendon Cahoon   bool insert(SUnit *SU, int StartCycle, int EndCycle, int II);
633254f889dSBrendon Cahoon 
634254f889dSBrendon Cahoon   /// Iterators for the cycle to instruction map.
635254f889dSBrendon Cahoon   typedef DenseMap<int, std::deque<SUnit *>>::iterator sched_iterator;
636254f889dSBrendon Cahoon   typedef DenseMap<int, std::deque<SUnit *>>::const_iterator
637254f889dSBrendon Cahoon       const_sched_iterator;
638254f889dSBrendon Cahoon 
639254f889dSBrendon Cahoon   /// Return true if the instruction is scheduled at the specified stage.
640254f889dSBrendon Cahoon   bool isScheduledAtStage(SUnit *SU, unsigned StageNum) {
641254f889dSBrendon Cahoon     return (stageScheduled(SU) == (int)StageNum);
642254f889dSBrendon Cahoon   }
643254f889dSBrendon Cahoon 
644254f889dSBrendon Cahoon   /// Return the stage for a scheduled instruction.  Return -1 if
645254f889dSBrendon Cahoon   /// the instruction has not been scheduled.
646254f889dSBrendon Cahoon   int stageScheduled(SUnit *SU) const {
647254f889dSBrendon Cahoon     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
648254f889dSBrendon Cahoon     if (it == InstrToCycle.end())
649254f889dSBrendon Cahoon       return -1;
650254f889dSBrendon Cahoon     return (it->second - FirstCycle) / InitiationInterval;
651254f889dSBrendon Cahoon   }
652254f889dSBrendon Cahoon 
653254f889dSBrendon Cahoon   /// Return the cycle for a scheduled instruction. This function normalizes
654254f889dSBrendon Cahoon   /// the first cycle to be 0.
655254f889dSBrendon Cahoon   unsigned cycleScheduled(SUnit *SU) const {
656254f889dSBrendon Cahoon     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
657254f889dSBrendon Cahoon     assert(it != InstrToCycle.end() && "Instruction hasn't been scheduled.");
658254f889dSBrendon Cahoon     return (it->second - FirstCycle) % InitiationInterval;
659254f889dSBrendon Cahoon   }
660254f889dSBrendon Cahoon 
661254f889dSBrendon Cahoon   /// Return the maximum stage count needed for this schedule.
662254f889dSBrendon Cahoon   unsigned getMaxStageCount() {
663254f889dSBrendon Cahoon     return (LastCycle - FirstCycle) / InitiationInterval;
664254f889dSBrendon Cahoon   }
665254f889dSBrendon Cahoon 
666254f889dSBrendon Cahoon   /// Return the max. number of stages/iterations that can occur between a
667254f889dSBrendon Cahoon   /// register definition and its uses.
668254f889dSBrendon Cahoon   unsigned getStagesForReg(int Reg, unsigned CurStage) {
669254f889dSBrendon Cahoon     std::pair<unsigned, bool> Stages = RegToStageDiff[Reg];
670254f889dSBrendon Cahoon     if (CurStage > getMaxStageCount() && Stages.first == 0 && Stages.second)
671254f889dSBrendon Cahoon       return 1;
672254f889dSBrendon Cahoon     return Stages.first;
673254f889dSBrendon Cahoon   }
674254f889dSBrendon Cahoon 
675254f889dSBrendon Cahoon   /// The number of stages for a Phi is a little different than other
676254f889dSBrendon Cahoon   /// instructions. The minimum value computed in RegToStageDiff is 1
677254f889dSBrendon Cahoon   /// because we assume the Phi is needed for at least 1 iteration.
678254f889dSBrendon Cahoon   /// This is not the case if the loop value is scheduled prior to the
679254f889dSBrendon Cahoon   /// Phi in the same stage.  This function returns the number of stages
680254f889dSBrendon Cahoon   /// or iterations needed between the Phi definition and any uses.
681254f889dSBrendon Cahoon   unsigned getStagesForPhi(int Reg) {
682254f889dSBrendon Cahoon     std::pair<unsigned, bool> Stages = RegToStageDiff[Reg];
683254f889dSBrendon Cahoon     if (Stages.second)
684254f889dSBrendon Cahoon       return Stages.first;
685254f889dSBrendon Cahoon     return Stages.first - 1;
686254f889dSBrendon Cahoon   }
687254f889dSBrendon Cahoon 
688254f889dSBrendon Cahoon   /// Return the instructions that are scheduled at the specified cycle.
689254f889dSBrendon Cahoon   std::deque<SUnit *> &getInstructions(int cycle) {
690254f889dSBrendon Cahoon     return ScheduledInstrs[cycle];
691254f889dSBrendon Cahoon   }
692254f889dSBrendon Cahoon 
693254f889dSBrendon Cahoon   bool isValidSchedule(SwingSchedulerDAG *SSD);
694254f889dSBrendon Cahoon   void finalizeSchedule(SwingSchedulerDAG *SSD);
695254f889dSBrendon Cahoon   bool orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
696254f889dSBrendon Cahoon                        std::deque<SUnit *> &Insts);
697254f889dSBrendon Cahoon   bool isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi);
698254f889dSBrendon Cahoon   bool isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD, MachineInstr *Inst,
699254f889dSBrendon Cahoon                              MachineOperand &MO);
700254f889dSBrendon Cahoon   void print(raw_ostream &os) const;
701254f889dSBrendon Cahoon   void dump() const;
702254f889dSBrendon Cahoon };
703254f889dSBrendon Cahoon 
704254f889dSBrendon Cahoon } // end anonymous namespace
705254f889dSBrendon Cahoon 
706254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
707254f889dSBrendon Cahoon char MachinePipeliner::ID = 0;
708254f889dSBrendon Cahoon #ifndef NDEBUG
709254f889dSBrendon Cahoon int MachinePipeliner::NumTries = 0;
710254f889dSBrendon Cahoon #endif
711254f889dSBrendon Cahoon char &llvm::MachinePipelinerID = MachinePipeliner::ID;
712254f889dSBrendon Cahoon INITIALIZE_PASS_BEGIN(MachinePipeliner, "pipeliner",
713254f889dSBrendon Cahoon                       "Modulo Software Pipelining", false, false)
714254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
715254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
716254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
717254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
718254f889dSBrendon Cahoon INITIALIZE_PASS_END(MachinePipeliner, "pipeliner",
719254f889dSBrendon Cahoon                     "Modulo Software Pipelining", false, false)
720254f889dSBrendon Cahoon 
721254f889dSBrendon Cahoon /// The "main" function for implementing Swing Modulo Scheduling.
722254f889dSBrendon Cahoon bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
723254f889dSBrendon Cahoon   if (skipFunction(*mf.getFunction()))
724254f889dSBrendon Cahoon     return false;
725254f889dSBrendon Cahoon 
726254f889dSBrendon Cahoon   if (!EnableSWP)
727254f889dSBrendon Cahoon     return false;
728254f889dSBrendon Cahoon 
729254f889dSBrendon Cahoon   if (mf.getFunction()->getAttributes().hasAttribute(
730254f889dSBrendon Cahoon           AttributeSet::FunctionIndex, Attribute::OptimizeForSize) &&
731254f889dSBrendon Cahoon       !EnableSWPOptSize.getPosition())
732254f889dSBrendon Cahoon     return false;
733254f889dSBrendon Cahoon 
734254f889dSBrendon Cahoon   MF = &mf;
735254f889dSBrendon Cahoon   MLI = &getAnalysis<MachineLoopInfo>();
736254f889dSBrendon Cahoon   MDT = &getAnalysis<MachineDominatorTree>();
737254f889dSBrendon Cahoon   TII = MF->getSubtarget().getInstrInfo();
738254f889dSBrendon Cahoon   RegClassInfo.runOnMachineFunction(*MF);
739254f889dSBrendon Cahoon 
740254f889dSBrendon Cahoon   for (auto &L : *MLI)
741254f889dSBrendon Cahoon     scheduleLoop(*L);
742254f889dSBrendon Cahoon 
743254f889dSBrendon Cahoon   return false;
744254f889dSBrendon Cahoon }
745254f889dSBrendon Cahoon 
746254f889dSBrendon Cahoon /// Attempt to perform the SMS algorithm on the specified loop. This function is
747254f889dSBrendon Cahoon /// the main entry point for the algorithm.  The function identifies candidate
748254f889dSBrendon Cahoon /// loops, calculates the minimum initiation interval, and attempts to schedule
749254f889dSBrendon Cahoon /// the loop.
750254f889dSBrendon Cahoon bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
751254f889dSBrendon Cahoon   bool Changed = false;
752254f889dSBrendon Cahoon   for (auto &InnerLoop : L)
753254f889dSBrendon Cahoon     Changed |= scheduleLoop(*InnerLoop);
754254f889dSBrendon Cahoon 
755254f889dSBrendon Cahoon #ifndef NDEBUG
756254f889dSBrendon Cahoon   // Stop trying after reaching the limit (if any).
757254f889dSBrendon Cahoon   int Limit = SwpLoopLimit;
758254f889dSBrendon Cahoon   if (Limit >= 0) {
759254f889dSBrendon Cahoon     if (NumTries >= SwpLoopLimit)
760254f889dSBrendon Cahoon       return Changed;
761254f889dSBrendon Cahoon     NumTries++;
762254f889dSBrendon Cahoon   }
763254f889dSBrendon Cahoon #endif
764254f889dSBrendon Cahoon 
765254f889dSBrendon Cahoon   if (!canPipelineLoop(L))
766254f889dSBrendon Cahoon     return Changed;
767254f889dSBrendon Cahoon 
768254f889dSBrendon Cahoon   ++NumTrytoPipeline;
769254f889dSBrendon Cahoon 
770254f889dSBrendon Cahoon   Changed = swingModuloScheduler(L);
771254f889dSBrendon Cahoon 
772254f889dSBrendon Cahoon   return Changed;
773254f889dSBrendon Cahoon }
774254f889dSBrendon Cahoon 
775254f889dSBrendon Cahoon /// Return true if the loop can be software pipelined.  The algorithm is
776254f889dSBrendon Cahoon /// restricted to loops with a single basic block.  Make sure that the
777254f889dSBrendon Cahoon /// branch in the loop can be analyzed.
778254f889dSBrendon Cahoon bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
779254f889dSBrendon Cahoon   if (L.getNumBlocks() != 1)
780254f889dSBrendon Cahoon     return false;
781254f889dSBrendon Cahoon 
782254f889dSBrendon Cahoon   // Check if the branch can't be understood because we can't do pipelining
783254f889dSBrendon Cahoon   // if that's the case.
784254f889dSBrendon Cahoon   LI.TBB = nullptr;
785254f889dSBrendon Cahoon   LI.FBB = nullptr;
786254f889dSBrendon Cahoon   LI.BrCond.clear();
787254f889dSBrendon Cahoon   if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond))
788254f889dSBrendon Cahoon     return false;
789254f889dSBrendon Cahoon 
790254f889dSBrendon Cahoon   LI.LoopInductionVar = nullptr;
791254f889dSBrendon Cahoon   LI.LoopCompare = nullptr;
792254f889dSBrendon Cahoon   if (TII->analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare))
793254f889dSBrendon Cahoon     return false;
794254f889dSBrendon Cahoon 
795254f889dSBrendon Cahoon   if (!L.getLoopPreheader())
796254f889dSBrendon Cahoon     return false;
797254f889dSBrendon Cahoon 
798254f889dSBrendon Cahoon   // If any of the Phis contain subregs, then we can't pipeline
799254f889dSBrendon Cahoon   // because we don't know how to maintain subreg information in the
800254f889dSBrendon Cahoon   // VMap structure.
801254f889dSBrendon Cahoon   MachineBasicBlock *MBB = L.getHeader();
802254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator BBI = MBB->instr_begin(),
803254f889dSBrendon Cahoon                                    BBE = MBB->getFirstNonPHI();
804254f889dSBrendon Cahoon        BBI != BBE; ++BBI)
805254f889dSBrendon Cahoon     for (unsigned i = 1; i != BBI->getNumOperands(); i += 2)
806254f889dSBrendon Cahoon       if (BBI->getOperand(i).getSubReg() != 0)
807254f889dSBrendon Cahoon         return false;
808254f889dSBrendon Cahoon 
809254f889dSBrendon Cahoon   return true;
810254f889dSBrendon Cahoon }
811254f889dSBrendon Cahoon 
812254f889dSBrendon Cahoon /// The SMS algorithm consists of the following main steps:
813254f889dSBrendon Cahoon /// 1. Computation and analysis of the dependence graph.
814254f889dSBrendon Cahoon /// 2. Ordering of the nodes (instructions).
815254f889dSBrendon Cahoon /// 3. Attempt to Schedule the loop.
816254f889dSBrendon Cahoon bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
817254f889dSBrendon Cahoon   assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
818254f889dSBrendon Cahoon 
819254f889dSBrendon Cahoon   SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo);
820254f889dSBrendon Cahoon 
821254f889dSBrendon Cahoon   MachineBasicBlock *MBB = L.getHeader();
822254f889dSBrendon Cahoon   // The kernel should not include any terminator instructions.  These
823254f889dSBrendon Cahoon   // will be added back later.
824254f889dSBrendon Cahoon   SMS.startBlock(MBB);
825254f889dSBrendon Cahoon 
826254f889dSBrendon Cahoon   // Compute the number of 'real' instructions in the basic block by
827254f889dSBrendon Cahoon   // ignoring terminators.
828254f889dSBrendon Cahoon   unsigned size = MBB->size();
829254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
830254f889dSBrendon Cahoon                                    E = MBB->instr_end();
831254f889dSBrendon Cahoon        I != E; ++I, --size)
832254f889dSBrendon Cahoon     ;
833254f889dSBrendon Cahoon 
834254f889dSBrendon Cahoon   SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
835254f889dSBrendon Cahoon   SMS.schedule();
836254f889dSBrendon Cahoon   SMS.exitRegion();
837254f889dSBrendon Cahoon 
838254f889dSBrendon Cahoon   SMS.finishBlock();
839254f889dSBrendon Cahoon   return SMS.hasNewSchedule();
840254f889dSBrendon Cahoon }
841254f889dSBrendon Cahoon 
842254f889dSBrendon Cahoon /// We override the schedule function in ScheduleDAGInstrs to implement the
843254f889dSBrendon Cahoon /// scheduling part of the Swing Modulo Scheduling algorithm.
844254f889dSBrendon Cahoon void SwingSchedulerDAG::schedule() {
845254f889dSBrendon Cahoon   AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
846254f889dSBrendon Cahoon   buildSchedGraph(AA);
847254f889dSBrendon Cahoon   addLoopCarriedDependences(AA);
848254f889dSBrendon Cahoon   updatePhiDependences();
849254f889dSBrendon Cahoon   Topo.InitDAGTopologicalSorting();
850254f889dSBrendon Cahoon   changeDependences();
851254f889dSBrendon Cahoon   DEBUG({
852254f889dSBrendon Cahoon     for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
853254f889dSBrendon Cahoon       SUnits[su].dumpAll(this);
854254f889dSBrendon Cahoon   });
855254f889dSBrendon Cahoon 
856254f889dSBrendon Cahoon   NodeSetType NodeSets;
857254f889dSBrendon Cahoon   findCircuits(NodeSets);
858254f889dSBrendon Cahoon 
859254f889dSBrendon Cahoon   // Calculate the MII.
860254f889dSBrendon Cahoon   unsigned ResMII = calculateResMII();
861254f889dSBrendon Cahoon   unsigned RecMII = calculateRecMII(NodeSets);
862254f889dSBrendon Cahoon 
863254f889dSBrendon Cahoon   fuseRecs(NodeSets);
864254f889dSBrendon Cahoon 
865254f889dSBrendon Cahoon   // This flag is used for testing and can cause correctness problems.
866254f889dSBrendon Cahoon   if (SwpIgnoreRecMII)
867254f889dSBrendon Cahoon     RecMII = 0;
868254f889dSBrendon Cahoon 
869254f889dSBrendon Cahoon   MII = std::max(ResMII, RecMII);
870254f889dSBrendon Cahoon   DEBUG(dbgs() << "MII = " << MII << " (rec=" << RecMII << ", res=" << ResMII
871254f889dSBrendon Cahoon                << ")\n");
872254f889dSBrendon Cahoon 
873254f889dSBrendon Cahoon   // Can't schedule a loop without a valid MII.
874254f889dSBrendon Cahoon   if (MII == 0)
875254f889dSBrendon Cahoon     return;
876254f889dSBrendon Cahoon 
877254f889dSBrendon Cahoon   // Don't pipeline large loops.
878254f889dSBrendon Cahoon   if (SwpMaxMii != -1 && (int)MII > SwpMaxMii)
879254f889dSBrendon Cahoon     return;
880254f889dSBrendon Cahoon 
881254f889dSBrendon Cahoon   computeNodeFunctions(NodeSets);
882254f889dSBrendon Cahoon 
883254f889dSBrendon Cahoon   registerPressureFilter(NodeSets);
884254f889dSBrendon Cahoon 
885254f889dSBrendon Cahoon   colocateNodeSets(NodeSets);
886254f889dSBrendon Cahoon 
887254f889dSBrendon Cahoon   checkNodeSets(NodeSets);
888254f889dSBrendon Cahoon 
889254f889dSBrendon Cahoon   DEBUG({
890254f889dSBrendon Cahoon     for (auto &I : NodeSets) {
891254f889dSBrendon Cahoon       dbgs() << "  Rec NodeSet ";
892254f889dSBrendon Cahoon       I.dump();
893254f889dSBrendon Cahoon     }
894254f889dSBrendon Cahoon   });
895254f889dSBrendon Cahoon 
896254f889dSBrendon Cahoon   std::sort(NodeSets.begin(), NodeSets.end(), std::greater<NodeSet>());
897254f889dSBrendon Cahoon 
898254f889dSBrendon Cahoon   groupRemainingNodes(NodeSets);
899254f889dSBrendon Cahoon 
900254f889dSBrendon Cahoon   removeDuplicateNodes(NodeSets);
901254f889dSBrendon Cahoon 
902254f889dSBrendon Cahoon   DEBUG({
903254f889dSBrendon Cahoon     for (auto &I : NodeSets) {
904254f889dSBrendon Cahoon       dbgs() << "  NodeSet ";
905254f889dSBrendon Cahoon       I.dump();
906254f889dSBrendon Cahoon     }
907254f889dSBrendon Cahoon   });
908254f889dSBrendon Cahoon 
909254f889dSBrendon Cahoon   computeNodeOrder(NodeSets);
910254f889dSBrendon Cahoon 
911254f889dSBrendon Cahoon   SMSchedule Schedule(Pass.MF);
912254f889dSBrendon Cahoon   Scheduled = schedulePipeline(Schedule);
913254f889dSBrendon Cahoon 
914254f889dSBrendon Cahoon   if (!Scheduled)
915254f889dSBrendon Cahoon     return;
916254f889dSBrendon Cahoon 
917254f889dSBrendon Cahoon   unsigned numStages = Schedule.getMaxStageCount();
918254f889dSBrendon Cahoon   // No need to generate pipeline if there are no overlapped iterations.
919254f889dSBrendon Cahoon   if (numStages == 0)
920254f889dSBrendon Cahoon     return;
921254f889dSBrendon Cahoon 
922254f889dSBrendon Cahoon   // Check that the maximum stage count is less than user-defined limit.
923254f889dSBrendon Cahoon   if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages)
924254f889dSBrendon Cahoon     return;
925254f889dSBrendon Cahoon 
926254f889dSBrendon Cahoon   generatePipelinedLoop(Schedule);
927254f889dSBrendon Cahoon   ++NumPipelined;
928254f889dSBrendon Cahoon }
929254f889dSBrendon Cahoon 
930254f889dSBrendon Cahoon /// Clean up after the software pipeliner runs.
931254f889dSBrendon Cahoon void SwingSchedulerDAG::finishBlock() {
932254f889dSBrendon Cahoon   for (MachineInstr *I : NewMIs)
933254f889dSBrendon Cahoon     MF.DeleteMachineInstr(I);
934254f889dSBrendon Cahoon   NewMIs.clear();
935254f889dSBrendon Cahoon 
936254f889dSBrendon Cahoon   // Call the superclass.
937254f889dSBrendon Cahoon   ScheduleDAGInstrs::finishBlock();
938254f889dSBrendon Cahoon }
939254f889dSBrendon Cahoon 
940254f889dSBrendon Cahoon /// Return the register values for  the operands of a Phi instruction.
941254f889dSBrendon Cahoon /// This function assume the instruction is a Phi.
942254f889dSBrendon Cahoon static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
943254f889dSBrendon Cahoon                        unsigned &InitVal, unsigned &LoopVal) {
944254f889dSBrendon Cahoon   assert(Phi.isPHI() && "Expecting a Phi.");
945254f889dSBrendon Cahoon 
946254f889dSBrendon Cahoon   InitVal = 0;
947254f889dSBrendon Cahoon   LoopVal = 0;
948254f889dSBrendon Cahoon   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
949254f889dSBrendon Cahoon     if (Phi.getOperand(i + 1).getMBB() != Loop)
950254f889dSBrendon Cahoon       InitVal = Phi.getOperand(i).getReg();
951254f889dSBrendon Cahoon     else if (Phi.getOperand(i + 1).getMBB() == Loop)
952254f889dSBrendon Cahoon       LoopVal = Phi.getOperand(i).getReg();
953254f889dSBrendon Cahoon 
954254f889dSBrendon Cahoon   assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
955254f889dSBrendon Cahoon }
956254f889dSBrendon Cahoon 
957254f889dSBrendon Cahoon /// Return the Phi register value that comes from the incoming block.
958254f889dSBrendon Cahoon static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
959254f889dSBrendon Cahoon   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
960254f889dSBrendon Cahoon     if (Phi.getOperand(i + 1).getMBB() != LoopBB)
961254f889dSBrendon Cahoon       return Phi.getOperand(i).getReg();
962254f889dSBrendon Cahoon   return 0;
963254f889dSBrendon Cahoon }
964254f889dSBrendon Cahoon 
965254f889dSBrendon Cahoon /// Return the Phi register value that comes the the loop block.
966254f889dSBrendon Cahoon static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
967254f889dSBrendon Cahoon   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
968254f889dSBrendon Cahoon     if (Phi.getOperand(i + 1).getMBB() == LoopBB)
969254f889dSBrendon Cahoon       return Phi.getOperand(i).getReg();
970254f889dSBrendon Cahoon   return 0;
971254f889dSBrendon Cahoon }
972254f889dSBrendon Cahoon 
973254f889dSBrendon Cahoon /// Return true if SUb can be reached from SUa following the chain edges.
974254f889dSBrendon Cahoon static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
975254f889dSBrendon Cahoon   SmallPtrSet<SUnit *, 8> Visited;
976254f889dSBrendon Cahoon   SmallVector<SUnit *, 8> Worklist;
977254f889dSBrendon Cahoon   Worklist.push_back(SUa);
978254f889dSBrendon Cahoon   while (!Worklist.empty()) {
979254f889dSBrendon Cahoon     const SUnit *SU = Worklist.pop_back_val();
980254f889dSBrendon Cahoon     for (auto &SI : SU->Succs) {
981254f889dSBrendon Cahoon       SUnit *SuccSU = SI.getSUnit();
982254f889dSBrendon Cahoon       if (SI.getKind() == SDep::Order) {
983254f889dSBrendon Cahoon         if (Visited.count(SuccSU))
984254f889dSBrendon Cahoon           continue;
985254f889dSBrendon Cahoon         if (SuccSU == SUb)
986254f889dSBrendon Cahoon           return true;
987254f889dSBrendon Cahoon         Worklist.push_back(SuccSU);
988254f889dSBrendon Cahoon         Visited.insert(SuccSU);
989254f889dSBrendon Cahoon       }
990254f889dSBrendon Cahoon     }
991254f889dSBrendon Cahoon   }
992254f889dSBrendon Cahoon   return false;
993254f889dSBrendon Cahoon }
994254f889dSBrendon Cahoon 
995254f889dSBrendon Cahoon /// Return true if the instruction causes a chain between memory
996254f889dSBrendon Cahoon /// references before and after it.
997254f889dSBrendon Cahoon static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
998254f889dSBrendon Cahoon   return MI.isCall() || MI.hasUnmodeledSideEffects() ||
999254f889dSBrendon Cahoon          (MI.hasOrderedMemoryRef() &&
1000d98cf00cSJustin Lebar           (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
1001254f889dSBrendon Cahoon }
1002254f889dSBrendon Cahoon 
1003254f889dSBrendon Cahoon /// Return the underlying objects for the memory references of an instruction.
1004254f889dSBrendon Cahoon /// This function calls the code in ValueTracking, but first checks that the
1005254f889dSBrendon Cahoon /// instruction has a memory operand.
1006254f889dSBrendon Cahoon static void getUnderlyingObjects(MachineInstr *MI,
1007254f889dSBrendon Cahoon                                  SmallVectorImpl<Value *> &Objs,
1008254f889dSBrendon Cahoon                                  const DataLayout &DL) {
1009254f889dSBrendon Cahoon   if (!MI->hasOneMemOperand())
1010254f889dSBrendon Cahoon     return;
1011254f889dSBrendon Cahoon   MachineMemOperand *MM = *MI->memoperands_begin();
1012254f889dSBrendon Cahoon   if (!MM->getValue())
1013254f889dSBrendon Cahoon     return;
1014254f889dSBrendon Cahoon   GetUnderlyingObjects(const_cast<Value *>(MM->getValue()), Objs, DL);
1015254f889dSBrendon Cahoon }
1016254f889dSBrendon Cahoon 
1017254f889dSBrendon Cahoon /// Add a chain edge between a load and store if the store can be an
1018254f889dSBrendon Cahoon /// alias of the load on a subsequent iteration, i.e., a loop carried
1019254f889dSBrendon Cahoon /// dependence. This code is very similar to the code in ScheduleDAGInstrs
1020254f889dSBrendon Cahoon /// but that code doesn't create loop carried dependences.
1021254f889dSBrendon Cahoon void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
1022254f889dSBrendon Cahoon   MapVector<Value *, SmallVector<SUnit *, 4>> PendingLoads;
1023254f889dSBrendon Cahoon   for (auto &SU : SUnits) {
1024254f889dSBrendon Cahoon     MachineInstr &MI = *SU.getInstr();
1025254f889dSBrendon Cahoon     if (isDependenceBarrier(MI, AA))
1026254f889dSBrendon Cahoon       PendingLoads.clear();
1027254f889dSBrendon Cahoon     else if (MI.mayLoad()) {
1028254f889dSBrendon Cahoon       SmallVector<Value *, 4> Objs;
1029254f889dSBrendon Cahoon       getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
1030254f889dSBrendon Cahoon       for (auto V : Objs) {
1031254f889dSBrendon Cahoon         SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
1032254f889dSBrendon Cahoon         SUs.push_back(&SU);
1033254f889dSBrendon Cahoon       }
1034254f889dSBrendon Cahoon     } else if (MI.mayStore()) {
1035254f889dSBrendon Cahoon       SmallVector<Value *, 4> Objs;
1036254f889dSBrendon Cahoon       getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
1037254f889dSBrendon Cahoon       for (auto V : Objs) {
1038254f889dSBrendon Cahoon         MapVector<Value *, SmallVector<SUnit *, 4>>::iterator I =
1039254f889dSBrendon Cahoon             PendingLoads.find(V);
1040254f889dSBrendon Cahoon         if (I == PendingLoads.end())
1041254f889dSBrendon Cahoon           continue;
1042254f889dSBrendon Cahoon         for (auto Load : I->second) {
1043254f889dSBrendon Cahoon           if (isSuccOrder(Load, &SU))
1044254f889dSBrendon Cahoon             continue;
1045254f889dSBrendon Cahoon           MachineInstr &LdMI = *Load->getInstr();
1046254f889dSBrendon Cahoon           // First, perform the cheaper check that compares the base register.
1047254f889dSBrendon Cahoon           // If they are the same and the load offset is less than the store
1048254f889dSBrendon Cahoon           // offset, then mark the dependence as loop carried potentially.
1049254f889dSBrendon Cahoon           unsigned BaseReg1, BaseReg2;
1050254f889dSBrendon Cahoon           int64_t Offset1, Offset2;
1051254f889dSBrendon Cahoon           if (!TII->getMemOpBaseRegImmOfs(LdMI, BaseReg1, Offset1, TRI) ||
1052254f889dSBrendon Cahoon               !TII->getMemOpBaseRegImmOfs(MI, BaseReg2, Offset2, TRI)) {
1053254f889dSBrendon Cahoon             SU.addPred(SDep(Load, SDep::Barrier));
1054254f889dSBrendon Cahoon             continue;
1055254f889dSBrendon Cahoon           }
1056254f889dSBrendon Cahoon           if (BaseReg1 == BaseReg2 && (int)Offset1 < (int)Offset2) {
1057254f889dSBrendon Cahoon             assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI, AA) &&
1058254f889dSBrendon Cahoon                    "What happened to the chain edge?");
1059254f889dSBrendon Cahoon             SU.addPred(SDep(Load, SDep::Barrier));
1060254f889dSBrendon Cahoon             continue;
1061254f889dSBrendon Cahoon           }
1062254f889dSBrendon Cahoon           // Second, the more expensive check that uses alias analysis on the
1063254f889dSBrendon Cahoon           // base registers. If they alias, and the load offset is less than
1064254f889dSBrendon Cahoon           // the store offset, the mark the dependence as loop carried.
1065254f889dSBrendon Cahoon           if (!AA) {
1066254f889dSBrendon Cahoon             SU.addPred(SDep(Load, SDep::Barrier));
1067254f889dSBrendon Cahoon             continue;
1068254f889dSBrendon Cahoon           }
1069254f889dSBrendon Cahoon           MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
1070254f889dSBrendon Cahoon           MachineMemOperand *MMO2 = *MI.memoperands_begin();
1071254f889dSBrendon Cahoon           if (!MMO1->getValue() || !MMO2->getValue()) {
1072254f889dSBrendon Cahoon             SU.addPred(SDep(Load, SDep::Barrier));
1073254f889dSBrendon Cahoon             continue;
1074254f889dSBrendon Cahoon           }
1075254f889dSBrendon Cahoon           if (MMO1->getValue() == MMO2->getValue() &&
1076254f889dSBrendon Cahoon               MMO1->getOffset() <= MMO2->getOffset()) {
1077254f889dSBrendon Cahoon             SU.addPred(SDep(Load, SDep::Barrier));
1078254f889dSBrendon Cahoon             continue;
1079254f889dSBrendon Cahoon           }
1080254f889dSBrendon Cahoon           AliasResult AAResult = AA->alias(
1081254f889dSBrendon Cahoon               MemoryLocation(MMO1->getValue(), MemoryLocation::UnknownSize,
1082254f889dSBrendon Cahoon                              MMO1->getAAInfo()),
1083254f889dSBrendon Cahoon               MemoryLocation(MMO2->getValue(), MemoryLocation::UnknownSize,
1084254f889dSBrendon Cahoon                              MMO2->getAAInfo()));
1085254f889dSBrendon Cahoon 
1086254f889dSBrendon Cahoon           if (AAResult != NoAlias)
1087254f889dSBrendon Cahoon             SU.addPred(SDep(Load, SDep::Barrier));
1088254f889dSBrendon Cahoon         }
1089254f889dSBrendon Cahoon       }
1090254f889dSBrendon Cahoon     }
1091254f889dSBrendon Cahoon   }
1092254f889dSBrendon Cahoon }
1093254f889dSBrendon Cahoon 
1094254f889dSBrendon Cahoon /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
1095254f889dSBrendon Cahoon /// processes dependences for PHIs. This function adds true dependences
1096254f889dSBrendon Cahoon /// from a PHI to a use, and a loop carried dependence from the use to the
1097254f889dSBrendon Cahoon /// PHI. The loop carried dependence is represented as an anti dependence
1098254f889dSBrendon Cahoon /// edge. This function also removes chain dependences between unrelated
1099254f889dSBrendon Cahoon /// PHIs.
1100254f889dSBrendon Cahoon void SwingSchedulerDAG::updatePhiDependences() {
1101254f889dSBrendon Cahoon   SmallVector<SDep, 4> RemoveDeps;
1102254f889dSBrendon Cahoon   const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
1103254f889dSBrendon Cahoon 
1104254f889dSBrendon Cahoon   // Iterate over each DAG node.
1105254f889dSBrendon Cahoon   for (SUnit &I : SUnits) {
1106254f889dSBrendon Cahoon     RemoveDeps.clear();
1107254f889dSBrendon Cahoon     // Set to true if the instruction has an operand defined by a Phi.
1108254f889dSBrendon Cahoon     unsigned HasPhiUse = 0;
1109254f889dSBrendon Cahoon     unsigned HasPhiDef = 0;
1110254f889dSBrendon Cahoon     MachineInstr *MI = I.getInstr();
1111254f889dSBrendon Cahoon     // Iterate over each operand, and we process the definitions.
1112254f889dSBrendon Cahoon     for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
1113254f889dSBrendon Cahoon                                     MOE = MI->operands_end();
1114254f889dSBrendon Cahoon          MOI != MOE; ++MOI) {
1115254f889dSBrendon Cahoon       if (!MOI->isReg())
1116254f889dSBrendon Cahoon         continue;
1117254f889dSBrendon Cahoon       unsigned Reg = MOI->getReg();
1118254f889dSBrendon Cahoon       if (MOI->isDef()) {
1119254f889dSBrendon Cahoon         // If the register is used by a Phi, then create an anti dependence.
1120254f889dSBrendon Cahoon         for (MachineRegisterInfo::use_instr_iterator
1121254f889dSBrendon Cahoon                  UI = MRI.use_instr_begin(Reg),
1122254f889dSBrendon Cahoon                  UE = MRI.use_instr_end();
1123254f889dSBrendon Cahoon              UI != UE; ++UI) {
1124254f889dSBrendon Cahoon           MachineInstr *UseMI = &*UI;
1125254f889dSBrendon Cahoon           SUnit *SU = getSUnit(UseMI);
1126cdc71612SEugene Zelenko           if (SU != nullptr && UseMI->isPHI()) {
1127254f889dSBrendon Cahoon             if (!MI->isPHI()) {
1128254f889dSBrendon Cahoon               SDep Dep(SU, SDep::Anti, Reg);
1129254f889dSBrendon Cahoon               I.addPred(Dep);
1130254f889dSBrendon Cahoon             } else {
1131254f889dSBrendon Cahoon               HasPhiDef = Reg;
1132254f889dSBrendon Cahoon               // Add a chain edge to a dependent Phi that isn't an existing
1133254f889dSBrendon Cahoon               // predecessor.
1134254f889dSBrendon Cahoon               if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
1135254f889dSBrendon Cahoon                 I.addPred(SDep(SU, SDep::Barrier));
1136254f889dSBrendon Cahoon             }
1137254f889dSBrendon Cahoon           }
1138254f889dSBrendon Cahoon         }
1139254f889dSBrendon Cahoon       } else if (MOI->isUse()) {
1140254f889dSBrendon Cahoon         // If the register is defined by a Phi, then create a true dependence.
1141254f889dSBrendon Cahoon         MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
1142cdc71612SEugene Zelenko         if (DefMI == nullptr)
1143254f889dSBrendon Cahoon           continue;
1144254f889dSBrendon Cahoon         SUnit *SU = getSUnit(DefMI);
1145cdc71612SEugene Zelenko         if (SU != nullptr && DefMI->isPHI()) {
1146254f889dSBrendon Cahoon           if (!MI->isPHI()) {
1147254f889dSBrendon Cahoon             SDep Dep(SU, SDep::Data, Reg);
1148254f889dSBrendon Cahoon             Dep.setLatency(0);
1149254f889dSBrendon Cahoon             ST.adjustSchedDependency(SU, &I, Dep);
1150254f889dSBrendon Cahoon             I.addPred(Dep);
1151254f889dSBrendon Cahoon           } else {
1152254f889dSBrendon Cahoon             HasPhiUse = Reg;
1153254f889dSBrendon Cahoon             // Add a chain edge to a dependent Phi that isn't an existing
1154254f889dSBrendon Cahoon             // predecessor.
1155254f889dSBrendon Cahoon             if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
1156254f889dSBrendon Cahoon               I.addPred(SDep(SU, SDep::Barrier));
1157254f889dSBrendon Cahoon           }
1158254f889dSBrendon Cahoon         }
1159254f889dSBrendon Cahoon       }
1160254f889dSBrendon Cahoon     }
1161254f889dSBrendon Cahoon     // Remove order dependences from an unrelated Phi.
1162254f889dSBrendon Cahoon     if (!SwpPruneDeps)
1163254f889dSBrendon Cahoon       continue;
1164254f889dSBrendon Cahoon     for (auto &PI : I.Preds) {
1165254f889dSBrendon Cahoon       MachineInstr *PMI = PI.getSUnit()->getInstr();
1166254f889dSBrendon Cahoon       if (PMI->isPHI() && PI.getKind() == SDep::Order) {
1167254f889dSBrendon Cahoon         if (I.getInstr()->isPHI()) {
1168254f889dSBrendon Cahoon           if (PMI->getOperand(0).getReg() == HasPhiUse)
1169254f889dSBrendon Cahoon             continue;
1170254f889dSBrendon Cahoon           if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
1171254f889dSBrendon Cahoon             continue;
1172254f889dSBrendon Cahoon         }
1173254f889dSBrendon Cahoon         RemoveDeps.push_back(PI);
1174254f889dSBrendon Cahoon       }
1175254f889dSBrendon Cahoon     }
1176254f889dSBrendon Cahoon     for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
1177254f889dSBrendon Cahoon       I.removePred(RemoveDeps[i]);
1178254f889dSBrendon Cahoon   }
1179254f889dSBrendon Cahoon }
1180254f889dSBrendon Cahoon 
1181254f889dSBrendon Cahoon /// Iterate over each DAG node and see if we can change any dependences
1182254f889dSBrendon Cahoon /// in order to reduce the recurrence MII.
1183254f889dSBrendon Cahoon void SwingSchedulerDAG::changeDependences() {
1184254f889dSBrendon Cahoon   // See if an instruction can use a value from the previous iteration.
1185254f889dSBrendon Cahoon   // If so, we update the base and offset of the instruction and change
1186254f889dSBrendon Cahoon   // the dependences.
1187254f889dSBrendon Cahoon   for (SUnit &I : SUnits) {
1188254f889dSBrendon Cahoon     unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
1189254f889dSBrendon Cahoon     int64_t NewOffset = 0;
1190254f889dSBrendon Cahoon     if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
1191254f889dSBrendon Cahoon                                NewOffset))
1192254f889dSBrendon Cahoon       continue;
1193254f889dSBrendon Cahoon 
1194254f889dSBrendon Cahoon     // Get the MI and SUnit for the instruction that defines the original base.
1195254f889dSBrendon Cahoon     unsigned OrigBase = I.getInstr()->getOperand(BasePos).getReg();
1196254f889dSBrendon Cahoon     MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
1197254f889dSBrendon Cahoon     if (!DefMI)
1198254f889dSBrendon Cahoon       continue;
1199254f889dSBrendon Cahoon     SUnit *DefSU = getSUnit(DefMI);
1200254f889dSBrendon Cahoon     if (!DefSU)
1201254f889dSBrendon Cahoon       continue;
1202254f889dSBrendon Cahoon     // Get the MI and SUnit for the instruction that defins the new base.
1203254f889dSBrendon Cahoon     MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
1204254f889dSBrendon Cahoon     if (!LastMI)
1205254f889dSBrendon Cahoon       continue;
1206254f889dSBrendon Cahoon     SUnit *LastSU = getSUnit(LastMI);
1207254f889dSBrendon Cahoon     if (!LastSU)
1208254f889dSBrendon Cahoon       continue;
1209254f889dSBrendon Cahoon 
1210254f889dSBrendon Cahoon     if (Topo.IsReachable(&I, LastSU))
1211254f889dSBrendon Cahoon       continue;
1212254f889dSBrendon Cahoon 
1213254f889dSBrendon Cahoon     // Remove the dependence. The value now depends on a prior iteration.
1214254f889dSBrendon Cahoon     SmallVector<SDep, 4> Deps;
1215254f889dSBrendon Cahoon     for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E;
1216254f889dSBrendon Cahoon          ++P)
1217254f889dSBrendon Cahoon       if (P->getSUnit() == DefSU)
1218254f889dSBrendon Cahoon         Deps.push_back(*P);
1219254f889dSBrendon Cahoon     for (int i = 0, e = Deps.size(); i != e; i++) {
1220254f889dSBrendon Cahoon       Topo.RemovePred(&I, Deps[i].getSUnit());
1221254f889dSBrendon Cahoon       I.removePred(Deps[i]);
1222254f889dSBrendon Cahoon     }
1223254f889dSBrendon Cahoon     // Remove the chain dependence between the instructions.
1224254f889dSBrendon Cahoon     Deps.clear();
1225254f889dSBrendon Cahoon     for (auto &P : LastSU->Preds)
1226254f889dSBrendon Cahoon       if (P.getSUnit() == &I && P.getKind() == SDep::Order)
1227254f889dSBrendon Cahoon         Deps.push_back(P);
1228254f889dSBrendon Cahoon     for (int i = 0, e = Deps.size(); i != e; i++) {
1229254f889dSBrendon Cahoon       Topo.RemovePred(LastSU, Deps[i].getSUnit());
1230254f889dSBrendon Cahoon       LastSU->removePred(Deps[i]);
1231254f889dSBrendon Cahoon     }
1232254f889dSBrendon Cahoon 
1233254f889dSBrendon Cahoon     // Add a dependence between the new instruction and the instruction
1234254f889dSBrendon Cahoon     // that defines the new base.
1235254f889dSBrendon Cahoon     SDep Dep(&I, SDep::Anti, NewBase);
1236254f889dSBrendon Cahoon     LastSU->addPred(Dep);
1237254f889dSBrendon Cahoon 
1238254f889dSBrendon Cahoon     // Remember the base and offset information so that we can update the
1239254f889dSBrendon Cahoon     // instruction during code generation.
1240254f889dSBrendon Cahoon     InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
1241254f889dSBrendon Cahoon   }
1242254f889dSBrendon Cahoon }
1243254f889dSBrendon Cahoon 
1244254f889dSBrendon Cahoon namespace {
1245cdc71612SEugene Zelenko 
1246254f889dSBrendon Cahoon // FuncUnitSorter - Comparison operator used to sort instructions by
1247254f889dSBrendon Cahoon // the number of functional unit choices.
1248254f889dSBrendon Cahoon struct FuncUnitSorter {
1249254f889dSBrendon Cahoon   const InstrItineraryData *InstrItins;
1250254f889dSBrendon Cahoon   DenseMap<unsigned, unsigned> Resources;
1251254f889dSBrendon Cahoon 
1252254f889dSBrendon Cahoon   // Compute the number of functional unit alternatives needed
1253254f889dSBrendon Cahoon   // at each stage, and take the minimum value. We prioritize the
1254254f889dSBrendon Cahoon   // instructions by the least number of choices first.
1255254f889dSBrendon Cahoon   unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const {
1256254f889dSBrendon Cahoon     unsigned schedClass = Inst->getDesc().getSchedClass();
1257254f889dSBrendon Cahoon     unsigned min = UINT_MAX;
1258254f889dSBrendon Cahoon     for (const InstrStage *IS = InstrItins->beginStage(schedClass),
1259254f889dSBrendon Cahoon                           *IE = InstrItins->endStage(schedClass);
1260254f889dSBrendon Cahoon          IS != IE; ++IS) {
1261254f889dSBrendon Cahoon       unsigned funcUnits = IS->getUnits();
1262254f889dSBrendon Cahoon       unsigned numAlternatives = countPopulation(funcUnits);
1263254f889dSBrendon Cahoon       if (numAlternatives < min) {
1264254f889dSBrendon Cahoon         min = numAlternatives;
1265254f889dSBrendon Cahoon         F = funcUnits;
1266254f889dSBrendon Cahoon       }
1267254f889dSBrendon Cahoon     }
1268254f889dSBrendon Cahoon     return min;
1269254f889dSBrendon Cahoon   }
1270254f889dSBrendon Cahoon 
1271254f889dSBrendon Cahoon   // Compute the critical resources needed by the instruction. This
1272254f889dSBrendon Cahoon   // function records the functional units needed by instructions that
1273254f889dSBrendon Cahoon   // must use only one functional unit. We use this as a tie breaker
1274254f889dSBrendon Cahoon   // for computing the resource MII. The instrutions that require
1275254f889dSBrendon Cahoon   // the same, highly used, functional unit have high priority.
1276254f889dSBrendon Cahoon   void calcCriticalResources(MachineInstr &MI) {
1277254f889dSBrendon Cahoon     unsigned SchedClass = MI.getDesc().getSchedClass();
1278254f889dSBrendon Cahoon     for (const InstrStage *IS = InstrItins->beginStage(SchedClass),
1279254f889dSBrendon Cahoon                           *IE = InstrItins->endStage(SchedClass);
1280254f889dSBrendon Cahoon          IS != IE; ++IS) {
1281254f889dSBrendon Cahoon       unsigned FuncUnits = IS->getUnits();
1282254f889dSBrendon Cahoon       if (countPopulation(FuncUnits) == 1)
1283254f889dSBrendon Cahoon         Resources[FuncUnits]++;
1284254f889dSBrendon Cahoon     }
1285254f889dSBrendon Cahoon   }
1286254f889dSBrendon Cahoon 
1287254f889dSBrendon Cahoon   FuncUnitSorter(const InstrItineraryData *IID) : InstrItins(IID) {}
1288254f889dSBrendon Cahoon   /// Return true if IS1 has less priority than IS2.
1289254f889dSBrendon Cahoon   bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
1290254f889dSBrendon Cahoon     unsigned F1 = 0, F2 = 0;
1291254f889dSBrendon Cahoon     unsigned MFUs1 = minFuncUnits(IS1, F1);
1292254f889dSBrendon Cahoon     unsigned MFUs2 = minFuncUnits(IS2, F2);
1293254f889dSBrendon Cahoon     if (MFUs1 == 1 && MFUs2 == 1)
1294254f889dSBrendon Cahoon       return Resources.lookup(F1) < Resources.lookup(F2);
1295254f889dSBrendon Cahoon     return MFUs1 > MFUs2;
1296254f889dSBrendon Cahoon   }
1297254f889dSBrendon Cahoon };
1298cdc71612SEugene Zelenko 
1299cdc71612SEugene Zelenko } // end anonymous namespace
1300254f889dSBrendon Cahoon 
1301254f889dSBrendon Cahoon /// Calculate the resource constrained minimum initiation interval for the
1302254f889dSBrendon Cahoon /// specified loop. We use the DFA to model the resources needed for
1303254f889dSBrendon Cahoon /// each instruction, and we ignore dependences. A different DFA is created
1304254f889dSBrendon Cahoon /// for each cycle that is required. When adding a new instruction, we attempt
1305254f889dSBrendon Cahoon /// to add it to each existing DFA, until a legal space is found. If the
1306254f889dSBrendon Cahoon /// instruction cannot be reserved in an existing DFA, we create a new one.
1307254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::calculateResMII() {
1308254f889dSBrendon Cahoon   SmallVector<DFAPacketizer *, 8> Resources;
1309254f889dSBrendon Cahoon   MachineBasicBlock *MBB = Loop.getHeader();
1310254f889dSBrendon Cahoon   Resources.push_back(TII->CreateTargetScheduleState(MF.getSubtarget()));
1311254f889dSBrendon Cahoon 
1312254f889dSBrendon Cahoon   // Sort the instructions by the number of available choices for scheduling,
1313254f889dSBrendon Cahoon   // least to most. Use the number of critical resources as the tie breaker.
1314254f889dSBrendon Cahoon   FuncUnitSorter FUS =
1315254f889dSBrendon Cahoon       FuncUnitSorter(MF.getSubtarget().getInstrItineraryData());
1316254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
1317254f889dSBrendon Cahoon                                    E = MBB->getFirstTerminator();
1318254f889dSBrendon Cahoon        I != E; ++I)
1319254f889dSBrendon Cahoon     FUS.calcCriticalResources(*I);
1320254f889dSBrendon Cahoon   PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
1321254f889dSBrendon Cahoon       FuncUnitOrder(FUS);
1322254f889dSBrendon Cahoon 
1323254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
1324254f889dSBrendon Cahoon                                    E = MBB->getFirstTerminator();
1325254f889dSBrendon Cahoon        I != E; ++I)
1326254f889dSBrendon Cahoon     FuncUnitOrder.push(&*I);
1327254f889dSBrendon Cahoon 
1328254f889dSBrendon Cahoon   while (!FuncUnitOrder.empty()) {
1329254f889dSBrendon Cahoon     MachineInstr *MI = FuncUnitOrder.top();
1330254f889dSBrendon Cahoon     FuncUnitOrder.pop();
1331254f889dSBrendon Cahoon     if (TII->isZeroCost(MI->getOpcode()))
1332254f889dSBrendon Cahoon       continue;
1333254f889dSBrendon Cahoon     // Attempt to reserve the instruction in an existing DFA. At least one
1334254f889dSBrendon Cahoon     // DFA is needed for each cycle.
1335254f889dSBrendon Cahoon     unsigned NumCycles = getSUnit(MI)->Latency;
1336254f889dSBrendon Cahoon     unsigned ReservedCycles = 0;
1337254f889dSBrendon Cahoon     SmallVectorImpl<DFAPacketizer *>::iterator RI = Resources.begin();
1338254f889dSBrendon Cahoon     SmallVectorImpl<DFAPacketizer *>::iterator RE = Resources.end();
1339254f889dSBrendon Cahoon     for (unsigned C = 0; C < NumCycles; ++C)
1340254f889dSBrendon Cahoon       while (RI != RE) {
1341254f889dSBrendon Cahoon         if ((*RI++)->canReserveResources(*MI)) {
1342254f889dSBrendon Cahoon           ++ReservedCycles;
1343254f889dSBrendon Cahoon           break;
1344254f889dSBrendon Cahoon         }
1345254f889dSBrendon Cahoon       }
1346254f889dSBrendon Cahoon     // Start reserving resources using existing DFAs.
1347254f889dSBrendon Cahoon     for (unsigned C = 0; C < ReservedCycles; ++C) {
1348254f889dSBrendon Cahoon       --RI;
1349254f889dSBrendon Cahoon       (*RI)->reserveResources(*MI);
1350254f889dSBrendon Cahoon     }
1351254f889dSBrendon Cahoon     // Add new DFAs, if needed, to reserve resources.
1352254f889dSBrendon Cahoon     for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
1353254f889dSBrendon Cahoon       DFAPacketizer *NewResource =
1354254f889dSBrendon Cahoon           TII->CreateTargetScheduleState(MF.getSubtarget());
1355254f889dSBrendon Cahoon       assert(NewResource->canReserveResources(*MI) && "Reserve error.");
1356254f889dSBrendon Cahoon       NewResource->reserveResources(*MI);
1357254f889dSBrendon Cahoon       Resources.push_back(NewResource);
1358254f889dSBrendon Cahoon     }
1359254f889dSBrendon Cahoon   }
1360254f889dSBrendon Cahoon   int Resmii = Resources.size();
1361254f889dSBrendon Cahoon   // Delete the memory for each of the DFAs that were created earlier.
1362254f889dSBrendon Cahoon   for (DFAPacketizer *RI : Resources) {
1363254f889dSBrendon Cahoon     DFAPacketizer *D = RI;
1364254f889dSBrendon Cahoon     delete D;
1365254f889dSBrendon Cahoon   }
1366254f889dSBrendon Cahoon   Resources.clear();
1367254f889dSBrendon Cahoon   return Resmii;
1368254f889dSBrendon Cahoon }
1369254f889dSBrendon Cahoon 
1370254f889dSBrendon Cahoon /// Calculate the recurrence-constrainted minimum initiation interval.
1371254f889dSBrendon Cahoon /// Iterate over each circuit.  Compute the delay(c) and distance(c)
1372254f889dSBrendon Cahoon /// for each circuit. The II needs to satisfy the inequality
1373254f889dSBrendon Cahoon /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
1374254f889dSBrendon Cahoon /// II that satistifies the inequality, and the RecMII is the maximum
1375254f889dSBrendon Cahoon /// of those values.
1376254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1377254f889dSBrendon Cahoon   unsigned RecMII = 0;
1378254f889dSBrendon Cahoon 
1379254f889dSBrendon Cahoon   for (NodeSet &Nodes : NodeSets) {
1380254f889dSBrendon Cahoon     if (Nodes.size() == 0)
1381254f889dSBrendon Cahoon       continue;
1382254f889dSBrendon Cahoon 
1383254f889dSBrendon Cahoon     unsigned Delay = Nodes.size() - 1;
1384254f889dSBrendon Cahoon     unsigned Distance = 1;
1385254f889dSBrendon Cahoon 
1386254f889dSBrendon Cahoon     // ii = ceil(delay / distance)
1387254f889dSBrendon Cahoon     unsigned CurMII = (Delay + Distance - 1) / Distance;
1388254f889dSBrendon Cahoon     Nodes.setRecMII(CurMII);
1389254f889dSBrendon Cahoon     if (CurMII > RecMII)
1390254f889dSBrendon Cahoon       RecMII = CurMII;
1391254f889dSBrendon Cahoon   }
1392254f889dSBrendon Cahoon 
1393254f889dSBrendon Cahoon   return RecMII;
1394254f889dSBrendon Cahoon }
1395254f889dSBrendon Cahoon 
1396254f889dSBrendon Cahoon /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1397254f889dSBrendon Cahoon /// but we do this to find the circuits, and then change them back.
1398254f889dSBrendon Cahoon static void swapAntiDependences(std::vector<SUnit> &SUnits) {
1399254f889dSBrendon Cahoon   SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
1400254f889dSBrendon Cahoon   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1401254f889dSBrendon Cahoon     SUnit *SU = &SUnits[i];
1402254f889dSBrendon Cahoon     for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end();
1403254f889dSBrendon Cahoon          IP != EP; ++IP) {
1404254f889dSBrendon Cahoon       if (IP->getKind() != SDep::Anti)
1405254f889dSBrendon Cahoon         continue;
1406254f889dSBrendon Cahoon       DepsAdded.push_back(std::make_pair(SU, *IP));
1407254f889dSBrendon Cahoon     }
1408254f889dSBrendon Cahoon   }
1409254f889dSBrendon Cahoon   for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(),
1410254f889dSBrendon Cahoon                                                           E = DepsAdded.end();
1411254f889dSBrendon Cahoon        I != E; ++I) {
1412254f889dSBrendon Cahoon     // Remove this anti dependency and add one in the reverse direction.
1413254f889dSBrendon Cahoon     SUnit *SU = I->first;
1414254f889dSBrendon Cahoon     SDep &D = I->second;
1415254f889dSBrendon Cahoon     SUnit *TargetSU = D.getSUnit();
1416254f889dSBrendon Cahoon     unsigned Reg = D.getReg();
1417254f889dSBrendon Cahoon     unsigned Lat = D.getLatency();
1418254f889dSBrendon Cahoon     SU->removePred(D);
1419254f889dSBrendon Cahoon     SDep Dep(SU, SDep::Anti, Reg);
1420254f889dSBrendon Cahoon     Dep.setLatency(Lat);
1421254f889dSBrendon Cahoon     TargetSU->addPred(Dep);
1422254f889dSBrendon Cahoon   }
1423254f889dSBrendon Cahoon }
1424254f889dSBrendon Cahoon 
1425254f889dSBrendon Cahoon /// Create the adjacency structure of the nodes in the graph.
1426254f889dSBrendon Cahoon void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1427254f889dSBrendon Cahoon     SwingSchedulerDAG *DAG) {
1428254f889dSBrendon Cahoon   BitVector Added(SUnits.size());
1429254f889dSBrendon Cahoon   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1430254f889dSBrendon Cahoon     Added.reset();
1431254f889dSBrendon Cahoon     // Add any successor to the adjacency matrix and exclude duplicates.
1432254f889dSBrendon Cahoon     for (auto &SI : SUnits[i].Succs) {
1433254f889dSBrendon Cahoon       // Do not process a boundary node and a back-edge is processed only
1434254f889dSBrendon Cahoon       // if it goes to a Phi.
1435254f889dSBrendon Cahoon       if (SI.getSUnit()->isBoundaryNode() ||
1436254f889dSBrendon Cahoon           (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
1437254f889dSBrendon Cahoon         continue;
1438254f889dSBrendon Cahoon       int N = SI.getSUnit()->NodeNum;
1439254f889dSBrendon Cahoon       if (!Added.test(N)) {
1440254f889dSBrendon Cahoon         AdjK[i].push_back(N);
1441254f889dSBrendon Cahoon         Added.set(N);
1442254f889dSBrendon Cahoon       }
1443254f889dSBrendon Cahoon     }
1444254f889dSBrendon Cahoon     // A chain edge between a store and a load is treated as a back-edge in the
1445254f889dSBrendon Cahoon     // adjacency matrix.
1446254f889dSBrendon Cahoon     for (auto &PI : SUnits[i].Preds) {
1447254f889dSBrendon Cahoon       if (!SUnits[i].getInstr()->mayStore() ||
1448254f889dSBrendon Cahoon           !DAG->isLoopCarriedOrder(&SUnits[i], PI, false))
1449254f889dSBrendon Cahoon         continue;
1450254f889dSBrendon Cahoon       if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1451254f889dSBrendon Cahoon         int N = PI.getSUnit()->NodeNum;
1452254f889dSBrendon Cahoon         if (!Added.test(N)) {
1453254f889dSBrendon Cahoon           AdjK[i].push_back(N);
1454254f889dSBrendon Cahoon           Added.set(N);
1455254f889dSBrendon Cahoon         }
1456254f889dSBrendon Cahoon       }
1457254f889dSBrendon Cahoon     }
1458254f889dSBrendon Cahoon   }
1459254f889dSBrendon Cahoon }
1460254f889dSBrendon Cahoon 
1461254f889dSBrendon Cahoon /// Identify an elementary circuit in the dependence graph starting at the
1462254f889dSBrendon Cahoon /// specified node.
1463254f889dSBrendon Cahoon bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
1464254f889dSBrendon Cahoon                                           bool HasBackedge) {
1465254f889dSBrendon Cahoon   SUnit *SV = &SUnits[V];
1466254f889dSBrendon Cahoon   bool F = false;
1467254f889dSBrendon Cahoon   Stack.insert(SV);
1468254f889dSBrendon Cahoon   Blocked.set(V);
1469254f889dSBrendon Cahoon 
1470254f889dSBrendon Cahoon   for (auto W : AdjK[V]) {
1471254f889dSBrendon Cahoon     if (NumPaths > MaxPaths)
1472254f889dSBrendon Cahoon       break;
1473254f889dSBrendon Cahoon     if (W < S)
1474254f889dSBrendon Cahoon       continue;
1475254f889dSBrendon Cahoon     if (W == S) {
1476254f889dSBrendon Cahoon       if (!HasBackedge)
1477254f889dSBrendon Cahoon         NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
1478254f889dSBrendon Cahoon       F = true;
1479254f889dSBrendon Cahoon       ++NumPaths;
1480254f889dSBrendon Cahoon       break;
1481254f889dSBrendon Cahoon     } else if (!Blocked.test(W)) {
1482254f889dSBrendon Cahoon       if (circuit(W, S, NodeSets, W < V ? true : HasBackedge))
1483254f889dSBrendon Cahoon         F = true;
1484254f889dSBrendon Cahoon     }
1485254f889dSBrendon Cahoon   }
1486254f889dSBrendon Cahoon 
1487254f889dSBrendon Cahoon   if (F)
1488254f889dSBrendon Cahoon     unblock(V);
1489254f889dSBrendon Cahoon   else {
1490254f889dSBrendon Cahoon     for (auto W : AdjK[V]) {
1491254f889dSBrendon Cahoon       if (W < S)
1492254f889dSBrendon Cahoon         continue;
1493254f889dSBrendon Cahoon       if (B[W].count(SV) == 0)
1494254f889dSBrendon Cahoon         B[W].insert(SV);
1495254f889dSBrendon Cahoon     }
1496254f889dSBrendon Cahoon   }
1497254f889dSBrendon Cahoon   Stack.pop_back();
1498254f889dSBrendon Cahoon   return F;
1499254f889dSBrendon Cahoon }
1500254f889dSBrendon Cahoon 
1501254f889dSBrendon Cahoon /// Unblock a node in the circuit finding algorithm.
1502254f889dSBrendon Cahoon void SwingSchedulerDAG::Circuits::unblock(int U) {
1503254f889dSBrendon Cahoon   Blocked.reset(U);
1504254f889dSBrendon Cahoon   SmallPtrSet<SUnit *, 4> &BU = B[U];
1505254f889dSBrendon Cahoon   while (!BU.empty()) {
1506254f889dSBrendon Cahoon     SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
1507254f889dSBrendon Cahoon     assert(SI != BU.end() && "Invalid B set.");
1508254f889dSBrendon Cahoon     SUnit *W = *SI;
1509254f889dSBrendon Cahoon     BU.erase(W);
1510254f889dSBrendon Cahoon     if (Blocked.test(W->NodeNum))
1511254f889dSBrendon Cahoon       unblock(W->NodeNum);
1512254f889dSBrendon Cahoon   }
1513254f889dSBrendon Cahoon }
1514254f889dSBrendon Cahoon 
1515254f889dSBrendon Cahoon /// Identify all the elementary circuits in the dependence graph using
1516254f889dSBrendon Cahoon /// Johnson's circuit algorithm.
1517254f889dSBrendon Cahoon void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1518254f889dSBrendon Cahoon   // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1519254f889dSBrendon Cahoon   // but we do this to find the circuits, and then change them back.
1520254f889dSBrendon Cahoon   swapAntiDependences(SUnits);
1521254f889dSBrendon Cahoon 
1522254f889dSBrendon Cahoon   Circuits Cir(SUnits);
1523254f889dSBrendon Cahoon   // Create the adjacency structure.
1524254f889dSBrendon Cahoon   Cir.createAdjacencyStructure(this);
1525254f889dSBrendon Cahoon   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1526254f889dSBrendon Cahoon     Cir.reset();
1527254f889dSBrendon Cahoon     Cir.circuit(i, i, NodeSets);
1528254f889dSBrendon Cahoon   }
1529254f889dSBrendon Cahoon 
1530254f889dSBrendon Cahoon   // Change the dependences back so that we've created a DAG again.
1531254f889dSBrendon Cahoon   swapAntiDependences(SUnits);
1532254f889dSBrendon Cahoon }
1533254f889dSBrendon Cahoon 
1534254f889dSBrendon Cahoon /// Return true for DAG nodes that we ignore when computing the cost functions.
1535254f889dSBrendon Cahoon /// We ignore the back-edge recurrence in order to avoid unbounded recurison
1536254f889dSBrendon Cahoon /// in the calculation of the ASAP, ALAP, etc functions.
1537254f889dSBrendon Cahoon static bool ignoreDependence(const SDep &D, bool isPred) {
1538254f889dSBrendon Cahoon   if (D.isArtificial())
1539254f889dSBrendon Cahoon     return true;
1540254f889dSBrendon Cahoon   return D.getKind() == SDep::Anti && isPred;
1541254f889dSBrendon Cahoon }
1542254f889dSBrendon Cahoon 
1543254f889dSBrendon Cahoon /// Compute several functions need to order the nodes for scheduling.
1544254f889dSBrendon Cahoon ///  ASAP - Earliest time to schedule a node.
1545254f889dSBrendon Cahoon ///  ALAP - Latest time to schedule a node.
1546254f889dSBrendon Cahoon ///  MOV - Mobility function, difference between ALAP and ASAP.
1547254f889dSBrendon Cahoon ///  D - Depth of each node.
1548254f889dSBrendon Cahoon ///  H - Height of each node.
1549254f889dSBrendon Cahoon void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
1550254f889dSBrendon Cahoon 
1551254f889dSBrendon Cahoon   ScheduleInfo.resize(SUnits.size());
1552254f889dSBrendon Cahoon 
1553254f889dSBrendon Cahoon   DEBUG({
1554254f889dSBrendon Cahoon     for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1555254f889dSBrendon Cahoon                                                     E = Topo.end();
1556254f889dSBrendon Cahoon          I != E; ++I) {
1557254f889dSBrendon Cahoon       SUnit *SU = &SUnits[*I];
1558254f889dSBrendon Cahoon       SU->dump(this);
1559254f889dSBrendon Cahoon     }
1560254f889dSBrendon Cahoon   });
1561254f889dSBrendon Cahoon 
1562254f889dSBrendon Cahoon   int maxASAP = 0;
1563254f889dSBrendon Cahoon   // Compute ASAP.
1564254f889dSBrendon Cahoon   for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1565254f889dSBrendon Cahoon                                                   E = Topo.end();
1566254f889dSBrendon Cahoon        I != E; ++I) {
1567254f889dSBrendon Cahoon     int asap = 0;
1568254f889dSBrendon Cahoon     SUnit *SU = &SUnits[*I];
1569254f889dSBrendon Cahoon     for (SUnit::const_pred_iterator IP = SU->Preds.begin(),
1570254f889dSBrendon Cahoon                                     EP = SU->Preds.end();
1571254f889dSBrendon Cahoon          IP != EP; ++IP) {
1572254f889dSBrendon Cahoon       if (ignoreDependence(*IP, true))
1573254f889dSBrendon Cahoon         continue;
1574254f889dSBrendon Cahoon       SUnit *pred = IP->getSUnit();
1575254f889dSBrendon Cahoon       asap = std::max(asap, (int)(getASAP(pred) + getLatency(SU, *IP) -
1576254f889dSBrendon Cahoon                                   getDistance(pred, SU, *IP) * MII));
1577254f889dSBrendon Cahoon     }
1578254f889dSBrendon Cahoon     maxASAP = std::max(maxASAP, asap);
1579254f889dSBrendon Cahoon     ScheduleInfo[*I].ASAP = asap;
1580254f889dSBrendon Cahoon   }
1581254f889dSBrendon Cahoon 
1582254f889dSBrendon Cahoon   // Compute ALAP and MOV.
1583254f889dSBrendon Cahoon   for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(),
1584254f889dSBrendon Cahoon                                                           E = Topo.rend();
1585254f889dSBrendon Cahoon        I != E; ++I) {
1586254f889dSBrendon Cahoon     int alap = maxASAP;
1587254f889dSBrendon Cahoon     SUnit *SU = &SUnits[*I];
1588254f889dSBrendon Cahoon     for (SUnit::const_succ_iterator IS = SU->Succs.begin(),
1589254f889dSBrendon Cahoon                                     ES = SU->Succs.end();
1590254f889dSBrendon Cahoon          IS != ES; ++IS) {
1591254f889dSBrendon Cahoon       if (ignoreDependence(*IS, true))
1592254f889dSBrendon Cahoon         continue;
1593254f889dSBrendon Cahoon       SUnit *succ = IS->getSUnit();
1594254f889dSBrendon Cahoon       alap = std::min(alap, (int)(getALAP(succ) - getLatency(SU, *IS) +
1595254f889dSBrendon Cahoon                                   getDistance(SU, succ, *IS) * MII));
1596254f889dSBrendon Cahoon     }
1597254f889dSBrendon Cahoon 
1598254f889dSBrendon Cahoon     ScheduleInfo[*I].ALAP = alap;
1599254f889dSBrendon Cahoon   }
1600254f889dSBrendon Cahoon 
1601254f889dSBrendon Cahoon   // After computing the node functions, compute the summary for each node set.
1602254f889dSBrendon Cahoon   for (NodeSet &I : NodeSets)
1603254f889dSBrendon Cahoon     I.computeNodeSetInfo(this);
1604254f889dSBrendon Cahoon 
1605254f889dSBrendon Cahoon   DEBUG({
1606254f889dSBrendon Cahoon     for (unsigned i = 0; i < SUnits.size(); i++) {
1607254f889dSBrendon Cahoon       dbgs() << "\tNode " << i << ":\n";
1608254f889dSBrendon Cahoon       dbgs() << "\t   ASAP = " << getASAP(&SUnits[i]) << "\n";
1609254f889dSBrendon Cahoon       dbgs() << "\t   ALAP = " << getALAP(&SUnits[i]) << "\n";
1610254f889dSBrendon Cahoon       dbgs() << "\t   MOV  = " << getMOV(&SUnits[i]) << "\n";
1611254f889dSBrendon Cahoon       dbgs() << "\t   D    = " << getDepth(&SUnits[i]) << "\n";
1612254f889dSBrendon Cahoon       dbgs() << "\t   H    = " << getHeight(&SUnits[i]) << "\n";
1613254f889dSBrendon Cahoon     }
1614254f889dSBrendon Cahoon   });
1615254f889dSBrendon Cahoon }
1616254f889dSBrendon Cahoon 
1617254f889dSBrendon Cahoon /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1618254f889dSBrendon Cahoon /// as the predecessors of the elements of NodeOrder that are not also in
1619254f889dSBrendon Cahoon /// NodeOrder.
1620254f889dSBrendon Cahoon static bool pred_L(SetVector<SUnit *> &NodeOrder,
1621254f889dSBrendon Cahoon                    SmallSetVector<SUnit *, 8> &Preds,
1622254f889dSBrendon Cahoon                    const NodeSet *S = nullptr) {
1623254f889dSBrendon Cahoon   Preds.clear();
1624254f889dSBrendon Cahoon   for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1625254f889dSBrendon Cahoon        I != E; ++I) {
1626254f889dSBrendon Cahoon     for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end();
1627254f889dSBrendon Cahoon          PI != PE; ++PI) {
1628254f889dSBrendon Cahoon       if (S && S->count(PI->getSUnit()) == 0)
1629254f889dSBrendon Cahoon         continue;
1630254f889dSBrendon Cahoon       if (ignoreDependence(*PI, true))
1631254f889dSBrendon Cahoon         continue;
1632254f889dSBrendon Cahoon       if (NodeOrder.count(PI->getSUnit()) == 0)
1633254f889dSBrendon Cahoon         Preds.insert(PI->getSUnit());
1634254f889dSBrendon Cahoon     }
1635254f889dSBrendon Cahoon     // Back-edges are predecessors with an anti-dependence.
1636254f889dSBrendon Cahoon     for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(),
1637254f889dSBrendon Cahoon                                     ES = (*I)->Succs.end();
1638254f889dSBrendon Cahoon          IS != ES; ++IS) {
1639254f889dSBrendon Cahoon       if (IS->getKind() != SDep::Anti)
1640254f889dSBrendon Cahoon         continue;
1641254f889dSBrendon Cahoon       if (S && S->count(IS->getSUnit()) == 0)
1642254f889dSBrendon Cahoon         continue;
1643254f889dSBrendon Cahoon       if (NodeOrder.count(IS->getSUnit()) == 0)
1644254f889dSBrendon Cahoon         Preds.insert(IS->getSUnit());
1645254f889dSBrendon Cahoon     }
1646254f889dSBrendon Cahoon   }
1647254f889dSBrendon Cahoon   return Preds.size() > 0;
1648254f889dSBrendon Cahoon }
1649254f889dSBrendon Cahoon 
1650254f889dSBrendon Cahoon /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1651254f889dSBrendon Cahoon /// as the successors of the elements of NodeOrder that are not also in
1652254f889dSBrendon Cahoon /// NodeOrder.
1653254f889dSBrendon Cahoon static bool succ_L(SetVector<SUnit *> &NodeOrder,
1654254f889dSBrendon Cahoon                    SmallSetVector<SUnit *, 8> &Succs,
1655254f889dSBrendon Cahoon                    const NodeSet *S = nullptr) {
1656254f889dSBrendon Cahoon   Succs.clear();
1657254f889dSBrendon Cahoon   for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1658254f889dSBrendon Cahoon        I != E; ++I) {
1659254f889dSBrendon Cahoon     for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end();
1660254f889dSBrendon Cahoon          SI != SE; ++SI) {
1661254f889dSBrendon Cahoon       if (S && S->count(SI->getSUnit()) == 0)
1662254f889dSBrendon Cahoon         continue;
1663254f889dSBrendon Cahoon       if (ignoreDependence(*SI, false))
1664254f889dSBrendon Cahoon         continue;
1665254f889dSBrendon Cahoon       if (NodeOrder.count(SI->getSUnit()) == 0)
1666254f889dSBrendon Cahoon         Succs.insert(SI->getSUnit());
1667254f889dSBrendon Cahoon     }
1668254f889dSBrendon Cahoon     for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(),
1669254f889dSBrendon Cahoon                                     PE = (*I)->Preds.end();
1670254f889dSBrendon Cahoon          PI != PE; ++PI) {
1671254f889dSBrendon Cahoon       if (PI->getKind() != SDep::Anti)
1672254f889dSBrendon Cahoon         continue;
1673254f889dSBrendon Cahoon       if (S && S->count(PI->getSUnit()) == 0)
1674254f889dSBrendon Cahoon         continue;
1675254f889dSBrendon Cahoon       if (NodeOrder.count(PI->getSUnit()) == 0)
1676254f889dSBrendon Cahoon         Succs.insert(PI->getSUnit());
1677254f889dSBrendon Cahoon     }
1678254f889dSBrendon Cahoon   }
1679254f889dSBrendon Cahoon   return Succs.size() > 0;
1680254f889dSBrendon Cahoon }
1681254f889dSBrendon Cahoon 
1682254f889dSBrendon Cahoon /// Return true if there is a path from the specified node to any of the nodes
1683254f889dSBrendon Cahoon /// in DestNodes. Keep track and return the nodes in any path.
1684254f889dSBrendon Cahoon static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
1685254f889dSBrendon Cahoon                         SetVector<SUnit *> &DestNodes,
1686254f889dSBrendon Cahoon                         SetVector<SUnit *> &Exclude,
1687254f889dSBrendon Cahoon                         SmallPtrSet<SUnit *, 8> &Visited) {
1688254f889dSBrendon Cahoon   if (Cur->isBoundaryNode())
1689254f889dSBrendon Cahoon     return false;
1690254f889dSBrendon Cahoon   if (Exclude.count(Cur) != 0)
1691254f889dSBrendon Cahoon     return false;
1692254f889dSBrendon Cahoon   if (DestNodes.count(Cur) != 0)
1693254f889dSBrendon Cahoon     return true;
1694254f889dSBrendon Cahoon   if (!Visited.insert(Cur).second)
1695254f889dSBrendon Cahoon     return Path.count(Cur) != 0;
1696254f889dSBrendon Cahoon   bool FoundPath = false;
1697254f889dSBrendon Cahoon   for (auto &SI : Cur->Succs)
1698254f889dSBrendon Cahoon     FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
1699254f889dSBrendon Cahoon   for (auto &PI : Cur->Preds)
1700254f889dSBrendon Cahoon     if (PI.getKind() == SDep::Anti)
1701254f889dSBrendon Cahoon       FoundPath |=
1702254f889dSBrendon Cahoon           computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
1703254f889dSBrendon Cahoon   if (FoundPath)
1704254f889dSBrendon Cahoon     Path.insert(Cur);
1705254f889dSBrendon Cahoon   return FoundPath;
1706254f889dSBrendon Cahoon }
1707254f889dSBrendon Cahoon 
1708254f889dSBrendon Cahoon /// Return true if Set1 is a subset of Set2.
1709254f889dSBrendon Cahoon template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
1710254f889dSBrendon Cahoon   for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I)
1711254f889dSBrendon Cahoon     if (Set2.count(*I) == 0)
1712254f889dSBrendon Cahoon       return false;
1713254f889dSBrendon Cahoon   return true;
1714254f889dSBrendon Cahoon }
1715254f889dSBrendon Cahoon 
1716254f889dSBrendon Cahoon /// Compute the live-out registers for the instructions in a node-set.
1717254f889dSBrendon Cahoon /// The live-out registers are those that are defined in the node-set,
1718254f889dSBrendon Cahoon /// but not used. Except for use operands of Phis.
1719254f889dSBrendon Cahoon static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
1720254f889dSBrendon Cahoon                             NodeSet &NS) {
1721254f889dSBrendon Cahoon   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1722254f889dSBrendon Cahoon   MachineRegisterInfo &MRI = MF.getRegInfo();
1723254f889dSBrendon Cahoon   SmallVector<RegisterMaskPair, 8> LiveOutRegs;
1724254f889dSBrendon Cahoon   SmallSet<unsigned, 4> Uses;
1725254f889dSBrendon Cahoon   for (SUnit *SU : NS) {
1726254f889dSBrendon Cahoon     const MachineInstr *MI = SU->getInstr();
1727254f889dSBrendon Cahoon     if (MI->isPHI())
1728254f889dSBrendon Cahoon       continue;
1729fc371558SMatthias Braun     for (const MachineOperand &MO : MI->operands())
1730fc371558SMatthias Braun       if (MO.isReg() && MO.isUse()) {
1731fc371558SMatthias Braun         unsigned Reg = MO.getReg();
1732254f889dSBrendon Cahoon         if (TargetRegisterInfo::isVirtualRegister(Reg))
1733254f889dSBrendon Cahoon           Uses.insert(Reg);
1734254f889dSBrendon Cahoon         else if (MRI.isAllocatable(Reg))
1735254f889dSBrendon Cahoon           for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1736254f889dSBrendon Cahoon             Uses.insert(*Units);
1737254f889dSBrendon Cahoon       }
1738254f889dSBrendon Cahoon   }
1739254f889dSBrendon Cahoon   for (SUnit *SU : NS)
1740fc371558SMatthias Braun     for (const MachineOperand &MO : SU->getInstr()->operands())
1741fc371558SMatthias Braun       if (MO.isReg() && MO.isDef() && !MO.isDead()) {
1742fc371558SMatthias Braun         unsigned Reg = MO.getReg();
1743254f889dSBrendon Cahoon         if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1744254f889dSBrendon Cahoon           if (!Uses.count(Reg))
174591b5cf84SKrzysztof Parzyszek             LiveOutRegs.push_back(RegisterMaskPair(Reg,
174691b5cf84SKrzysztof Parzyszek                                                    LaneBitmask::getNone()));
1747254f889dSBrendon Cahoon         } else if (MRI.isAllocatable(Reg)) {
1748254f889dSBrendon Cahoon           for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1749254f889dSBrendon Cahoon             if (!Uses.count(*Units))
175091b5cf84SKrzysztof Parzyszek               LiveOutRegs.push_back(RegisterMaskPair(*Units,
175191b5cf84SKrzysztof Parzyszek                                                      LaneBitmask::getNone()));
1752254f889dSBrendon Cahoon         }
1753254f889dSBrendon Cahoon       }
1754254f889dSBrendon Cahoon   RPTracker.addLiveRegs(LiveOutRegs);
1755254f889dSBrendon Cahoon }
1756254f889dSBrendon Cahoon 
1757254f889dSBrendon Cahoon /// A heuristic to filter nodes in recurrent node-sets if the register
1758254f889dSBrendon Cahoon /// pressure of a set is too high.
1759254f889dSBrendon Cahoon void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
1760254f889dSBrendon Cahoon   for (auto &NS : NodeSets) {
1761254f889dSBrendon Cahoon     // Skip small node-sets since they won't cause register pressure problems.
1762254f889dSBrendon Cahoon     if (NS.size() <= 2)
1763254f889dSBrendon Cahoon       continue;
1764254f889dSBrendon Cahoon     IntervalPressure RecRegPressure;
1765254f889dSBrendon Cahoon     RegPressureTracker RecRPTracker(RecRegPressure);
1766254f889dSBrendon Cahoon     RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
1767254f889dSBrendon Cahoon     computeLiveOuts(MF, RecRPTracker, NS);
1768254f889dSBrendon Cahoon     RecRPTracker.closeBottom();
1769254f889dSBrendon Cahoon 
1770254f889dSBrendon Cahoon     std::vector<SUnit *> SUnits(NS.begin(), NS.end());
1771254f889dSBrendon Cahoon     std::sort(SUnits.begin(), SUnits.end(), [](const SUnit *A, const SUnit *B) {
1772254f889dSBrendon Cahoon       return A->NodeNum > B->NodeNum;
1773254f889dSBrendon Cahoon     });
1774254f889dSBrendon Cahoon 
1775254f889dSBrendon Cahoon     for (auto &SU : SUnits) {
1776254f889dSBrendon Cahoon       // Since we're computing the register pressure for a subset of the
1777254f889dSBrendon Cahoon       // instructions in a block, we need to set the tracker for each
1778254f889dSBrendon Cahoon       // instruction in the node-set. The tracker is set to the instruction
1779254f889dSBrendon Cahoon       // just after the one we're interested in.
1780254f889dSBrendon Cahoon       MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
1781254f889dSBrendon Cahoon       RecRPTracker.setPos(std::next(CurInstI));
1782254f889dSBrendon Cahoon 
1783254f889dSBrendon Cahoon       RegPressureDelta RPDelta;
1784254f889dSBrendon Cahoon       ArrayRef<PressureChange> CriticalPSets;
1785254f889dSBrendon Cahoon       RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
1786254f889dSBrendon Cahoon                                              CriticalPSets,
1787254f889dSBrendon Cahoon                                              RecRegPressure.MaxSetPressure);
1788254f889dSBrendon Cahoon       if (RPDelta.Excess.isValid()) {
1789254f889dSBrendon Cahoon         DEBUG(dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
1790254f889dSBrendon Cahoon                      << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
1791254f889dSBrendon Cahoon                      << ":" << RPDelta.Excess.getUnitInc());
1792254f889dSBrendon Cahoon         NS.setExceedPressure(SU);
1793254f889dSBrendon Cahoon         break;
1794254f889dSBrendon Cahoon       }
1795254f889dSBrendon Cahoon       RecRPTracker.recede();
1796254f889dSBrendon Cahoon     }
1797254f889dSBrendon Cahoon   }
1798254f889dSBrendon Cahoon }
1799254f889dSBrendon Cahoon 
1800254f889dSBrendon Cahoon /// A heuristic to colocate node sets that have the same set of
1801254f889dSBrendon Cahoon /// successors.
1802254f889dSBrendon Cahoon void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
1803254f889dSBrendon Cahoon   unsigned Colocate = 0;
1804254f889dSBrendon Cahoon   for (int i = 0, e = NodeSets.size(); i < e; ++i) {
1805254f889dSBrendon Cahoon     NodeSet &N1 = NodeSets[i];
1806254f889dSBrendon Cahoon     SmallSetVector<SUnit *, 8> S1;
1807254f889dSBrendon Cahoon     if (N1.empty() || !succ_L(N1, S1))
1808254f889dSBrendon Cahoon       continue;
1809254f889dSBrendon Cahoon     for (int j = i + 1; j < e; ++j) {
1810254f889dSBrendon Cahoon       NodeSet &N2 = NodeSets[j];
1811254f889dSBrendon Cahoon       if (N1.compareRecMII(N2) != 0)
1812254f889dSBrendon Cahoon         continue;
1813254f889dSBrendon Cahoon       SmallSetVector<SUnit *, 8> S2;
1814254f889dSBrendon Cahoon       if (N2.empty() || !succ_L(N2, S2))
1815254f889dSBrendon Cahoon         continue;
1816254f889dSBrendon Cahoon       if (isSubset(S1, S2) && S1.size() == S2.size()) {
1817254f889dSBrendon Cahoon         N1.setColocate(++Colocate);
1818254f889dSBrendon Cahoon         N2.setColocate(Colocate);
1819254f889dSBrendon Cahoon         break;
1820254f889dSBrendon Cahoon       }
1821254f889dSBrendon Cahoon     }
1822254f889dSBrendon Cahoon   }
1823254f889dSBrendon Cahoon }
1824254f889dSBrendon Cahoon 
1825254f889dSBrendon Cahoon /// Check if the existing node-sets are profitable. If not, then ignore the
1826254f889dSBrendon Cahoon /// recurrent node-sets, and attempt to schedule all nodes together. This is
1827254f889dSBrendon Cahoon /// a heuristic. If the MII is large and there is a non-recurrent node with
1828254f889dSBrendon Cahoon /// a large depth compared to the MII, then it's best to try and schedule
1829254f889dSBrendon Cahoon /// all instruction together instead of starting with the recurrent node-sets.
1830254f889dSBrendon Cahoon void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
1831254f889dSBrendon Cahoon   // Look for loops with a large MII.
1832254f889dSBrendon Cahoon   if (MII <= 20)
1833254f889dSBrendon Cahoon     return;
1834254f889dSBrendon Cahoon   // Check if the node-set contains only a simple add recurrence.
1835254f889dSBrendon Cahoon   for (auto &NS : NodeSets)
1836254f889dSBrendon Cahoon     if (NS.size() > 2)
1837254f889dSBrendon Cahoon       return;
1838254f889dSBrendon Cahoon   // If the depth of any instruction is significantly larger than the MII, then
1839254f889dSBrendon Cahoon   // ignore the recurrent node-sets and treat all instructions equally.
1840254f889dSBrendon Cahoon   for (auto &SU : SUnits)
1841254f889dSBrendon Cahoon     if (SU.getDepth() > MII * 1.5) {
1842254f889dSBrendon Cahoon       NodeSets.clear();
1843254f889dSBrendon Cahoon       DEBUG(dbgs() << "Clear recurrence node-sets\n");
1844254f889dSBrendon Cahoon       return;
1845254f889dSBrendon Cahoon     }
1846254f889dSBrendon Cahoon }
1847254f889dSBrendon Cahoon 
1848254f889dSBrendon Cahoon /// Add the nodes that do not belong to a recurrence set into groups
1849254f889dSBrendon Cahoon /// based upon connected componenets.
1850254f889dSBrendon Cahoon void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
1851254f889dSBrendon Cahoon   SetVector<SUnit *> NodesAdded;
1852254f889dSBrendon Cahoon   SmallPtrSet<SUnit *, 8> Visited;
1853254f889dSBrendon Cahoon   // Add the nodes that are on a path between the previous node sets and
1854254f889dSBrendon Cahoon   // the current node set.
1855254f889dSBrendon Cahoon   for (NodeSet &I : NodeSets) {
1856254f889dSBrendon Cahoon     SmallSetVector<SUnit *, 8> N;
1857254f889dSBrendon Cahoon     // Add the nodes from the current node set to the previous node set.
1858254f889dSBrendon Cahoon     if (succ_L(I, N)) {
1859254f889dSBrendon Cahoon       SetVector<SUnit *> Path;
1860254f889dSBrendon Cahoon       for (SUnit *NI : N) {
1861254f889dSBrendon Cahoon         Visited.clear();
1862254f889dSBrendon Cahoon         computePath(NI, Path, NodesAdded, I, Visited);
1863254f889dSBrendon Cahoon       }
1864254f889dSBrendon Cahoon       if (Path.size() > 0)
1865254f889dSBrendon Cahoon         I.insert(Path.begin(), Path.end());
1866254f889dSBrendon Cahoon     }
1867254f889dSBrendon Cahoon     // Add the nodes from the previous node set to the current node set.
1868254f889dSBrendon Cahoon     N.clear();
1869254f889dSBrendon Cahoon     if (succ_L(NodesAdded, N)) {
1870254f889dSBrendon Cahoon       SetVector<SUnit *> Path;
1871254f889dSBrendon Cahoon       for (SUnit *NI : N) {
1872254f889dSBrendon Cahoon         Visited.clear();
1873254f889dSBrendon Cahoon         computePath(NI, Path, I, NodesAdded, Visited);
1874254f889dSBrendon Cahoon       }
1875254f889dSBrendon Cahoon       if (Path.size() > 0)
1876254f889dSBrendon Cahoon         I.insert(Path.begin(), Path.end());
1877254f889dSBrendon Cahoon     }
1878254f889dSBrendon Cahoon     NodesAdded.insert(I.begin(), I.end());
1879254f889dSBrendon Cahoon   }
1880254f889dSBrendon Cahoon 
1881254f889dSBrendon Cahoon   // Create a new node set with the connected nodes of any successor of a node
1882254f889dSBrendon Cahoon   // in a recurrent set.
1883254f889dSBrendon Cahoon   NodeSet NewSet;
1884254f889dSBrendon Cahoon   SmallSetVector<SUnit *, 8> N;
1885254f889dSBrendon Cahoon   if (succ_L(NodesAdded, N))
1886254f889dSBrendon Cahoon     for (SUnit *I : N)
1887254f889dSBrendon Cahoon       addConnectedNodes(I, NewSet, NodesAdded);
1888254f889dSBrendon Cahoon   if (NewSet.size() > 0)
1889254f889dSBrendon Cahoon     NodeSets.push_back(NewSet);
1890254f889dSBrendon Cahoon 
1891254f889dSBrendon Cahoon   // Create a new node set with the connected nodes of any predecessor of a node
1892254f889dSBrendon Cahoon   // in a recurrent set.
1893254f889dSBrendon Cahoon   NewSet.clear();
1894254f889dSBrendon Cahoon   if (pred_L(NodesAdded, N))
1895254f889dSBrendon Cahoon     for (SUnit *I : N)
1896254f889dSBrendon Cahoon       addConnectedNodes(I, NewSet, NodesAdded);
1897254f889dSBrendon Cahoon   if (NewSet.size() > 0)
1898254f889dSBrendon Cahoon     NodeSets.push_back(NewSet);
1899254f889dSBrendon Cahoon 
1900254f889dSBrendon Cahoon   // Create new nodes sets with the connected nodes any any remaining node that
1901254f889dSBrendon Cahoon   // has no predecessor.
1902254f889dSBrendon Cahoon   for (unsigned i = 0; i < SUnits.size(); ++i) {
1903254f889dSBrendon Cahoon     SUnit *SU = &SUnits[i];
1904254f889dSBrendon Cahoon     if (NodesAdded.count(SU) == 0) {
1905254f889dSBrendon Cahoon       NewSet.clear();
1906254f889dSBrendon Cahoon       addConnectedNodes(SU, NewSet, NodesAdded);
1907254f889dSBrendon Cahoon       if (NewSet.size() > 0)
1908254f889dSBrendon Cahoon         NodeSets.push_back(NewSet);
1909254f889dSBrendon Cahoon     }
1910254f889dSBrendon Cahoon   }
1911254f889dSBrendon Cahoon }
1912254f889dSBrendon Cahoon 
1913254f889dSBrendon Cahoon /// Add the node to the set, and add all is its connected nodes to the set.
1914254f889dSBrendon Cahoon void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
1915254f889dSBrendon Cahoon                                           SetVector<SUnit *> &NodesAdded) {
1916254f889dSBrendon Cahoon   NewSet.insert(SU);
1917254f889dSBrendon Cahoon   NodesAdded.insert(SU);
1918254f889dSBrendon Cahoon   for (auto &SI : SU->Succs) {
1919254f889dSBrendon Cahoon     SUnit *Successor = SI.getSUnit();
1920254f889dSBrendon Cahoon     if (!SI.isArtificial() && NodesAdded.count(Successor) == 0)
1921254f889dSBrendon Cahoon       addConnectedNodes(Successor, NewSet, NodesAdded);
1922254f889dSBrendon Cahoon   }
1923254f889dSBrendon Cahoon   for (auto &PI : SU->Preds) {
1924254f889dSBrendon Cahoon     SUnit *Predecessor = PI.getSUnit();
1925254f889dSBrendon Cahoon     if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
1926254f889dSBrendon Cahoon       addConnectedNodes(Predecessor, NewSet, NodesAdded);
1927254f889dSBrendon Cahoon   }
1928254f889dSBrendon Cahoon }
1929254f889dSBrendon Cahoon 
1930254f889dSBrendon Cahoon /// Return true if Set1 contains elements in Set2. The elements in common
1931254f889dSBrendon Cahoon /// are returned in a different container.
1932254f889dSBrendon Cahoon static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
1933254f889dSBrendon Cahoon                         SmallSetVector<SUnit *, 8> &Result) {
1934254f889dSBrendon Cahoon   Result.clear();
1935254f889dSBrendon Cahoon   for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
1936254f889dSBrendon Cahoon     SUnit *SU = Set1[i];
1937254f889dSBrendon Cahoon     if (Set2.count(SU) != 0)
1938254f889dSBrendon Cahoon       Result.insert(SU);
1939254f889dSBrendon Cahoon   }
1940254f889dSBrendon Cahoon   return !Result.empty();
1941254f889dSBrendon Cahoon }
1942254f889dSBrendon Cahoon 
1943254f889dSBrendon Cahoon /// Merge the recurrence node sets that have the same initial node.
1944254f889dSBrendon Cahoon void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
1945254f889dSBrendon Cahoon   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1946254f889dSBrendon Cahoon        ++I) {
1947254f889dSBrendon Cahoon     NodeSet &NI = *I;
1948254f889dSBrendon Cahoon     for (NodeSetType::iterator J = I + 1; J != E;) {
1949254f889dSBrendon Cahoon       NodeSet &NJ = *J;
1950254f889dSBrendon Cahoon       if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
1951254f889dSBrendon Cahoon         if (NJ.compareRecMII(NI) > 0)
1952254f889dSBrendon Cahoon           NI.setRecMII(NJ.getRecMII());
1953254f889dSBrendon Cahoon         for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI;
1954254f889dSBrendon Cahoon              ++NII)
1955254f889dSBrendon Cahoon           I->insert(*NII);
1956254f889dSBrendon Cahoon         NodeSets.erase(J);
1957254f889dSBrendon Cahoon         E = NodeSets.end();
1958254f889dSBrendon Cahoon       } else {
1959254f889dSBrendon Cahoon         ++J;
1960254f889dSBrendon Cahoon       }
1961254f889dSBrendon Cahoon     }
1962254f889dSBrendon Cahoon   }
1963254f889dSBrendon Cahoon }
1964254f889dSBrendon Cahoon 
1965254f889dSBrendon Cahoon /// Remove nodes that have been scheduled in previous NodeSets.
1966254f889dSBrendon Cahoon void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
1967254f889dSBrendon Cahoon   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1968254f889dSBrendon Cahoon        ++I)
1969254f889dSBrendon Cahoon     for (NodeSetType::iterator J = I + 1; J != E;) {
1970254f889dSBrendon Cahoon       J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
1971254f889dSBrendon Cahoon 
1972254f889dSBrendon Cahoon       if (J->size() == 0) {
1973254f889dSBrendon Cahoon         NodeSets.erase(J);
1974254f889dSBrendon Cahoon         E = NodeSets.end();
1975254f889dSBrendon Cahoon       } else {
1976254f889dSBrendon Cahoon         ++J;
1977254f889dSBrendon Cahoon       }
1978254f889dSBrendon Cahoon     }
1979254f889dSBrendon Cahoon }
1980254f889dSBrendon Cahoon 
1981254f889dSBrendon Cahoon /// Return true if Inst1 defines a value that is used in Inst2.
1982254f889dSBrendon Cahoon static bool hasDataDependence(SUnit *Inst1, SUnit *Inst2) {
1983254f889dSBrendon Cahoon   for (auto &SI : Inst1->Succs)
1984254f889dSBrendon Cahoon     if (SI.getSUnit() == Inst2 && SI.getKind() == SDep::Data)
1985254f889dSBrendon Cahoon       return true;
1986254f889dSBrendon Cahoon   return false;
1987254f889dSBrendon Cahoon }
1988254f889dSBrendon Cahoon 
1989254f889dSBrendon Cahoon /// Compute an ordered list of the dependence graph nodes, which
1990254f889dSBrendon Cahoon /// indicates the order that the nodes will be scheduled.  This is a
1991254f889dSBrendon Cahoon /// two-level algorithm. First, a partial order is created, which
1992254f889dSBrendon Cahoon /// consists of a list of sets ordered from highest to lowest priority.
1993254f889dSBrendon Cahoon void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
1994254f889dSBrendon Cahoon   SmallSetVector<SUnit *, 8> R;
1995254f889dSBrendon Cahoon   NodeOrder.clear();
1996254f889dSBrendon Cahoon 
1997254f889dSBrendon Cahoon   for (auto &Nodes : NodeSets) {
1998254f889dSBrendon Cahoon     DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
1999254f889dSBrendon Cahoon     OrderKind Order;
2000254f889dSBrendon Cahoon     SmallSetVector<SUnit *, 8> N;
2001254f889dSBrendon Cahoon     if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) {
2002254f889dSBrendon Cahoon       R.insert(N.begin(), N.end());
2003254f889dSBrendon Cahoon       Order = BottomUp;
2004254f889dSBrendon Cahoon       DEBUG(dbgs() << "  Bottom up (preds) ");
2005254f889dSBrendon Cahoon     } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) {
2006254f889dSBrendon Cahoon       R.insert(N.begin(), N.end());
2007254f889dSBrendon Cahoon       Order = TopDown;
2008254f889dSBrendon Cahoon       DEBUG(dbgs() << "  Top down (succs) ");
2009254f889dSBrendon Cahoon     } else if (isIntersect(N, Nodes, R)) {
2010254f889dSBrendon Cahoon       // If some of the successors are in the existing node-set, then use the
2011254f889dSBrendon Cahoon       // top-down ordering.
2012254f889dSBrendon Cahoon       Order = TopDown;
2013254f889dSBrendon Cahoon       DEBUG(dbgs() << "  Top down (intersect) ");
2014254f889dSBrendon Cahoon     } else if (NodeSets.size() == 1) {
2015254f889dSBrendon Cahoon       for (auto &N : Nodes)
2016254f889dSBrendon Cahoon         if (N->Succs.size() == 0)
2017254f889dSBrendon Cahoon           R.insert(N);
2018254f889dSBrendon Cahoon       Order = BottomUp;
2019254f889dSBrendon Cahoon       DEBUG(dbgs() << "  Bottom up (all) ");
2020254f889dSBrendon Cahoon     } else {
2021254f889dSBrendon Cahoon       // Find the node with the highest ASAP.
2022254f889dSBrendon Cahoon       SUnit *maxASAP = nullptr;
2023254f889dSBrendon Cahoon       for (SUnit *SU : Nodes) {
2024254f889dSBrendon Cahoon         if (maxASAP == nullptr || getASAP(SU) >= getASAP(maxASAP))
2025254f889dSBrendon Cahoon           maxASAP = SU;
2026254f889dSBrendon Cahoon       }
2027254f889dSBrendon Cahoon       R.insert(maxASAP);
2028254f889dSBrendon Cahoon       Order = BottomUp;
2029254f889dSBrendon Cahoon       DEBUG(dbgs() << "  Bottom up (default) ");
2030254f889dSBrendon Cahoon     }
2031254f889dSBrendon Cahoon 
2032254f889dSBrendon Cahoon     while (!R.empty()) {
2033254f889dSBrendon Cahoon       if (Order == TopDown) {
2034254f889dSBrendon Cahoon         // Choose the node with the maximum height.  If more than one, choose
2035254f889dSBrendon Cahoon         // the node with the lowest MOV. If still more than one, check if there
2036254f889dSBrendon Cahoon         // is a dependence between the instructions.
2037254f889dSBrendon Cahoon         while (!R.empty()) {
2038254f889dSBrendon Cahoon           SUnit *maxHeight = nullptr;
2039254f889dSBrendon Cahoon           for (SUnit *I : R) {
2040cdc71612SEugene Zelenko             if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
2041254f889dSBrendon Cahoon               maxHeight = I;
2042254f889dSBrendon Cahoon             else if (getHeight(I) == getHeight(maxHeight) &&
2043254f889dSBrendon Cahoon                      getMOV(I) < getMOV(maxHeight) &&
2044254f889dSBrendon Cahoon                      !hasDataDependence(maxHeight, I))
2045254f889dSBrendon Cahoon               maxHeight = I;
2046254f889dSBrendon Cahoon             else if (hasDataDependence(I, maxHeight))
2047254f889dSBrendon Cahoon               maxHeight = I;
2048254f889dSBrendon Cahoon           }
2049254f889dSBrendon Cahoon           NodeOrder.insert(maxHeight);
2050254f889dSBrendon Cahoon           DEBUG(dbgs() << maxHeight->NodeNum << " ");
2051254f889dSBrendon Cahoon           R.remove(maxHeight);
2052254f889dSBrendon Cahoon           for (const auto &I : maxHeight->Succs) {
2053254f889dSBrendon Cahoon             if (Nodes.count(I.getSUnit()) == 0)
2054254f889dSBrendon Cahoon               continue;
2055254f889dSBrendon Cahoon             if (NodeOrder.count(I.getSUnit()) != 0)
2056254f889dSBrendon Cahoon               continue;
2057254f889dSBrendon Cahoon             if (ignoreDependence(I, false))
2058254f889dSBrendon Cahoon               continue;
2059254f889dSBrendon Cahoon             R.insert(I.getSUnit());
2060254f889dSBrendon Cahoon           }
2061254f889dSBrendon Cahoon           // Back-edges are predecessors with an anti-dependence.
2062254f889dSBrendon Cahoon           for (const auto &I : maxHeight->Preds) {
2063254f889dSBrendon Cahoon             if (I.getKind() != SDep::Anti)
2064254f889dSBrendon Cahoon               continue;
2065254f889dSBrendon Cahoon             if (Nodes.count(I.getSUnit()) == 0)
2066254f889dSBrendon Cahoon               continue;
2067254f889dSBrendon Cahoon             if (NodeOrder.count(I.getSUnit()) != 0)
2068254f889dSBrendon Cahoon               continue;
2069254f889dSBrendon Cahoon             R.insert(I.getSUnit());
2070254f889dSBrendon Cahoon           }
2071254f889dSBrendon Cahoon         }
2072254f889dSBrendon Cahoon         Order = BottomUp;
2073254f889dSBrendon Cahoon         DEBUG(dbgs() << "\n   Switching order to bottom up ");
2074254f889dSBrendon Cahoon         SmallSetVector<SUnit *, 8> N;
2075254f889dSBrendon Cahoon         if (pred_L(NodeOrder, N, &Nodes))
2076254f889dSBrendon Cahoon           R.insert(N.begin(), N.end());
2077254f889dSBrendon Cahoon       } else {
2078254f889dSBrendon Cahoon         // Choose the node with the maximum depth.  If more than one, choose
2079254f889dSBrendon Cahoon         // the node with the lowest MOV. If there is still more than one, check
2080254f889dSBrendon Cahoon         // for a dependence between the instructions.
2081254f889dSBrendon Cahoon         while (!R.empty()) {
2082254f889dSBrendon Cahoon           SUnit *maxDepth = nullptr;
2083254f889dSBrendon Cahoon           for (SUnit *I : R) {
2084cdc71612SEugene Zelenko             if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
2085254f889dSBrendon Cahoon               maxDepth = I;
2086254f889dSBrendon Cahoon             else if (getDepth(I) == getDepth(maxDepth) &&
2087254f889dSBrendon Cahoon                      getMOV(I) < getMOV(maxDepth) &&
2088254f889dSBrendon Cahoon                      !hasDataDependence(I, maxDepth))
2089254f889dSBrendon Cahoon               maxDepth = I;
2090254f889dSBrendon Cahoon             else if (hasDataDependence(maxDepth, I))
2091254f889dSBrendon Cahoon               maxDepth = I;
2092254f889dSBrendon Cahoon           }
2093254f889dSBrendon Cahoon           NodeOrder.insert(maxDepth);
2094254f889dSBrendon Cahoon           DEBUG(dbgs() << maxDepth->NodeNum << " ");
2095254f889dSBrendon Cahoon           R.remove(maxDepth);
2096254f889dSBrendon Cahoon           if (Nodes.isExceedSU(maxDepth)) {
2097254f889dSBrendon Cahoon             Order = TopDown;
2098254f889dSBrendon Cahoon             R.clear();
2099254f889dSBrendon Cahoon             R.insert(Nodes.getNode(0));
2100254f889dSBrendon Cahoon             break;
2101254f889dSBrendon Cahoon           }
2102254f889dSBrendon Cahoon           for (const auto &I : maxDepth->Preds) {
2103254f889dSBrendon Cahoon             if (Nodes.count(I.getSUnit()) == 0)
2104254f889dSBrendon Cahoon               continue;
2105254f889dSBrendon Cahoon             if (NodeOrder.count(I.getSUnit()) != 0)
2106254f889dSBrendon Cahoon               continue;
2107254f889dSBrendon Cahoon             if (I.getKind() == SDep::Anti)
2108254f889dSBrendon Cahoon               continue;
2109254f889dSBrendon Cahoon             R.insert(I.getSUnit());
2110254f889dSBrendon Cahoon           }
2111254f889dSBrendon Cahoon           // Back-edges are predecessors with an anti-dependence.
2112254f889dSBrendon Cahoon           for (const auto &I : maxDepth->Succs) {
2113254f889dSBrendon Cahoon             if (I.getKind() != SDep::Anti)
2114254f889dSBrendon Cahoon               continue;
2115254f889dSBrendon Cahoon             if (Nodes.count(I.getSUnit()) == 0)
2116254f889dSBrendon Cahoon               continue;
2117254f889dSBrendon Cahoon             if (NodeOrder.count(I.getSUnit()) != 0)
2118254f889dSBrendon Cahoon               continue;
2119254f889dSBrendon Cahoon             R.insert(I.getSUnit());
2120254f889dSBrendon Cahoon           }
2121254f889dSBrendon Cahoon         }
2122254f889dSBrendon Cahoon         Order = TopDown;
2123254f889dSBrendon Cahoon         DEBUG(dbgs() << "\n   Switching order to top down ");
2124254f889dSBrendon Cahoon         SmallSetVector<SUnit *, 8> N;
2125254f889dSBrendon Cahoon         if (succ_L(NodeOrder, N, &Nodes))
2126254f889dSBrendon Cahoon           R.insert(N.begin(), N.end());
2127254f889dSBrendon Cahoon       }
2128254f889dSBrendon Cahoon     }
2129254f889dSBrendon Cahoon     DEBUG(dbgs() << "\nDone with Nodeset\n");
2130254f889dSBrendon Cahoon   }
2131254f889dSBrendon Cahoon 
2132254f889dSBrendon Cahoon   DEBUG({
2133254f889dSBrendon Cahoon     dbgs() << "Node order: ";
2134254f889dSBrendon Cahoon     for (SUnit *I : NodeOrder)
2135254f889dSBrendon Cahoon       dbgs() << " " << I->NodeNum << " ";
2136254f889dSBrendon Cahoon     dbgs() << "\n";
2137254f889dSBrendon Cahoon   });
2138254f889dSBrendon Cahoon }
2139254f889dSBrendon Cahoon 
2140254f889dSBrendon Cahoon /// Process the nodes in the computed order and create the pipelined schedule
2141254f889dSBrendon Cahoon /// of the instructions, if possible. Return true if a schedule is found.
2142254f889dSBrendon Cahoon bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
2143254f889dSBrendon Cahoon 
2144254f889dSBrendon Cahoon   if (NodeOrder.size() == 0)
2145254f889dSBrendon Cahoon     return false;
2146254f889dSBrendon Cahoon 
2147254f889dSBrendon Cahoon   bool scheduleFound = false;
2148254f889dSBrendon Cahoon   // Keep increasing II until a valid schedule is found.
2149254f889dSBrendon Cahoon   for (unsigned II = MII; II < MII + 10 && !scheduleFound; ++II) {
2150254f889dSBrendon Cahoon     Schedule.reset();
2151254f889dSBrendon Cahoon     Schedule.setInitiationInterval(II);
2152254f889dSBrendon Cahoon     DEBUG(dbgs() << "Try to schedule with " << II << "\n");
2153254f889dSBrendon Cahoon 
2154254f889dSBrendon Cahoon     SetVector<SUnit *>::iterator NI = NodeOrder.begin();
2155254f889dSBrendon Cahoon     SetVector<SUnit *>::iterator NE = NodeOrder.end();
2156254f889dSBrendon Cahoon     do {
2157254f889dSBrendon Cahoon       SUnit *SU = *NI;
2158254f889dSBrendon Cahoon 
2159254f889dSBrendon Cahoon       // Compute the schedule time for the instruction, which is based
2160254f889dSBrendon Cahoon       // upon the scheduled time for any predecessors/successors.
2161254f889dSBrendon Cahoon       int EarlyStart = INT_MIN;
2162254f889dSBrendon Cahoon       int LateStart = INT_MAX;
2163254f889dSBrendon Cahoon       // These values are set when the size of the schedule window is limited
2164254f889dSBrendon Cahoon       // due to chain dependences.
2165254f889dSBrendon Cahoon       int SchedEnd = INT_MAX;
2166254f889dSBrendon Cahoon       int SchedStart = INT_MIN;
2167254f889dSBrendon Cahoon       Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
2168254f889dSBrendon Cahoon                             II, this);
2169254f889dSBrendon Cahoon       DEBUG({
2170254f889dSBrendon Cahoon         dbgs() << "Inst (" << SU->NodeNum << ") ";
2171254f889dSBrendon Cahoon         SU->getInstr()->dump();
2172254f889dSBrendon Cahoon         dbgs() << "\n";
2173254f889dSBrendon Cahoon       });
2174254f889dSBrendon Cahoon       DEBUG({
2175254f889dSBrendon Cahoon         dbgs() << "\tes: " << EarlyStart << " ls: " << LateStart
2176254f889dSBrendon Cahoon                << " me: " << SchedEnd << " ms: " << SchedStart << "\n";
2177254f889dSBrendon Cahoon       });
2178254f889dSBrendon Cahoon 
2179254f889dSBrendon Cahoon       if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
2180254f889dSBrendon Cahoon           SchedStart > LateStart)
2181254f889dSBrendon Cahoon         scheduleFound = false;
2182254f889dSBrendon Cahoon       else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
2183254f889dSBrendon Cahoon         SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
2184254f889dSBrendon Cahoon         scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
2185254f889dSBrendon Cahoon       } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
2186254f889dSBrendon Cahoon         SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
2187254f889dSBrendon Cahoon         scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
2188254f889dSBrendon Cahoon       } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
2189254f889dSBrendon Cahoon         SchedEnd =
2190254f889dSBrendon Cahoon             std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
2191254f889dSBrendon Cahoon         // When scheduling a Phi it is better to start at the late cycle and go
2192254f889dSBrendon Cahoon         // backwards. The default order may insert the Phi too far away from
2193254f889dSBrendon Cahoon         // its first dependence.
2194254f889dSBrendon Cahoon         if (SU->getInstr()->isPHI())
2195254f889dSBrendon Cahoon           scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
2196254f889dSBrendon Cahoon         else
2197254f889dSBrendon Cahoon           scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
2198254f889dSBrendon Cahoon       } else {
2199254f889dSBrendon Cahoon         int FirstCycle = Schedule.getFirstCycle();
2200254f889dSBrendon Cahoon         scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
2201254f889dSBrendon Cahoon                                         FirstCycle + getASAP(SU) + II - 1, II);
2202254f889dSBrendon Cahoon       }
2203254f889dSBrendon Cahoon       // Even if we find a schedule, make sure the schedule doesn't exceed the
2204254f889dSBrendon Cahoon       // allowable number of stages. We keep trying if this happens.
2205254f889dSBrendon Cahoon       if (scheduleFound)
2206254f889dSBrendon Cahoon         if (SwpMaxStages > -1 &&
2207254f889dSBrendon Cahoon             Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
2208254f889dSBrendon Cahoon           scheduleFound = false;
2209254f889dSBrendon Cahoon 
2210254f889dSBrendon Cahoon       DEBUG({
2211254f889dSBrendon Cahoon         if (!scheduleFound)
2212254f889dSBrendon Cahoon           dbgs() << "\tCan't schedule\n";
2213254f889dSBrendon Cahoon       });
2214254f889dSBrendon Cahoon     } while (++NI != NE && scheduleFound);
2215254f889dSBrendon Cahoon 
2216254f889dSBrendon Cahoon     // If a schedule is found, check if it is a valid schedule too.
2217254f889dSBrendon Cahoon     if (scheduleFound)
2218254f889dSBrendon Cahoon       scheduleFound = Schedule.isValidSchedule(this);
2219254f889dSBrendon Cahoon   }
2220254f889dSBrendon Cahoon 
2221254f889dSBrendon Cahoon   DEBUG(dbgs() << "Schedule Found? " << scheduleFound << "\n");
2222254f889dSBrendon Cahoon 
2223254f889dSBrendon Cahoon   if (scheduleFound)
2224254f889dSBrendon Cahoon     Schedule.finalizeSchedule(this);
2225254f889dSBrendon Cahoon   else
2226254f889dSBrendon Cahoon     Schedule.reset();
2227254f889dSBrendon Cahoon 
2228254f889dSBrendon Cahoon   return scheduleFound && Schedule.getMaxStageCount() > 0;
2229254f889dSBrendon Cahoon }
2230254f889dSBrendon Cahoon 
2231254f889dSBrendon Cahoon /// Given a schedule for the loop, generate a new version of the loop,
2232254f889dSBrendon Cahoon /// and replace the old version.  This function generates a prolog
2233254f889dSBrendon Cahoon /// that contains the initial iterations in the pipeline, and kernel
2234254f889dSBrendon Cahoon /// loop, and the epilogue that contains the code for the final
2235254f889dSBrendon Cahoon /// iterations.
2236254f889dSBrendon Cahoon void SwingSchedulerDAG::generatePipelinedLoop(SMSchedule &Schedule) {
2237254f889dSBrendon Cahoon   // Create a new basic block for the kernel and add it to the CFG.
2238254f889dSBrendon Cahoon   MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
2239254f889dSBrendon Cahoon 
2240254f889dSBrendon Cahoon   unsigned MaxStageCount = Schedule.getMaxStageCount();
2241254f889dSBrendon Cahoon 
2242254f889dSBrendon Cahoon   // Remember the registers that are used in different stages. The index is
2243254f889dSBrendon Cahoon   // the iteration, or stage, that the instruction is scheduled in.  This is
2244254f889dSBrendon Cahoon   // a map between register names in the orignal block and the names created
2245254f889dSBrendon Cahoon   // in each stage of the pipelined loop.
2246254f889dSBrendon Cahoon   ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
2247254f889dSBrendon Cahoon   InstrMapTy InstrMap;
2248254f889dSBrendon Cahoon 
2249254f889dSBrendon Cahoon   SmallVector<MachineBasicBlock *, 4> PrologBBs;
2250254f889dSBrendon Cahoon   // Generate the prolog instructions that set up the pipeline.
2251254f889dSBrendon Cahoon   generateProlog(Schedule, MaxStageCount, KernelBB, VRMap, PrologBBs);
2252254f889dSBrendon Cahoon   MF.insert(BB->getIterator(), KernelBB);
2253254f889dSBrendon Cahoon 
2254254f889dSBrendon Cahoon   // Rearrange the instructions to generate the new, pipelined loop,
2255254f889dSBrendon Cahoon   // and update register names as needed.
2256254f889dSBrendon Cahoon   for (int Cycle = Schedule.getFirstCycle(),
2257254f889dSBrendon Cahoon            LastCycle = Schedule.getFinalCycle();
2258254f889dSBrendon Cahoon        Cycle <= LastCycle; ++Cycle) {
2259254f889dSBrendon Cahoon     std::deque<SUnit *> &CycleInstrs = Schedule.getInstructions(Cycle);
2260254f889dSBrendon Cahoon     // This inner loop schedules each instruction in the cycle.
2261254f889dSBrendon Cahoon     for (SUnit *CI : CycleInstrs) {
2262254f889dSBrendon Cahoon       if (CI->getInstr()->isPHI())
2263254f889dSBrendon Cahoon         continue;
2264254f889dSBrendon Cahoon       unsigned StageNum = Schedule.stageScheduled(getSUnit(CI->getInstr()));
2265254f889dSBrendon Cahoon       MachineInstr *NewMI = cloneInstr(CI->getInstr(), MaxStageCount, StageNum);
2266254f889dSBrendon Cahoon       updateInstruction(NewMI, false, MaxStageCount, StageNum, Schedule, VRMap);
2267254f889dSBrendon Cahoon       KernelBB->push_back(NewMI);
2268254f889dSBrendon Cahoon       InstrMap[NewMI] = CI->getInstr();
2269254f889dSBrendon Cahoon     }
2270254f889dSBrendon Cahoon   }
2271254f889dSBrendon Cahoon 
2272254f889dSBrendon Cahoon   // Copy any terminator instructions to the new kernel, and update
2273254f889dSBrendon Cahoon   // names as needed.
2274254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator I = BB->getFirstTerminator(),
2275254f889dSBrendon Cahoon                                    E = BB->instr_end();
2276254f889dSBrendon Cahoon        I != E; ++I) {
2277254f889dSBrendon Cahoon     MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
2278254f889dSBrendon Cahoon     updateInstruction(NewMI, false, MaxStageCount, 0, Schedule, VRMap);
2279254f889dSBrendon Cahoon     KernelBB->push_back(NewMI);
2280254f889dSBrendon Cahoon     InstrMap[NewMI] = &*I;
2281254f889dSBrendon Cahoon   }
2282254f889dSBrendon Cahoon 
2283254f889dSBrendon Cahoon   KernelBB->transferSuccessors(BB);
2284254f889dSBrendon Cahoon   KernelBB->replaceSuccessor(BB, KernelBB);
2285254f889dSBrendon Cahoon 
2286254f889dSBrendon Cahoon   generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule,
2287254f889dSBrendon Cahoon                        VRMap, InstrMap, MaxStageCount, MaxStageCount, false);
2288254f889dSBrendon Cahoon   generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule, VRMap,
2289254f889dSBrendon Cahoon                InstrMap, MaxStageCount, MaxStageCount, false);
2290254f889dSBrendon Cahoon 
2291254f889dSBrendon Cahoon   DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
2292254f889dSBrendon Cahoon 
2293254f889dSBrendon Cahoon   SmallVector<MachineBasicBlock *, 4> EpilogBBs;
2294254f889dSBrendon Cahoon   // Generate the epilog instructions to complete the pipeline.
2295254f889dSBrendon Cahoon   generateEpilog(Schedule, MaxStageCount, KernelBB, VRMap, EpilogBBs,
2296254f889dSBrendon Cahoon                  PrologBBs);
2297254f889dSBrendon Cahoon 
2298254f889dSBrendon Cahoon   // We need this step because the register allocation doesn't handle some
2299254f889dSBrendon Cahoon   // situations well, so we insert copies to help out.
2300254f889dSBrendon Cahoon   splitLifetimes(KernelBB, EpilogBBs, Schedule);
2301254f889dSBrendon Cahoon 
2302254f889dSBrendon Cahoon   // Remove dead instructions due to loop induction variables.
2303254f889dSBrendon Cahoon   removeDeadInstructions(KernelBB, EpilogBBs);
2304254f889dSBrendon Cahoon 
2305254f889dSBrendon Cahoon   // Add branches between prolog and epilog blocks.
2306254f889dSBrendon Cahoon   addBranches(PrologBBs, KernelBB, EpilogBBs, Schedule, VRMap);
2307254f889dSBrendon Cahoon 
2308254f889dSBrendon Cahoon   // Remove the original loop since it's no longer referenced.
2309254f889dSBrendon Cahoon   BB->clear();
2310254f889dSBrendon Cahoon   BB->eraseFromParent();
2311254f889dSBrendon Cahoon 
2312254f889dSBrendon Cahoon   delete[] VRMap;
2313254f889dSBrendon Cahoon }
2314254f889dSBrendon Cahoon 
2315254f889dSBrendon Cahoon /// Generate the pipeline prolog code.
2316254f889dSBrendon Cahoon void SwingSchedulerDAG::generateProlog(SMSchedule &Schedule, unsigned LastStage,
2317254f889dSBrendon Cahoon                                        MachineBasicBlock *KernelBB,
2318254f889dSBrendon Cahoon                                        ValueMapTy *VRMap,
2319254f889dSBrendon Cahoon                                        MBBVectorTy &PrologBBs) {
2320254f889dSBrendon Cahoon   MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader();
2321254f889dSBrendon Cahoon   assert(PreheaderBB != NULL &&
2322254f889dSBrendon Cahoon          "Need to add code to handle loops w/o preheader");
2323254f889dSBrendon Cahoon   MachineBasicBlock *PredBB = PreheaderBB;
2324254f889dSBrendon Cahoon   InstrMapTy InstrMap;
2325254f889dSBrendon Cahoon 
2326254f889dSBrendon Cahoon   // Generate a basic block for each stage, not including the last stage,
2327254f889dSBrendon Cahoon   // which will be generated in the kernel. Each basic block may contain
2328254f889dSBrendon Cahoon   // instructions from multiple stages/iterations.
2329254f889dSBrendon Cahoon   for (unsigned i = 0; i < LastStage; ++i) {
2330254f889dSBrendon Cahoon     // Create and insert the prolog basic block prior to the original loop
2331254f889dSBrendon Cahoon     // basic block.  The original loop is removed later.
2332254f889dSBrendon Cahoon     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
2333254f889dSBrendon Cahoon     PrologBBs.push_back(NewBB);
2334254f889dSBrendon Cahoon     MF.insert(BB->getIterator(), NewBB);
2335254f889dSBrendon Cahoon     NewBB->transferSuccessors(PredBB);
2336254f889dSBrendon Cahoon     PredBB->addSuccessor(NewBB);
2337254f889dSBrendon Cahoon     PredBB = NewBB;
2338254f889dSBrendon Cahoon 
2339254f889dSBrendon Cahoon     // Generate instructions for each appropriate stage. Process instructions
2340254f889dSBrendon Cahoon     // in original program order.
2341254f889dSBrendon Cahoon     for (int StageNum = i; StageNum >= 0; --StageNum) {
2342254f889dSBrendon Cahoon       for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2343254f889dSBrendon Cahoon                                        BBE = BB->getFirstTerminator();
2344254f889dSBrendon Cahoon            BBI != BBE; ++BBI) {
2345254f889dSBrendon Cahoon         if (Schedule.isScheduledAtStage(getSUnit(&*BBI), (unsigned)StageNum)) {
2346254f889dSBrendon Cahoon           if (BBI->isPHI())
2347254f889dSBrendon Cahoon             continue;
2348254f889dSBrendon Cahoon           MachineInstr *NewMI =
2349254f889dSBrendon Cahoon               cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum, Schedule);
2350254f889dSBrendon Cahoon           updateInstruction(NewMI, false, i, (unsigned)StageNum, Schedule,
2351254f889dSBrendon Cahoon                             VRMap);
2352254f889dSBrendon Cahoon           NewBB->push_back(NewMI);
2353254f889dSBrendon Cahoon           InstrMap[NewMI] = &*BBI;
2354254f889dSBrendon Cahoon         }
2355254f889dSBrendon Cahoon       }
2356254f889dSBrendon Cahoon     }
2357254f889dSBrendon Cahoon     rewritePhiValues(NewBB, i, Schedule, VRMap, InstrMap);
2358254f889dSBrendon Cahoon     DEBUG({
2359254f889dSBrendon Cahoon       dbgs() << "prolog:\n";
2360254f889dSBrendon Cahoon       NewBB->dump();
2361254f889dSBrendon Cahoon     });
2362254f889dSBrendon Cahoon   }
2363254f889dSBrendon Cahoon 
2364254f889dSBrendon Cahoon   PredBB->replaceSuccessor(BB, KernelBB);
2365254f889dSBrendon Cahoon 
2366254f889dSBrendon Cahoon   // Check if we need to remove the branch from the preheader to the original
2367254f889dSBrendon Cahoon   // loop, and replace it with a branch to the new loop.
23681b9fc8edSMatt Arsenault   unsigned numBranches = TII->removeBranch(*PreheaderBB);
2369254f889dSBrendon Cahoon   if (numBranches) {
2370254f889dSBrendon Cahoon     SmallVector<MachineOperand, 0> Cond;
2371e8e0f5caSMatt Arsenault     TII->insertBranch(*PreheaderBB, PrologBBs[0], nullptr, Cond, DebugLoc());
2372254f889dSBrendon Cahoon   }
2373254f889dSBrendon Cahoon }
2374254f889dSBrendon Cahoon 
2375254f889dSBrendon Cahoon /// Generate the pipeline epilog code. The epilog code finishes the iterations
2376254f889dSBrendon Cahoon /// that were started in either the prolog or the kernel.  We create a basic
2377254f889dSBrendon Cahoon /// block for each stage that needs to complete.
2378254f889dSBrendon Cahoon void SwingSchedulerDAG::generateEpilog(SMSchedule &Schedule, unsigned LastStage,
2379254f889dSBrendon Cahoon                                        MachineBasicBlock *KernelBB,
2380254f889dSBrendon Cahoon                                        ValueMapTy *VRMap,
2381254f889dSBrendon Cahoon                                        MBBVectorTy &EpilogBBs,
2382254f889dSBrendon Cahoon                                        MBBVectorTy &PrologBBs) {
2383254f889dSBrendon Cahoon   // We need to change the branch from the kernel to the first epilog block, so
2384254f889dSBrendon Cahoon   // this call to analyze branch uses the kernel rather than the original BB.
2385254f889dSBrendon Cahoon   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2386254f889dSBrendon Cahoon   SmallVector<MachineOperand, 4> Cond;
2387254f889dSBrendon Cahoon   bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
2388254f889dSBrendon Cahoon   assert(!checkBranch && "generateEpilog must be able to analyze the branch");
2389254f889dSBrendon Cahoon   if (checkBranch)
2390254f889dSBrendon Cahoon     return;
2391254f889dSBrendon Cahoon 
2392254f889dSBrendon Cahoon   MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
2393254f889dSBrendon Cahoon   if (*LoopExitI == KernelBB)
2394254f889dSBrendon Cahoon     ++LoopExitI;
2395254f889dSBrendon Cahoon   assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
2396254f889dSBrendon Cahoon   MachineBasicBlock *LoopExitBB = *LoopExitI;
2397254f889dSBrendon Cahoon 
2398254f889dSBrendon Cahoon   MachineBasicBlock *PredBB = KernelBB;
2399254f889dSBrendon Cahoon   MachineBasicBlock *EpilogStart = LoopExitBB;
2400254f889dSBrendon Cahoon   InstrMapTy InstrMap;
2401254f889dSBrendon Cahoon 
2402254f889dSBrendon Cahoon   // Generate a basic block for each stage, not including the last stage,
2403254f889dSBrendon Cahoon   // which was generated for the kernel.  Each basic block may contain
2404254f889dSBrendon Cahoon   // instructions from multiple stages/iterations.
2405254f889dSBrendon Cahoon   int EpilogStage = LastStage + 1;
2406254f889dSBrendon Cahoon   for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
2407254f889dSBrendon Cahoon     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
2408254f889dSBrendon Cahoon     EpilogBBs.push_back(NewBB);
2409254f889dSBrendon Cahoon     MF.insert(BB->getIterator(), NewBB);
2410254f889dSBrendon Cahoon 
2411254f889dSBrendon Cahoon     PredBB->replaceSuccessor(LoopExitBB, NewBB);
2412254f889dSBrendon Cahoon     NewBB->addSuccessor(LoopExitBB);
2413254f889dSBrendon Cahoon 
2414254f889dSBrendon Cahoon     if (EpilogStart == LoopExitBB)
2415254f889dSBrendon Cahoon       EpilogStart = NewBB;
2416254f889dSBrendon Cahoon 
2417254f889dSBrendon Cahoon     // Add instructions to the epilog depending on the current block.
2418254f889dSBrendon Cahoon     // Process instructions in original program order.
2419254f889dSBrendon Cahoon     for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
2420254f889dSBrendon Cahoon       for (auto &BBI : *BB) {
2421254f889dSBrendon Cahoon         if (BBI.isPHI())
2422254f889dSBrendon Cahoon           continue;
2423254f889dSBrendon Cahoon         MachineInstr *In = &BBI;
2424254f889dSBrendon Cahoon         if (Schedule.isScheduledAtStage(getSUnit(In), StageNum)) {
2425254f889dSBrendon Cahoon           MachineInstr *NewMI = cloneInstr(In, EpilogStage - LastStage, 0);
2426254f889dSBrendon Cahoon           updateInstruction(NewMI, i == 1, EpilogStage, 0, Schedule, VRMap);
2427254f889dSBrendon Cahoon           NewBB->push_back(NewMI);
2428254f889dSBrendon Cahoon           InstrMap[NewMI] = In;
2429254f889dSBrendon Cahoon         }
2430254f889dSBrendon Cahoon       }
2431254f889dSBrendon Cahoon     }
2432254f889dSBrendon Cahoon     generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule,
2433254f889dSBrendon Cahoon                          VRMap, InstrMap, LastStage, EpilogStage, i == 1);
2434254f889dSBrendon Cahoon     generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, VRMap,
2435254f889dSBrendon Cahoon                  InstrMap, LastStage, EpilogStage, i == 1);
2436254f889dSBrendon Cahoon     PredBB = NewBB;
2437254f889dSBrendon Cahoon 
2438254f889dSBrendon Cahoon     DEBUG({
2439254f889dSBrendon Cahoon       dbgs() << "epilog:\n";
2440254f889dSBrendon Cahoon       NewBB->dump();
2441254f889dSBrendon Cahoon     });
2442254f889dSBrendon Cahoon   }
2443254f889dSBrendon Cahoon 
2444254f889dSBrendon Cahoon   // Fix any Phi nodes in the loop exit block.
2445254f889dSBrendon Cahoon   for (MachineInstr &MI : *LoopExitBB) {
2446254f889dSBrendon Cahoon     if (!MI.isPHI())
2447254f889dSBrendon Cahoon       break;
2448254f889dSBrendon Cahoon     for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
2449254f889dSBrendon Cahoon       MachineOperand &MO = MI.getOperand(i);
2450254f889dSBrendon Cahoon       if (MO.getMBB() == BB)
2451254f889dSBrendon Cahoon         MO.setMBB(PredBB);
2452254f889dSBrendon Cahoon     }
2453254f889dSBrendon Cahoon   }
2454254f889dSBrendon Cahoon 
2455254f889dSBrendon Cahoon   // Create a branch to the new epilog from the kernel.
2456254f889dSBrendon Cahoon   // Remove the original branch and add a new branch to the epilog.
24571b9fc8edSMatt Arsenault   TII->removeBranch(*KernelBB);
2458e8e0f5caSMatt Arsenault   TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
2459254f889dSBrendon Cahoon   // Add a branch to the loop exit.
2460254f889dSBrendon Cahoon   if (EpilogBBs.size() > 0) {
2461254f889dSBrendon Cahoon     MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
2462254f889dSBrendon Cahoon     SmallVector<MachineOperand, 4> Cond1;
2463e8e0f5caSMatt Arsenault     TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
2464254f889dSBrendon Cahoon   }
2465254f889dSBrendon Cahoon }
2466254f889dSBrendon Cahoon 
2467254f889dSBrendon Cahoon /// Replace all uses of FromReg that appear outside the specified
2468254f889dSBrendon Cahoon /// basic block with ToReg.
2469254f889dSBrendon Cahoon static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
2470254f889dSBrendon Cahoon                                     MachineBasicBlock *MBB,
2471254f889dSBrendon Cahoon                                     MachineRegisterInfo &MRI,
2472254f889dSBrendon Cahoon                                     LiveIntervals &LIS) {
2473254f889dSBrendon Cahoon   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(FromReg),
2474254f889dSBrendon Cahoon                                          E = MRI.use_end();
2475254f889dSBrendon Cahoon        I != E;) {
2476254f889dSBrendon Cahoon     MachineOperand &O = *I;
2477254f889dSBrendon Cahoon     ++I;
2478254f889dSBrendon Cahoon     if (O.getParent()->getParent() != MBB)
2479254f889dSBrendon Cahoon       O.setReg(ToReg);
2480254f889dSBrendon Cahoon   }
2481254f889dSBrendon Cahoon   if (!LIS.hasInterval(ToReg))
2482254f889dSBrendon Cahoon     LIS.createEmptyInterval(ToReg);
2483254f889dSBrendon Cahoon }
2484254f889dSBrendon Cahoon 
2485254f889dSBrendon Cahoon /// Return true if the register has a use that occurs outside the
2486254f889dSBrendon Cahoon /// specified loop.
2487254f889dSBrendon Cahoon static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
2488254f889dSBrendon Cahoon                             MachineRegisterInfo &MRI) {
2489254f889dSBrendon Cahoon   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(Reg),
2490254f889dSBrendon Cahoon                                          E = MRI.use_end();
2491254f889dSBrendon Cahoon        I != E; ++I)
2492254f889dSBrendon Cahoon     if (I->getParent()->getParent() != BB)
2493254f889dSBrendon Cahoon       return true;
2494254f889dSBrendon Cahoon   return false;
2495254f889dSBrendon Cahoon }
2496254f889dSBrendon Cahoon 
2497254f889dSBrendon Cahoon /// Generate Phis for the specific block in the generated pipelined code.
2498254f889dSBrendon Cahoon /// This function looks at the Phis from the original code to guide the
2499254f889dSBrendon Cahoon /// creation of new Phis.
2500254f889dSBrendon Cahoon void SwingSchedulerDAG::generateExistingPhis(
2501254f889dSBrendon Cahoon     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2502254f889dSBrendon Cahoon     MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2503254f889dSBrendon Cahoon     InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2504254f889dSBrendon Cahoon     bool IsLast) {
2505254f889dSBrendon Cahoon   // Compute the stage number for the inital value of the Phi, which
2506254f889dSBrendon Cahoon   // comes from the prolog. The prolog to use depends on to which kernel/
2507254f889dSBrendon Cahoon   // epilog that we're adding the Phi.
2508254f889dSBrendon Cahoon   unsigned PrologStage = 0;
2509254f889dSBrendon Cahoon   unsigned PrevStage = 0;
2510254f889dSBrendon Cahoon   bool InKernel = (LastStageNum == CurStageNum);
2511254f889dSBrendon Cahoon   if (InKernel) {
2512254f889dSBrendon Cahoon     PrologStage = LastStageNum - 1;
2513254f889dSBrendon Cahoon     PrevStage = CurStageNum;
2514254f889dSBrendon Cahoon   } else {
2515254f889dSBrendon Cahoon     PrologStage = LastStageNum - (CurStageNum - LastStageNum);
2516254f889dSBrendon Cahoon     PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
2517254f889dSBrendon Cahoon   }
2518254f889dSBrendon Cahoon 
2519254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2520254f889dSBrendon Cahoon                                    BBE = BB->getFirstNonPHI();
2521254f889dSBrendon Cahoon        BBI != BBE; ++BBI) {
2522254f889dSBrendon Cahoon     unsigned Def = BBI->getOperand(0).getReg();
2523254f889dSBrendon Cahoon 
2524254f889dSBrendon Cahoon     unsigned InitVal = 0;
2525254f889dSBrendon Cahoon     unsigned LoopVal = 0;
2526254f889dSBrendon Cahoon     getPhiRegs(*BBI, BB, InitVal, LoopVal);
2527254f889dSBrendon Cahoon 
2528254f889dSBrendon Cahoon     unsigned PhiOp1 = 0;
2529254f889dSBrendon Cahoon     // The Phi value from the loop body typically is defined in the loop, but
2530254f889dSBrendon Cahoon     // not always. So, we need to check if the value is defined in the loop.
2531254f889dSBrendon Cahoon     unsigned PhiOp2 = LoopVal;
2532254f889dSBrendon Cahoon     if (VRMap[LastStageNum].count(LoopVal))
2533254f889dSBrendon Cahoon       PhiOp2 = VRMap[LastStageNum][LoopVal];
2534254f889dSBrendon Cahoon 
2535254f889dSBrendon Cahoon     int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2536254f889dSBrendon Cahoon     int LoopValStage =
2537254f889dSBrendon Cahoon         Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
2538254f889dSBrendon Cahoon     unsigned NumStages = Schedule.getStagesForReg(Def, CurStageNum);
2539254f889dSBrendon Cahoon     if (NumStages == 0) {
2540254f889dSBrendon Cahoon       // We don't need to generate a Phi anymore, but we need to rename any uses
2541254f889dSBrendon Cahoon       // of the Phi value.
2542254f889dSBrendon Cahoon       unsigned NewReg = VRMap[PrevStage][LoopVal];
2543254f889dSBrendon Cahoon       rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, 0, &*BBI,
2544254f889dSBrendon Cahoon                             Def, NewReg);
2545254f889dSBrendon Cahoon       if (VRMap[CurStageNum].count(LoopVal))
2546254f889dSBrendon Cahoon         VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
2547254f889dSBrendon Cahoon     }
2548254f889dSBrendon Cahoon     // Adjust the number of Phis needed depending on the number of prologs left,
2549254f889dSBrendon Cahoon     // and the distance from where the Phi is first scheduled.
2550254f889dSBrendon Cahoon     unsigned NumPhis = NumStages;
2551254f889dSBrendon Cahoon     if (!InKernel && (int)PrologStage < LoopValStage)
2552254f889dSBrendon Cahoon       // The NumPhis is the maximum number of new Phis needed during the steady
2553254f889dSBrendon Cahoon       // state. If the Phi has not been scheduled in current prolog, then we
2554254f889dSBrendon Cahoon       // need to generate less Phis.
2555254f889dSBrendon Cahoon       NumPhis = std::max((int)NumPhis - (int)(LoopValStage - PrologStage), 1);
2556254f889dSBrendon Cahoon     // The number of Phis cannot exceed the number of prolog stages. Each
2557254f889dSBrendon Cahoon     // stage can potentially define two values.
2558254f889dSBrendon Cahoon     NumPhis = std::min(NumPhis, PrologStage + 2);
2559254f889dSBrendon Cahoon 
2560254f889dSBrendon Cahoon     unsigned NewReg = 0;
2561254f889dSBrendon Cahoon 
2562254f889dSBrendon Cahoon     unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
2563254f889dSBrendon Cahoon     // In the epilog, we may need to look back one stage to get the correct
2564254f889dSBrendon Cahoon     // Phi name because the epilog and prolog blocks execute the same stage.
2565254f889dSBrendon Cahoon     // The correct name is from the previous block only when the Phi has
2566254f889dSBrendon Cahoon     // been completely scheduled prior to the epilog, and Phi value is not
2567254f889dSBrendon Cahoon     // needed in multiple stages.
2568254f889dSBrendon Cahoon     int StageDiff = 0;
2569254f889dSBrendon Cahoon     if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
2570254f889dSBrendon Cahoon         NumPhis == 1)
2571254f889dSBrendon Cahoon       StageDiff = 1;
2572254f889dSBrendon Cahoon     // Adjust the computations below when the phi and the loop definition
2573254f889dSBrendon Cahoon     // are scheduled in different stages.
2574254f889dSBrendon Cahoon     if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
2575254f889dSBrendon Cahoon       StageDiff = StageScheduled - LoopValStage;
2576254f889dSBrendon Cahoon     for (unsigned np = 0; np < NumPhis; ++np) {
2577254f889dSBrendon Cahoon       // If the Phi hasn't been scheduled, then use the initial Phi operand
2578254f889dSBrendon Cahoon       // value. Otherwise, use the scheduled version of the instruction. This
2579254f889dSBrendon Cahoon       // is a little complicated when a Phi references another Phi.
2580254f889dSBrendon Cahoon       if (np > PrologStage || StageScheduled >= (int)LastStageNum)
2581254f889dSBrendon Cahoon         PhiOp1 = InitVal;
2582254f889dSBrendon Cahoon       // Check if the Phi has already been scheduled in a prolog stage.
2583254f889dSBrendon Cahoon       else if (PrologStage >= AccessStage + StageDiff + np &&
2584254f889dSBrendon Cahoon                VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
2585254f889dSBrendon Cahoon         PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
2586254f889dSBrendon Cahoon       // Check if the Phi has already been scheduled, but the loop intruction
2587254f889dSBrendon Cahoon       // is either another Phi, or doesn't occur in the loop.
2588254f889dSBrendon Cahoon       else if (PrologStage >= AccessStage + StageDiff + np) {
2589254f889dSBrendon Cahoon         // If the Phi references another Phi, we need to examine the other
2590254f889dSBrendon Cahoon         // Phi to get the correct value.
2591254f889dSBrendon Cahoon         PhiOp1 = LoopVal;
2592254f889dSBrendon Cahoon         MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
2593254f889dSBrendon Cahoon         int Indirects = 1;
2594254f889dSBrendon Cahoon         while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
2595254f889dSBrendon Cahoon           int PhiStage = Schedule.stageScheduled(getSUnit(InstOp1));
2596254f889dSBrendon Cahoon           if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
2597254f889dSBrendon Cahoon             PhiOp1 = getInitPhiReg(*InstOp1, BB);
2598254f889dSBrendon Cahoon           else
2599254f889dSBrendon Cahoon             PhiOp1 = getLoopPhiReg(*InstOp1, BB);
2600254f889dSBrendon Cahoon           InstOp1 = MRI.getVRegDef(PhiOp1);
2601254f889dSBrendon Cahoon           int PhiOpStage = Schedule.stageScheduled(getSUnit(InstOp1));
2602254f889dSBrendon Cahoon           int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
2603254f889dSBrendon Cahoon           if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
2604254f889dSBrendon Cahoon               VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
2605254f889dSBrendon Cahoon             PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
2606254f889dSBrendon Cahoon             break;
2607254f889dSBrendon Cahoon           }
2608254f889dSBrendon Cahoon           ++Indirects;
2609254f889dSBrendon Cahoon         }
2610254f889dSBrendon Cahoon       } else
2611254f889dSBrendon Cahoon         PhiOp1 = InitVal;
2612254f889dSBrendon Cahoon       // If this references a generated Phi in the kernel, get the Phi operand
2613254f889dSBrendon Cahoon       // from the incoming block.
2614254f889dSBrendon Cahoon       if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
2615254f889dSBrendon Cahoon         if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2616254f889dSBrendon Cahoon           PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2617254f889dSBrendon Cahoon 
2618254f889dSBrendon Cahoon       MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
2619254f889dSBrendon Cahoon       bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
2620254f889dSBrendon Cahoon       // In the epilog, a map lookup is needed to get the value from the kernel,
2621254f889dSBrendon Cahoon       // or previous epilog block. How is does this depends on if the
2622254f889dSBrendon Cahoon       // instruction is scheduled in the previous block.
2623254f889dSBrendon Cahoon       if (!InKernel) {
2624254f889dSBrendon Cahoon         int StageDiffAdj = 0;
2625254f889dSBrendon Cahoon         if (LoopValStage != -1 && StageScheduled > LoopValStage)
2626254f889dSBrendon Cahoon           StageDiffAdj = StageScheduled - LoopValStage;
2627254f889dSBrendon Cahoon         // Use the loop value defined in the kernel, unless the kernel
2628254f889dSBrendon Cahoon         // contains the last definition of the Phi.
2629254f889dSBrendon Cahoon         if (np == 0 && PrevStage == LastStageNum &&
2630254f889dSBrendon Cahoon             (StageScheduled != 0 || LoopValStage != 0) &&
2631254f889dSBrendon Cahoon             VRMap[PrevStage - StageDiffAdj].count(LoopVal))
2632254f889dSBrendon Cahoon           PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
2633254f889dSBrendon Cahoon         // Use the value defined by the Phi. We add one because we switch
2634254f889dSBrendon Cahoon         // from looking at the loop value to the Phi definition.
2635254f889dSBrendon Cahoon         else if (np > 0 && PrevStage == LastStageNum &&
2636254f889dSBrendon Cahoon                  VRMap[PrevStage - np + 1].count(Def))
2637254f889dSBrendon Cahoon           PhiOp2 = VRMap[PrevStage - np + 1][Def];
2638254f889dSBrendon Cahoon         // Use the loop value defined in the kernel.
2639254f889dSBrendon Cahoon         else if ((unsigned)LoopValStage + StageDiffAdj > PrologStage + 1 &&
2640254f889dSBrendon Cahoon                  VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
2641254f889dSBrendon Cahoon           PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
2642254f889dSBrendon Cahoon         // Use the value defined by the Phi, unless we're generating the first
2643254f889dSBrendon Cahoon         // epilog and the Phi refers to a Phi in a different stage.
2644254f889dSBrendon Cahoon         else if (VRMap[PrevStage - np].count(Def) &&
2645254f889dSBrendon Cahoon                  (!LoopDefIsPhi || PrevStage != LastStageNum))
2646254f889dSBrendon Cahoon           PhiOp2 = VRMap[PrevStage - np][Def];
2647254f889dSBrendon Cahoon       }
2648254f889dSBrendon Cahoon 
2649254f889dSBrendon Cahoon       // Check if we can reuse an existing Phi. This occurs when a Phi
2650254f889dSBrendon Cahoon       // references another Phi, and the other Phi is scheduled in an
2651254f889dSBrendon Cahoon       // earlier stage. We can try to reuse an existing Phi up until the last
2652254f889dSBrendon Cahoon       // stage of the current Phi.
265365b6ebccSBrendon Cahoon       if (LoopDefIsPhi && (int)PrologStage >= StageScheduled) {
2654254f889dSBrendon Cahoon         int LVNumStages = Schedule.getStagesForPhi(LoopVal);
2655254f889dSBrendon Cahoon         int StageDiff = (StageScheduled - LoopValStage);
2656254f889dSBrendon Cahoon         LVNumStages -= StageDiff;
2657254f889dSBrendon Cahoon         if (LVNumStages > (int)np) {
2658254f889dSBrendon Cahoon           NewReg = PhiOp2;
2659254f889dSBrendon Cahoon           unsigned ReuseStage = CurStageNum;
2660254f889dSBrendon Cahoon           if (Schedule.isLoopCarried(this, *PhiInst))
2661254f889dSBrendon Cahoon             ReuseStage -= LVNumStages;
2662254f889dSBrendon Cahoon           // Check if the Phi to reuse has been generated yet. If not, then
2663254f889dSBrendon Cahoon           // there is nothing to reuse.
2664254f889dSBrendon Cahoon           if (VRMap[ReuseStage].count(LoopVal)) {
2665254f889dSBrendon Cahoon             NewReg = VRMap[ReuseStage][LoopVal];
2666254f889dSBrendon Cahoon 
2667254f889dSBrendon Cahoon             rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2668254f889dSBrendon Cahoon                                   &*BBI, Def, NewReg);
2669254f889dSBrendon Cahoon             // Update the map with the new Phi name.
2670254f889dSBrendon Cahoon             VRMap[CurStageNum - np][Def] = NewReg;
2671254f889dSBrendon Cahoon             PhiOp2 = NewReg;
2672254f889dSBrendon Cahoon             if (VRMap[LastStageNum - np - 1].count(LoopVal))
2673254f889dSBrendon Cahoon               PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
2674254f889dSBrendon Cahoon 
2675254f889dSBrendon Cahoon             if (IsLast && np == NumPhis - 1)
2676254f889dSBrendon Cahoon               replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2677254f889dSBrendon Cahoon             continue;
2678254f889dSBrendon Cahoon           }
2679*df24da22SKrzysztof Parzyszek         } else if (InKernel && StageDiff > 0 &&
2680254f889dSBrendon Cahoon                    VRMap[CurStageNum - StageDiff - np].count(LoopVal))
2681254f889dSBrendon Cahoon           PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
2682254f889dSBrendon Cahoon       }
2683254f889dSBrendon Cahoon 
2684254f889dSBrendon Cahoon       const TargetRegisterClass *RC = MRI.getRegClass(Def);
2685254f889dSBrendon Cahoon       NewReg = MRI.createVirtualRegister(RC);
2686254f889dSBrendon Cahoon 
2687254f889dSBrendon Cahoon       MachineInstrBuilder NewPhi =
2688254f889dSBrendon Cahoon           BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2689254f889dSBrendon Cahoon                   TII->get(TargetOpcode::PHI), NewReg);
2690254f889dSBrendon Cahoon       NewPhi.addReg(PhiOp1).addMBB(BB1);
2691254f889dSBrendon Cahoon       NewPhi.addReg(PhiOp2).addMBB(BB2);
2692254f889dSBrendon Cahoon       if (np == 0)
2693254f889dSBrendon Cahoon         InstrMap[NewPhi] = &*BBI;
2694254f889dSBrendon Cahoon 
2695254f889dSBrendon Cahoon       // We define the Phis after creating the new pipelined code, so
2696254f889dSBrendon Cahoon       // we need to rename the Phi values in scheduled instructions.
2697254f889dSBrendon Cahoon 
2698254f889dSBrendon Cahoon       unsigned PrevReg = 0;
2699254f889dSBrendon Cahoon       if (InKernel && VRMap[PrevStage - np].count(LoopVal))
2700254f889dSBrendon Cahoon         PrevReg = VRMap[PrevStage - np][LoopVal];
2701254f889dSBrendon Cahoon       rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2702254f889dSBrendon Cahoon                             Def, NewReg, PrevReg);
2703254f889dSBrendon Cahoon       // If the Phi has been scheduled, use the new name for rewriting.
2704254f889dSBrendon Cahoon       if (VRMap[CurStageNum - np].count(Def)) {
2705254f889dSBrendon Cahoon         unsigned R = VRMap[CurStageNum - np][Def];
2706254f889dSBrendon Cahoon         rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2707254f889dSBrendon Cahoon                               R, NewReg);
2708254f889dSBrendon Cahoon       }
2709254f889dSBrendon Cahoon 
2710254f889dSBrendon Cahoon       // Check if we need to rename any uses that occurs after the loop. The
2711254f889dSBrendon Cahoon       // register to replace depends on whether the Phi is scheduled in the
2712254f889dSBrendon Cahoon       // epilog.
2713254f889dSBrendon Cahoon       if (IsLast && np == NumPhis - 1)
2714254f889dSBrendon Cahoon         replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2715254f889dSBrendon Cahoon 
2716254f889dSBrendon Cahoon       // In the kernel, a dependent Phi uses the value from this Phi.
2717254f889dSBrendon Cahoon       if (InKernel)
2718254f889dSBrendon Cahoon         PhiOp2 = NewReg;
2719254f889dSBrendon Cahoon 
2720254f889dSBrendon Cahoon       // Update the map with the new Phi name.
2721254f889dSBrendon Cahoon       VRMap[CurStageNum - np][Def] = NewReg;
2722254f889dSBrendon Cahoon     }
2723254f889dSBrendon Cahoon 
2724254f889dSBrendon Cahoon     while (NumPhis++ < NumStages) {
2725254f889dSBrendon Cahoon       rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, NumPhis,
2726254f889dSBrendon Cahoon                             &*BBI, Def, NewReg, 0);
2727254f889dSBrendon Cahoon     }
2728254f889dSBrendon Cahoon 
2729254f889dSBrendon Cahoon     // Check if we need to rename a Phi that has been eliminated due to
2730254f889dSBrendon Cahoon     // scheduling.
2731254f889dSBrendon Cahoon     if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
2732254f889dSBrendon Cahoon       replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
2733254f889dSBrendon Cahoon   }
2734254f889dSBrendon Cahoon }
2735254f889dSBrendon Cahoon 
2736254f889dSBrendon Cahoon /// Generate Phis for the specified block in the generated pipelined code.
2737254f889dSBrendon Cahoon /// These are new Phis needed because the definition is scheduled after the
2738254f889dSBrendon Cahoon /// use in the pipelened sequence.
2739254f889dSBrendon Cahoon void SwingSchedulerDAG::generatePhis(
2740254f889dSBrendon Cahoon     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2741254f889dSBrendon Cahoon     MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2742254f889dSBrendon Cahoon     InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2743254f889dSBrendon Cahoon     bool IsLast) {
2744254f889dSBrendon Cahoon   // Compute the stage number that contains the initial Phi value, and
2745254f889dSBrendon Cahoon   // the Phi from the previous stage.
2746254f889dSBrendon Cahoon   unsigned PrologStage = 0;
2747254f889dSBrendon Cahoon   unsigned PrevStage = 0;
2748254f889dSBrendon Cahoon   unsigned StageDiff = CurStageNum - LastStageNum;
2749254f889dSBrendon Cahoon   bool InKernel = (StageDiff == 0);
2750254f889dSBrendon Cahoon   if (InKernel) {
2751254f889dSBrendon Cahoon     PrologStage = LastStageNum - 1;
2752254f889dSBrendon Cahoon     PrevStage = CurStageNum;
2753254f889dSBrendon Cahoon   } else {
2754254f889dSBrendon Cahoon     PrologStage = LastStageNum - StageDiff;
2755254f889dSBrendon Cahoon     PrevStage = LastStageNum + StageDiff - 1;
2756254f889dSBrendon Cahoon   }
2757254f889dSBrendon Cahoon 
2758254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
2759254f889dSBrendon Cahoon                                    BBE = BB->instr_end();
2760254f889dSBrendon Cahoon        BBI != BBE; ++BBI) {
2761254f889dSBrendon Cahoon     for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
2762254f889dSBrendon Cahoon       MachineOperand &MO = BBI->getOperand(i);
2763254f889dSBrendon Cahoon       if (!MO.isReg() || !MO.isDef() ||
2764254f889dSBrendon Cahoon           !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2765254f889dSBrendon Cahoon         continue;
2766254f889dSBrendon Cahoon 
2767254f889dSBrendon Cahoon       int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2768254f889dSBrendon Cahoon       assert(StageScheduled != -1 && "Expecting scheduled instruction.");
2769254f889dSBrendon Cahoon       unsigned Def = MO.getReg();
2770254f889dSBrendon Cahoon       unsigned NumPhis = Schedule.getStagesForReg(Def, CurStageNum);
2771254f889dSBrendon Cahoon       // An instruction scheduled in stage 0 and is used after the loop
2772254f889dSBrendon Cahoon       // requires a phi in the epilog for the last definition from either
2773254f889dSBrendon Cahoon       // the kernel or prolog.
2774254f889dSBrendon Cahoon       if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
2775254f889dSBrendon Cahoon           hasUseAfterLoop(Def, BB, MRI))
2776254f889dSBrendon Cahoon         NumPhis = 1;
2777254f889dSBrendon Cahoon       if (!InKernel && (unsigned)StageScheduled > PrologStage)
2778254f889dSBrendon Cahoon         continue;
2779254f889dSBrendon Cahoon 
2780254f889dSBrendon Cahoon       unsigned PhiOp2 = VRMap[PrevStage][Def];
2781254f889dSBrendon Cahoon       if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
2782254f889dSBrendon Cahoon         if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
2783254f889dSBrendon Cahoon           PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
2784254f889dSBrendon Cahoon       // The number of Phis can't exceed the number of prolog stages. The
2785254f889dSBrendon Cahoon       // prolog stage number is zero based.
2786254f889dSBrendon Cahoon       if (NumPhis > PrologStage + 1 - StageScheduled)
2787254f889dSBrendon Cahoon         NumPhis = PrologStage + 1 - StageScheduled;
2788254f889dSBrendon Cahoon       for (unsigned np = 0; np < NumPhis; ++np) {
2789254f889dSBrendon Cahoon         unsigned PhiOp1 = VRMap[PrologStage][Def];
2790254f889dSBrendon Cahoon         if (np <= PrologStage)
2791254f889dSBrendon Cahoon           PhiOp1 = VRMap[PrologStage - np][Def];
2792254f889dSBrendon Cahoon         if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) {
2793254f889dSBrendon Cahoon           if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2794254f889dSBrendon Cahoon             PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2795254f889dSBrendon Cahoon           if (InstOp1->isPHI() && InstOp1->getParent() == NewBB)
2796254f889dSBrendon Cahoon             PhiOp1 = getInitPhiReg(*InstOp1, NewBB);
2797254f889dSBrendon Cahoon         }
2798254f889dSBrendon Cahoon         if (!InKernel)
2799254f889dSBrendon Cahoon           PhiOp2 = VRMap[PrevStage - np][Def];
2800254f889dSBrendon Cahoon 
2801254f889dSBrendon Cahoon         const TargetRegisterClass *RC = MRI.getRegClass(Def);
2802254f889dSBrendon Cahoon         unsigned NewReg = MRI.createVirtualRegister(RC);
2803254f889dSBrendon Cahoon 
2804254f889dSBrendon Cahoon         MachineInstrBuilder NewPhi =
2805254f889dSBrendon Cahoon             BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2806254f889dSBrendon Cahoon                     TII->get(TargetOpcode::PHI), NewReg);
2807254f889dSBrendon Cahoon         NewPhi.addReg(PhiOp1).addMBB(BB1);
2808254f889dSBrendon Cahoon         NewPhi.addReg(PhiOp2).addMBB(BB2);
2809254f889dSBrendon Cahoon         if (np == 0)
2810254f889dSBrendon Cahoon           InstrMap[NewPhi] = &*BBI;
2811254f889dSBrendon Cahoon 
2812254f889dSBrendon Cahoon         // Rewrite uses and update the map. The actions depend upon whether
2813254f889dSBrendon Cahoon         // we generating code for the kernel or epilog blocks.
2814254f889dSBrendon Cahoon         if (InKernel) {
2815254f889dSBrendon Cahoon           rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2816254f889dSBrendon Cahoon                                 &*BBI, PhiOp1, NewReg);
2817254f889dSBrendon Cahoon           rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2818254f889dSBrendon Cahoon                                 &*BBI, PhiOp2, NewReg);
2819254f889dSBrendon Cahoon 
2820254f889dSBrendon Cahoon           PhiOp2 = NewReg;
2821254f889dSBrendon Cahoon           VRMap[PrevStage - np - 1][Def] = NewReg;
2822254f889dSBrendon Cahoon         } else {
2823254f889dSBrendon Cahoon           VRMap[CurStageNum - np][Def] = NewReg;
2824254f889dSBrendon Cahoon           if (np == NumPhis - 1)
2825254f889dSBrendon Cahoon             rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2826254f889dSBrendon Cahoon                                   &*BBI, Def, NewReg);
2827254f889dSBrendon Cahoon         }
2828254f889dSBrendon Cahoon         if (IsLast && np == NumPhis - 1)
2829254f889dSBrendon Cahoon           replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2830254f889dSBrendon Cahoon       }
2831254f889dSBrendon Cahoon     }
2832254f889dSBrendon Cahoon   }
2833254f889dSBrendon Cahoon }
2834254f889dSBrendon Cahoon 
2835254f889dSBrendon Cahoon /// Remove instructions that generate values with no uses.
2836254f889dSBrendon Cahoon /// Typically, these are induction variable operations that generate values
2837254f889dSBrendon Cahoon /// used in the loop itself.  A dead instruction has a definition with
2838254f889dSBrendon Cahoon /// no uses, or uses that occur in the original loop only.
2839254f889dSBrendon Cahoon void SwingSchedulerDAG::removeDeadInstructions(MachineBasicBlock *KernelBB,
2840254f889dSBrendon Cahoon                                                MBBVectorTy &EpilogBBs) {
2841254f889dSBrendon Cahoon   // For each epilog block, check that the value defined by each instruction
2842254f889dSBrendon Cahoon   // is used.  If not, delete it.
2843254f889dSBrendon Cahoon   for (MBBVectorTy::reverse_iterator MBB = EpilogBBs.rbegin(),
2844254f889dSBrendon Cahoon                                      MBE = EpilogBBs.rend();
2845254f889dSBrendon Cahoon        MBB != MBE; ++MBB)
2846254f889dSBrendon Cahoon     for (MachineBasicBlock::reverse_instr_iterator MI = (*MBB)->instr_rbegin(),
2847254f889dSBrendon Cahoon                                                    ME = (*MBB)->instr_rend();
2848254f889dSBrendon Cahoon          MI != ME;) {
2849254f889dSBrendon Cahoon       // From DeadMachineInstructionElem. Don't delete inline assembly.
2850254f889dSBrendon Cahoon       if (MI->isInlineAsm()) {
2851254f889dSBrendon Cahoon         ++MI;
2852254f889dSBrendon Cahoon         continue;
2853254f889dSBrendon Cahoon       }
2854254f889dSBrendon Cahoon       bool SawStore = false;
2855254f889dSBrendon Cahoon       // Check if it's safe to remove the instruction due to side effects.
2856254f889dSBrendon Cahoon       // We can, and want to, remove Phis here.
2857254f889dSBrendon Cahoon       if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
2858254f889dSBrendon Cahoon         ++MI;
2859254f889dSBrendon Cahoon         continue;
2860254f889dSBrendon Cahoon       }
2861254f889dSBrendon Cahoon       bool used = true;
2862254f889dSBrendon Cahoon       for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
2863254f889dSBrendon Cahoon                                       MOE = MI->operands_end();
2864254f889dSBrendon Cahoon            MOI != MOE; ++MOI) {
2865254f889dSBrendon Cahoon         if (!MOI->isReg() || !MOI->isDef())
2866254f889dSBrendon Cahoon           continue;
2867254f889dSBrendon Cahoon         unsigned reg = MOI->getReg();
2868254f889dSBrendon Cahoon         unsigned realUses = 0;
2869254f889dSBrendon Cahoon         for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(reg),
2870254f889dSBrendon Cahoon                                                EI = MRI.use_end();
2871254f889dSBrendon Cahoon              UI != EI; ++UI) {
2872254f889dSBrendon Cahoon           // Check if there are any uses that occur only in the original
2873254f889dSBrendon Cahoon           // loop.  If so, that's not a real use.
2874254f889dSBrendon Cahoon           if (UI->getParent()->getParent() != BB) {
2875254f889dSBrendon Cahoon             realUses++;
2876254f889dSBrendon Cahoon             used = true;
2877254f889dSBrendon Cahoon             break;
2878254f889dSBrendon Cahoon           }
2879254f889dSBrendon Cahoon         }
2880254f889dSBrendon Cahoon         if (realUses > 0)
2881254f889dSBrendon Cahoon           break;
2882254f889dSBrendon Cahoon         used = false;
2883254f889dSBrendon Cahoon       }
2884254f889dSBrendon Cahoon       if (!used) {
28855c001c36SDuncan P. N. Exon Smith         MI++->eraseFromParent();
2886254f889dSBrendon Cahoon         continue;
2887254f889dSBrendon Cahoon       }
2888254f889dSBrendon Cahoon       ++MI;
2889254f889dSBrendon Cahoon     }
2890254f889dSBrendon Cahoon   // In the kernel block, check if we can remove a Phi that generates a value
2891254f889dSBrendon Cahoon   // used in an instruction removed in the epilog block.
2892254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(),
2893254f889dSBrendon Cahoon                                    BBE = KernelBB->getFirstNonPHI();
2894254f889dSBrendon Cahoon        BBI != BBE;) {
2895254f889dSBrendon Cahoon     MachineInstr *MI = &*BBI;
2896254f889dSBrendon Cahoon     ++BBI;
2897254f889dSBrendon Cahoon     unsigned reg = MI->getOperand(0).getReg();
2898254f889dSBrendon Cahoon     if (MRI.use_begin(reg) == MRI.use_end()) {
2899254f889dSBrendon Cahoon       MI->eraseFromParent();
2900254f889dSBrendon Cahoon     }
2901254f889dSBrendon Cahoon   }
2902254f889dSBrendon Cahoon }
2903254f889dSBrendon Cahoon 
2904254f889dSBrendon Cahoon /// For loop carried definitions, we split the lifetime of a virtual register
2905254f889dSBrendon Cahoon /// that has uses past the definition in the next iteration. A copy with a new
2906254f889dSBrendon Cahoon /// virtual register is inserted before the definition, which helps with
2907254f889dSBrendon Cahoon /// generating a better register assignment.
2908254f889dSBrendon Cahoon ///
2909254f889dSBrendon Cahoon ///   v1 = phi(a, v2)     v1 = phi(a, v2)
2910254f889dSBrendon Cahoon ///   v2 = phi(b, v3)     v2 = phi(b, v3)
2911254f889dSBrendon Cahoon ///   v3 = ..             v4 = copy v1
2912254f889dSBrendon Cahoon ///   .. = V1             v3 = ..
2913254f889dSBrendon Cahoon ///                       .. = v4
2914254f889dSBrendon Cahoon void SwingSchedulerDAG::splitLifetimes(MachineBasicBlock *KernelBB,
2915254f889dSBrendon Cahoon                                        MBBVectorTy &EpilogBBs,
2916254f889dSBrendon Cahoon                                        SMSchedule &Schedule) {
2917254f889dSBrendon Cahoon   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2918254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(),
2919254f889dSBrendon Cahoon                                    BBF = KernelBB->getFirstNonPHI();
2920254f889dSBrendon Cahoon        BBI != BBF; ++BBI) {
2921254f889dSBrendon Cahoon     unsigned Def = BBI->getOperand(0).getReg();
2922254f889dSBrendon Cahoon     // Check for any Phi definition that used as an operand of another Phi
2923254f889dSBrendon Cahoon     // in the same block.
2924254f889dSBrendon Cahoon     for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
2925254f889dSBrendon Cahoon                                                  E = MRI.use_instr_end();
2926254f889dSBrendon Cahoon          I != E; ++I) {
2927254f889dSBrendon Cahoon       if (I->isPHI() && I->getParent() == KernelBB) {
2928254f889dSBrendon Cahoon         // Get the loop carried definition.
2929254f889dSBrendon Cahoon         unsigned LCDef = getLoopPhiReg(*BBI, KernelBB);
2930254f889dSBrendon Cahoon         if (!LCDef)
2931254f889dSBrendon Cahoon           continue;
2932254f889dSBrendon Cahoon         MachineInstr *MI = MRI.getVRegDef(LCDef);
2933254f889dSBrendon Cahoon         if (!MI || MI->getParent() != KernelBB || MI->isPHI())
2934254f889dSBrendon Cahoon           continue;
2935254f889dSBrendon Cahoon         // Search through the rest of the block looking for uses of the Phi
2936254f889dSBrendon Cahoon         // definition. If one occurs, then split the lifetime.
2937254f889dSBrendon Cahoon         unsigned SplitReg = 0;
2938254f889dSBrendon Cahoon         for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
2939254f889dSBrendon Cahoon                                     KernelBB->instr_end()))
2940254f889dSBrendon Cahoon           if (BBJ.readsRegister(Def)) {
2941254f889dSBrendon Cahoon             // We split the lifetime when we find the first use.
2942254f889dSBrendon Cahoon             if (SplitReg == 0) {
2943254f889dSBrendon Cahoon               SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
2944254f889dSBrendon Cahoon               BuildMI(*KernelBB, MI, MI->getDebugLoc(),
2945254f889dSBrendon Cahoon                       TII->get(TargetOpcode::COPY), SplitReg)
2946254f889dSBrendon Cahoon                   .addReg(Def);
2947254f889dSBrendon Cahoon             }
2948254f889dSBrendon Cahoon             BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
2949254f889dSBrendon Cahoon           }
2950254f889dSBrendon Cahoon         if (!SplitReg)
2951254f889dSBrendon Cahoon           continue;
2952254f889dSBrendon Cahoon         // Search through each of the epilog blocks for any uses to be renamed.
2953254f889dSBrendon Cahoon         for (auto &Epilog : EpilogBBs)
2954254f889dSBrendon Cahoon           for (auto &I : *Epilog)
2955254f889dSBrendon Cahoon             if (I.readsRegister(Def))
2956254f889dSBrendon Cahoon               I.substituteRegister(Def, SplitReg, 0, *TRI);
2957254f889dSBrendon Cahoon         break;
2958254f889dSBrendon Cahoon       }
2959254f889dSBrendon Cahoon     }
2960254f889dSBrendon Cahoon   }
2961254f889dSBrendon Cahoon }
2962254f889dSBrendon Cahoon 
2963254f889dSBrendon Cahoon /// Remove the incoming block from the Phis in a basic block.
2964254f889dSBrendon Cahoon static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
2965254f889dSBrendon Cahoon   for (MachineInstr &MI : *BB) {
2966254f889dSBrendon Cahoon     if (!MI.isPHI())
2967254f889dSBrendon Cahoon       break;
2968254f889dSBrendon Cahoon     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
2969254f889dSBrendon Cahoon       if (MI.getOperand(i + 1).getMBB() == Incoming) {
2970254f889dSBrendon Cahoon         MI.RemoveOperand(i + 1);
2971254f889dSBrendon Cahoon         MI.RemoveOperand(i);
2972254f889dSBrendon Cahoon         break;
2973254f889dSBrendon Cahoon       }
2974254f889dSBrendon Cahoon   }
2975254f889dSBrendon Cahoon }
2976254f889dSBrendon Cahoon 
2977254f889dSBrendon Cahoon /// Create branches from each prolog basic block to the appropriate epilog
2978254f889dSBrendon Cahoon /// block.  These edges are needed if the loop ends before reaching the
2979254f889dSBrendon Cahoon /// kernel.
2980254f889dSBrendon Cahoon void SwingSchedulerDAG::addBranches(MBBVectorTy &PrologBBs,
2981254f889dSBrendon Cahoon                                     MachineBasicBlock *KernelBB,
2982254f889dSBrendon Cahoon                                     MBBVectorTy &EpilogBBs,
2983254f889dSBrendon Cahoon                                     SMSchedule &Schedule, ValueMapTy *VRMap) {
2984254f889dSBrendon Cahoon   assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
2985254f889dSBrendon Cahoon   MachineInstr *IndVar = Pass.LI.LoopInductionVar;
2986254f889dSBrendon Cahoon   MachineInstr *Cmp = Pass.LI.LoopCompare;
2987254f889dSBrendon Cahoon   MachineBasicBlock *LastPro = KernelBB;
2988254f889dSBrendon Cahoon   MachineBasicBlock *LastEpi = KernelBB;
2989254f889dSBrendon Cahoon 
2990254f889dSBrendon Cahoon   // Start from the blocks connected to the kernel and work "out"
2991254f889dSBrendon Cahoon   // to the first prolog and the last epilog blocks.
2992254f889dSBrendon Cahoon   SmallVector<MachineInstr *, 4> PrevInsts;
2993254f889dSBrendon Cahoon   unsigned MaxIter = PrologBBs.size() - 1;
2994254f889dSBrendon Cahoon   unsigned LC = UINT_MAX;
2995254f889dSBrendon Cahoon   unsigned LCMin = UINT_MAX;
2996254f889dSBrendon Cahoon   for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
2997254f889dSBrendon Cahoon     // Add branches to the prolog that go to the corresponding
2998254f889dSBrendon Cahoon     // epilog, and the fall-thru prolog/kernel block.
2999254f889dSBrendon Cahoon     MachineBasicBlock *Prolog = PrologBBs[j];
3000254f889dSBrendon Cahoon     MachineBasicBlock *Epilog = EpilogBBs[i];
3001254f889dSBrendon Cahoon     // We've executed one iteration, so decrement the loop count and check for
3002254f889dSBrendon Cahoon     // the loop end.
3003254f889dSBrendon Cahoon     SmallVector<MachineOperand, 4> Cond;
3004254f889dSBrendon Cahoon     // Check if the LOOP0 has already been removed. If so, then there is no need
3005254f889dSBrendon Cahoon     // to reduce the trip count.
3006254f889dSBrendon Cahoon     if (LC != 0)
30078fb181caSKrzysztof Parzyszek       LC = TII->reduceLoopCount(*Prolog, IndVar, *Cmp, Cond, PrevInsts, j,
3008254f889dSBrendon Cahoon                                 MaxIter);
3009254f889dSBrendon Cahoon 
3010254f889dSBrendon Cahoon     // Record the value of the first trip count, which is used to determine if
3011254f889dSBrendon Cahoon     // branches and blocks can be removed for constant trip counts.
3012254f889dSBrendon Cahoon     if (LCMin == UINT_MAX)
3013254f889dSBrendon Cahoon       LCMin = LC;
3014254f889dSBrendon Cahoon 
3015254f889dSBrendon Cahoon     unsigned numAdded = 0;
3016254f889dSBrendon Cahoon     if (TargetRegisterInfo::isVirtualRegister(LC)) {
3017254f889dSBrendon Cahoon       Prolog->addSuccessor(Epilog);
3018e8e0f5caSMatt Arsenault       numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
3019254f889dSBrendon Cahoon     } else if (j >= LCMin) {
3020254f889dSBrendon Cahoon       Prolog->addSuccessor(Epilog);
3021254f889dSBrendon Cahoon       Prolog->removeSuccessor(LastPro);
3022254f889dSBrendon Cahoon       LastEpi->removeSuccessor(Epilog);
3023e8e0f5caSMatt Arsenault       numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
3024254f889dSBrendon Cahoon       removePhis(Epilog, LastEpi);
3025254f889dSBrendon Cahoon       // Remove the blocks that are no longer referenced.
3026254f889dSBrendon Cahoon       if (LastPro != LastEpi) {
3027254f889dSBrendon Cahoon         LastEpi->clear();
3028254f889dSBrendon Cahoon         LastEpi->eraseFromParent();
3029254f889dSBrendon Cahoon       }
3030254f889dSBrendon Cahoon       LastPro->clear();
3031254f889dSBrendon Cahoon       LastPro->eraseFromParent();
3032254f889dSBrendon Cahoon     } else {
3033e8e0f5caSMatt Arsenault       numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
3034254f889dSBrendon Cahoon       removePhis(Epilog, Prolog);
3035254f889dSBrendon Cahoon     }
3036254f889dSBrendon Cahoon     LastPro = Prolog;
3037254f889dSBrendon Cahoon     LastEpi = Epilog;
3038254f889dSBrendon Cahoon     for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
3039254f889dSBrendon Cahoon                                                    E = Prolog->instr_rend();
3040254f889dSBrendon Cahoon          I != E && numAdded > 0; ++I, --numAdded)
3041254f889dSBrendon Cahoon       updateInstruction(&*I, false, j, 0, Schedule, VRMap);
3042254f889dSBrendon Cahoon   }
3043254f889dSBrendon Cahoon }
3044254f889dSBrendon Cahoon 
3045254f889dSBrendon Cahoon /// Return true if we can compute the amount the instruction changes
3046254f889dSBrendon Cahoon /// during each iteration. Set Delta to the amount of the change.
3047254f889dSBrendon Cahoon bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
3048254f889dSBrendon Cahoon   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3049254f889dSBrendon Cahoon   unsigned BaseReg;
3050254f889dSBrendon Cahoon   int64_t Offset;
3051254f889dSBrendon Cahoon   if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI))
3052254f889dSBrendon Cahoon     return false;
3053254f889dSBrendon Cahoon 
3054254f889dSBrendon Cahoon   MachineRegisterInfo &MRI = MF.getRegInfo();
3055254f889dSBrendon Cahoon   // Check if there is a Phi. If so, get the definition in the loop.
3056254f889dSBrendon Cahoon   MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
3057254f889dSBrendon Cahoon   if (BaseDef && BaseDef->isPHI()) {
3058254f889dSBrendon Cahoon     BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
3059254f889dSBrendon Cahoon     BaseDef = MRI.getVRegDef(BaseReg);
3060254f889dSBrendon Cahoon   }
3061254f889dSBrendon Cahoon   if (!BaseDef)
3062254f889dSBrendon Cahoon     return false;
3063254f889dSBrendon Cahoon 
3064254f889dSBrendon Cahoon   int D = 0;
30658fb181caSKrzysztof Parzyszek   if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
3066254f889dSBrendon Cahoon     return false;
3067254f889dSBrendon Cahoon 
3068254f889dSBrendon Cahoon   Delta = D;
3069254f889dSBrendon Cahoon   return true;
3070254f889dSBrendon Cahoon }
3071254f889dSBrendon Cahoon 
3072254f889dSBrendon Cahoon /// Update the memory operand with a new offset when the pipeliner
3073cf56e92cSJustin Lebar /// generates a new copy of the instruction that refers to a
3074254f889dSBrendon Cahoon /// different memory location.
3075254f889dSBrendon Cahoon void SwingSchedulerDAG::updateMemOperands(MachineInstr &NewMI,
3076254f889dSBrendon Cahoon                                           MachineInstr &OldMI, unsigned Num) {
3077254f889dSBrendon Cahoon   if (Num == 0)
3078254f889dSBrendon Cahoon     return;
3079254f889dSBrendon Cahoon   // If the instruction has memory operands, then adjust the offset
3080254f889dSBrendon Cahoon   // when the instruction appears in different stages.
3081254f889dSBrendon Cahoon   unsigned NumRefs = NewMI.memoperands_end() - NewMI.memoperands_begin();
3082254f889dSBrendon Cahoon   if (NumRefs == 0)
3083254f889dSBrendon Cahoon     return;
3084254f889dSBrendon Cahoon   MachineInstr::mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NumRefs);
3085254f889dSBrendon Cahoon   unsigned Refs = 0;
30860a33a7aeSJustin Lebar   for (MachineMemOperand *MMO : NewMI.memoperands()) {
3087adbf09e8SJustin Lebar     if (MMO->isVolatile() || (MMO->isInvariant() && MMO->isDereferenceable()) ||
3088adbf09e8SJustin Lebar         (!MMO->getValue())) {
30890a33a7aeSJustin Lebar       NewMemRefs[Refs++] = MMO;
3090254f889dSBrendon Cahoon       continue;
3091254f889dSBrendon Cahoon     }
3092254f889dSBrendon Cahoon     unsigned Delta;
3093254f889dSBrendon Cahoon     if (computeDelta(OldMI, Delta)) {
3094254f889dSBrendon Cahoon       int64_t AdjOffset = Delta * Num;
3095254f889dSBrendon Cahoon       NewMemRefs[Refs++] =
30960a33a7aeSJustin Lebar           MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize());
3097254f889dSBrendon Cahoon     } else
30980a33a7aeSJustin Lebar       NewMemRefs[Refs++] = MF.getMachineMemOperand(MMO, 0, UINT64_MAX);
3099254f889dSBrendon Cahoon   }
3100254f889dSBrendon Cahoon   NewMI.setMemRefs(NewMemRefs, NewMemRefs + NumRefs);
3101254f889dSBrendon Cahoon }
3102254f889dSBrendon Cahoon 
3103254f889dSBrendon Cahoon /// Clone the instruction for the new pipelined loop and update the
3104254f889dSBrendon Cahoon /// memory operands, if needed.
3105254f889dSBrendon Cahoon MachineInstr *SwingSchedulerDAG::cloneInstr(MachineInstr *OldMI,
3106254f889dSBrendon Cahoon                                             unsigned CurStageNum,
3107254f889dSBrendon Cahoon                                             unsigned InstStageNum) {
3108254f889dSBrendon Cahoon   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
3109254f889dSBrendon Cahoon   // Check for tied operands in inline asm instructions. This should be handled
3110254f889dSBrendon Cahoon   // elsewhere, but I'm not sure of the best solution.
3111254f889dSBrendon Cahoon   if (OldMI->isInlineAsm())
3112254f889dSBrendon Cahoon     for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
3113254f889dSBrendon Cahoon       const auto &MO = OldMI->getOperand(i);
3114254f889dSBrendon Cahoon       if (MO.isReg() && MO.isUse())
3115254f889dSBrendon Cahoon         break;
3116254f889dSBrendon Cahoon       unsigned UseIdx;
3117254f889dSBrendon Cahoon       if (OldMI->isRegTiedToUseOperand(i, &UseIdx))
3118254f889dSBrendon Cahoon         NewMI->tieOperands(i, UseIdx);
3119254f889dSBrendon Cahoon     }
3120254f889dSBrendon Cahoon   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
3121254f889dSBrendon Cahoon   return NewMI;
3122254f889dSBrendon Cahoon }
3123254f889dSBrendon Cahoon 
3124254f889dSBrendon Cahoon /// Clone the instruction for the new pipelined loop. If needed, this
3125254f889dSBrendon Cahoon /// function updates the instruction using the values saved in the
3126254f889dSBrendon Cahoon /// InstrChanges structure.
3127254f889dSBrendon Cahoon MachineInstr *SwingSchedulerDAG::cloneAndChangeInstr(MachineInstr *OldMI,
3128254f889dSBrendon Cahoon                                                      unsigned CurStageNum,
3129254f889dSBrendon Cahoon                                                      unsigned InstStageNum,
3130254f889dSBrendon Cahoon                                                      SMSchedule &Schedule) {
3131254f889dSBrendon Cahoon   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
3132254f889dSBrendon Cahoon   DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3133254f889dSBrendon Cahoon       InstrChanges.find(getSUnit(OldMI));
3134254f889dSBrendon Cahoon   if (It != InstrChanges.end()) {
3135254f889dSBrendon Cahoon     std::pair<unsigned, int64_t> RegAndOffset = It->second;
3136254f889dSBrendon Cahoon     unsigned BasePos, OffsetPos;
31378fb181caSKrzysztof Parzyszek     if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
3138254f889dSBrendon Cahoon       return nullptr;
3139254f889dSBrendon Cahoon     int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
3140254f889dSBrendon Cahoon     MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
3141254f889dSBrendon Cahoon     if (Schedule.stageScheduled(getSUnit(LoopDef)) > (signed)InstStageNum)
3142254f889dSBrendon Cahoon       NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
3143254f889dSBrendon Cahoon     NewMI->getOperand(OffsetPos).setImm(NewOffset);
3144254f889dSBrendon Cahoon   }
3145254f889dSBrendon Cahoon   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
3146254f889dSBrendon Cahoon   return NewMI;
3147254f889dSBrendon Cahoon }
3148254f889dSBrendon Cahoon 
3149254f889dSBrendon Cahoon /// Update the machine instruction with new virtual registers.  This
3150254f889dSBrendon Cahoon /// function may change the defintions and/or uses.
3151254f889dSBrendon Cahoon void SwingSchedulerDAG::updateInstruction(MachineInstr *NewMI, bool LastDef,
3152254f889dSBrendon Cahoon                                           unsigned CurStageNum,
3153254f889dSBrendon Cahoon                                           unsigned InstrStageNum,
3154254f889dSBrendon Cahoon                                           SMSchedule &Schedule,
3155254f889dSBrendon Cahoon                                           ValueMapTy *VRMap) {
3156254f889dSBrendon Cahoon   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
3157254f889dSBrendon Cahoon     MachineOperand &MO = NewMI->getOperand(i);
3158254f889dSBrendon Cahoon     if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
3159254f889dSBrendon Cahoon       continue;
3160254f889dSBrendon Cahoon     unsigned reg = MO.getReg();
3161254f889dSBrendon Cahoon     if (MO.isDef()) {
3162254f889dSBrendon Cahoon       // Create a new virtual register for the definition.
3163254f889dSBrendon Cahoon       const TargetRegisterClass *RC = MRI.getRegClass(reg);
3164254f889dSBrendon Cahoon       unsigned NewReg = MRI.createVirtualRegister(RC);
3165254f889dSBrendon Cahoon       MO.setReg(NewReg);
3166254f889dSBrendon Cahoon       VRMap[CurStageNum][reg] = NewReg;
3167254f889dSBrendon Cahoon       if (LastDef)
3168254f889dSBrendon Cahoon         replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
3169254f889dSBrendon Cahoon     } else if (MO.isUse()) {
3170254f889dSBrendon Cahoon       MachineInstr *Def = MRI.getVRegDef(reg);
3171254f889dSBrendon Cahoon       // Compute the stage that contains the last definition for instruction.
3172254f889dSBrendon Cahoon       int DefStageNum = Schedule.stageScheduled(getSUnit(Def));
3173254f889dSBrendon Cahoon       unsigned StageNum = CurStageNum;
3174254f889dSBrendon Cahoon       if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
3175254f889dSBrendon Cahoon         // Compute the difference in stages between the defintion and the use.
3176254f889dSBrendon Cahoon         unsigned StageDiff = (InstrStageNum - DefStageNum);
3177254f889dSBrendon Cahoon         // Make an adjustment to get the last definition.
3178254f889dSBrendon Cahoon         StageNum -= StageDiff;
3179254f889dSBrendon Cahoon       }
3180254f889dSBrendon Cahoon       if (VRMap[StageNum].count(reg))
3181254f889dSBrendon Cahoon         MO.setReg(VRMap[StageNum][reg]);
3182254f889dSBrendon Cahoon     }
3183254f889dSBrendon Cahoon   }
3184254f889dSBrendon Cahoon }
3185254f889dSBrendon Cahoon 
3186254f889dSBrendon Cahoon /// Return the instruction in the loop that defines the register.
3187254f889dSBrendon Cahoon /// If the definition is a Phi, then follow the Phi operand to
3188254f889dSBrendon Cahoon /// the instruction in the loop.
3189254f889dSBrendon Cahoon MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) {
3190254f889dSBrendon Cahoon   SmallPtrSet<MachineInstr *, 8> Visited;
3191254f889dSBrendon Cahoon   MachineInstr *Def = MRI.getVRegDef(Reg);
3192254f889dSBrendon Cahoon   while (Def->isPHI()) {
3193254f889dSBrendon Cahoon     if (!Visited.insert(Def).second)
3194254f889dSBrendon Cahoon       break;
3195254f889dSBrendon Cahoon     for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
3196254f889dSBrendon Cahoon       if (Def->getOperand(i + 1).getMBB() == BB) {
3197254f889dSBrendon Cahoon         Def = MRI.getVRegDef(Def->getOperand(i).getReg());
3198254f889dSBrendon Cahoon         break;
3199254f889dSBrendon Cahoon       }
3200254f889dSBrendon Cahoon   }
3201254f889dSBrendon Cahoon   return Def;
3202254f889dSBrendon Cahoon }
3203254f889dSBrendon Cahoon 
3204254f889dSBrendon Cahoon /// Return the new name for the value from the previous stage.
3205254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::getPrevMapVal(unsigned StageNum, unsigned PhiStage,
3206254f889dSBrendon Cahoon                                           unsigned LoopVal, unsigned LoopStage,
3207254f889dSBrendon Cahoon                                           ValueMapTy *VRMap,
3208254f889dSBrendon Cahoon                                           MachineBasicBlock *BB) {
3209254f889dSBrendon Cahoon   unsigned PrevVal = 0;
3210254f889dSBrendon Cahoon   if (StageNum > PhiStage) {
3211254f889dSBrendon Cahoon     MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
3212254f889dSBrendon Cahoon     if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
3213254f889dSBrendon Cahoon       // The name is defined in the previous stage.
3214254f889dSBrendon Cahoon       PrevVal = VRMap[StageNum - 1][LoopVal];
3215254f889dSBrendon Cahoon     else if (VRMap[StageNum].count(LoopVal))
3216254f889dSBrendon Cahoon       // The previous name is defined in the current stage when the instruction
3217254f889dSBrendon Cahoon       // order is swapped.
3218254f889dSBrendon Cahoon       PrevVal = VRMap[StageNum][LoopVal];
3219*df24da22SKrzysztof Parzyszek     else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
3220254f889dSBrendon Cahoon       // The loop value hasn't yet been scheduled.
3221254f889dSBrendon Cahoon       PrevVal = LoopVal;
3222254f889dSBrendon Cahoon     else if (StageNum == PhiStage + 1)
3223254f889dSBrendon Cahoon       // The loop value is another phi, which has not been scheduled.
3224254f889dSBrendon Cahoon       PrevVal = getInitPhiReg(*LoopInst, BB);
3225254f889dSBrendon Cahoon     else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
3226254f889dSBrendon Cahoon       // The loop value is another phi, which has been scheduled.
3227254f889dSBrendon Cahoon       PrevVal =
3228254f889dSBrendon Cahoon           getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
3229254f889dSBrendon Cahoon                         LoopStage, VRMap, BB);
3230254f889dSBrendon Cahoon   }
3231254f889dSBrendon Cahoon   return PrevVal;
3232254f889dSBrendon Cahoon }
3233254f889dSBrendon Cahoon 
3234254f889dSBrendon Cahoon /// Rewrite the Phi values in the specified block to use the mappings
3235254f889dSBrendon Cahoon /// from the initial operand. Once the Phi is scheduled, we switch
3236254f889dSBrendon Cahoon /// to using the loop value instead of the Phi value, so those names
3237254f889dSBrendon Cahoon /// do not need to be rewritten.
3238254f889dSBrendon Cahoon void SwingSchedulerDAG::rewritePhiValues(MachineBasicBlock *NewBB,
3239254f889dSBrendon Cahoon                                          unsigned StageNum,
3240254f889dSBrendon Cahoon                                          SMSchedule &Schedule,
3241254f889dSBrendon Cahoon                                          ValueMapTy *VRMap,
3242254f889dSBrendon Cahoon                                          InstrMapTy &InstrMap) {
3243254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
3244254f889dSBrendon Cahoon                                    BBE = BB->getFirstNonPHI();
3245254f889dSBrendon Cahoon        BBI != BBE; ++BBI) {
3246254f889dSBrendon Cahoon     unsigned InitVal = 0;
3247254f889dSBrendon Cahoon     unsigned LoopVal = 0;
3248254f889dSBrendon Cahoon     getPhiRegs(*BBI, BB, InitVal, LoopVal);
3249254f889dSBrendon Cahoon     unsigned PhiDef = BBI->getOperand(0).getReg();
3250254f889dSBrendon Cahoon 
3251254f889dSBrendon Cahoon     unsigned PhiStage =
3252254f889dSBrendon Cahoon         (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(PhiDef)));
3253254f889dSBrendon Cahoon     unsigned LoopStage =
3254254f889dSBrendon Cahoon         (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
3255254f889dSBrendon Cahoon     unsigned NumPhis = Schedule.getStagesForPhi(PhiDef);
3256254f889dSBrendon Cahoon     if (NumPhis > StageNum)
3257254f889dSBrendon Cahoon       NumPhis = StageNum;
3258254f889dSBrendon Cahoon     for (unsigned np = 0; np <= NumPhis; ++np) {
3259254f889dSBrendon Cahoon       unsigned NewVal =
3260254f889dSBrendon Cahoon           getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
3261254f889dSBrendon Cahoon       if (!NewVal)
3262254f889dSBrendon Cahoon         NewVal = InitVal;
3263254f889dSBrendon Cahoon       rewriteScheduledInstr(NewBB, Schedule, InstrMap, StageNum - np, np, &*BBI,
3264254f889dSBrendon Cahoon                             PhiDef, NewVal);
3265254f889dSBrendon Cahoon     }
3266254f889dSBrendon Cahoon   }
3267254f889dSBrendon Cahoon }
3268254f889dSBrendon Cahoon 
3269254f889dSBrendon Cahoon /// Rewrite a previously scheduled instruction to use the register value
3270254f889dSBrendon Cahoon /// from the new instruction. Make sure the instruction occurs in the
3271254f889dSBrendon Cahoon /// basic block, and we don't change the uses in the new instruction.
3272254f889dSBrendon Cahoon void SwingSchedulerDAG::rewriteScheduledInstr(
3273254f889dSBrendon Cahoon     MachineBasicBlock *BB, SMSchedule &Schedule, InstrMapTy &InstrMap,
3274254f889dSBrendon Cahoon     unsigned CurStageNum, unsigned PhiNum, MachineInstr *Phi, unsigned OldReg,
3275254f889dSBrendon Cahoon     unsigned NewReg, unsigned PrevReg) {
3276254f889dSBrendon Cahoon   bool InProlog = (CurStageNum < Schedule.getMaxStageCount());
3277254f889dSBrendon Cahoon   int StagePhi = Schedule.stageScheduled(getSUnit(Phi)) + PhiNum;
3278254f889dSBrendon Cahoon   // Rewrite uses that have been scheduled already to use the new
3279254f889dSBrendon Cahoon   // Phi register.
3280254f889dSBrendon Cahoon   for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(OldReg),
3281254f889dSBrendon Cahoon                                          EI = MRI.use_end();
3282254f889dSBrendon Cahoon        UI != EI;) {
3283254f889dSBrendon Cahoon     MachineOperand &UseOp = *UI;
3284254f889dSBrendon Cahoon     MachineInstr *UseMI = UseOp.getParent();
3285254f889dSBrendon Cahoon     ++UI;
3286254f889dSBrendon Cahoon     if (UseMI->getParent() != BB)
3287254f889dSBrendon Cahoon       continue;
3288254f889dSBrendon Cahoon     if (UseMI->isPHI()) {
3289254f889dSBrendon Cahoon       if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
3290254f889dSBrendon Cahoon         continue;
3291254f889dSBrendon Cahoon       if (getLoopPhiReg(*UseMI, BB) != OldReg)
3292254f889dSBrendon Cahoon         continue;
3293254f889dSBrendon Cahoon     }
3294254f889dSBrendon Cahoon     InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
3295254f889dSBrendon Cahoon     assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
3296254f889dSBrendon Cahoon     SUnit *OrigMISU = getSUnit(OrigInstr->second);
3297254f889dSBrendon Cahoon     int StageSched = Schedule.stageScheduled(OrigMISU);
3298254f889dSBrendon Cahoon     int CycleSched = Schedule.cycleScheduled(OrigMISU);
3299254f889dSBrendon Cahoon     unsigned ReplaceReg = 0;
3300254f889dSBrendon Cahoon     // This is the stage for the scheduled instruction.
3301254f889dSBrendon Cahoon     if (StagePhi == StageSched && Phi->isPHI()) {
3302254f889dSBrendon Cahoon       int CyclePhi = Schedule.cycleScheduled(getSUnit(Phi));
3303254f889dSBrendon Cahoon       if (PrevReg && InProlog)
3304254f889dSBrendon Cahoon         ReplaceReg = PrevReg;
3305254f889dSBrendon Cahoon       else if (PrevReg && !Schedule.isLoopCarried(this, *Phi) &&
3306254f889dSBrendon Cahoon                (CyclePhi <= CycleSched || OrigMISU->getInstr()->isPHI()))
3307254f889dSBrendon Cahoon         ReplaceReg = PrevReg;
3308254f889dSBrendon Cahoon       else
3309254f889dSBrendon Cahoon         ReplaceReg = NewReg;
3310254f889dSBrendon Cahoon     }
3311254f889dSBrendon Cahoon     // The scheduled instruction occurs before the scheduled Phi, and the
3312254f889dSBrendon Cahoon     // Phi is not loop carried.
3313254f889dSBrendon Cahoon     if (!InProlog && StagePhi + 1 == StageSched &&
3314254f889dSBrendon Cahoon         !Schedule.isLoopCarried(this, *Phi))
3315254f889dSBrendon Cahoon       ReplaceReg = NewReg;
3316254f889dSBrendon Cahoon     if (StagePhi > StageSched && Phi->isPHI())
3317254f889dSBrendon Cahoon       ReplaceReg = NewReg;
3318254f889dSBrendon Cahoon     if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
3319254f889dSBrendon Cahoon       ReplaceReg = NewReg;
3320254f889dSBrendon Cahoon     if (ReplaceReg) {
3321254f889dSBrendon Cahoon       MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
3322254f889dSBrendon Cahoon       UseOp.setReg(ReplaceReg);
3323254f889dSBrendon Cahoon     }
3324254f889dSBrendon Cahoon   }
3325254f889dSBrendon Cahoon }
3326254f889dSBrendon Cahoon 
3327254f889dSBrendon Cahoon /// Check if we can change the instruction to use an offset value from the
3328254f889dSBrendon Cahoon /// previous iteration. If so, return true and set the base and offset values
3329254f889dSBrendon Cahoon /// so that we can rewrite the load, if necessary.
3330254f889dSBrendon Cahoon ///   v1 = Phi(v0, v3)
3331254f889dSBrendon Cahoon ///   v2 = load v1, 0
3332254f889dSBrendon Cahoon ///   v3 = post_store v1, 4, x
3333254f889dSBrendon Cahoon /// This function enables the load to be rewritten as v2 = load v3, 4.
3334254f889dSBrendon Cahoon bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
3335254f889dSBrendon Cahoon                                               unsigned &BasePos,
3336254f889dSBrendon Cahoon                                               unsigned &OffsetPos,
3337254f889dSBrendon Cahoon                                               unsigned &NewBase,
3338254f889dSBrendon Cahoon                                               int64_t &Offset) {
3339254f889dSBrendon Cahoon   // Get the load instruction.
33408fb181caSKrzysztof Parzyszek   if (TII->isPostIncrement(*MI))
3341254f889dSBrendon Cahoon     return false;
3342254f889dSBrendon Cahoon   unsigned BasePosLd, OffsetPosLd;
33438fb181caSKrzysztof Parzyszek   if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
3344254f889dSBrendon Cahoon     return false;
3345254f889dSBrendon Cahoon   unsigned BaseReg = MI->getOperand(BasePosLd).getReg();
3346254f889dSBrendon Cahoon 
3347254f889dSBrendon Cahoon   // Look for the Phi instruction.
3348254f889dSBrendon Cahoon   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
3349254f889dSBrendon Cahoon   MachineInstr *Phi = MRI.getVRegDef(BaseReg);
3350254f889dSBrendon Cahoon   if (!Phi || !Phi->isPHI())
3351254f889dSBrendon Cahoon     return false;
3352254f889dSBrendon Cahoon   // Get the register defined in the loop block.
3353254f889dSBrendon Cahoon   unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
3354254f889dSBrendon Cahoon   if (!PrevReg)
3355254f889dSBrendon Cahoon     return false;
3356254f889dSBrendon Cahoon 
3357254f889dSBrendon Cahoon   // Check for the post-increment load/store instruction.
3358254f889dSBrendon Cahoon   MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
3359254f889dSBrendon Cahoon   if (!PrevDef || PrevDef == MI)
3360254f889dSBrendon Cahoon     return false;
3361254f889dSBrendon Cahoon 
33628fb181caSKrzysztof Parzyszek   if (!TII->isPostIncrement(*PrevDef))
3363254f889dSBrendon Cahoon     return false;
3364254f889dSBrendon Cahoon 
3365254f889dSBrendon Cahoon   unsigned BasePos1 = 0, OffsetPos1 = 0;
33668fb181caSKrzysztof Parzyszek   if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
3367254f889dSBrendon Cahoon     return false;
3368254f889dSBrendon Cahoon 
3369254f889dSBrendon Cahoon   // Make sure offset values are both positive or both negative.
3370254f889dSBrendon Cahoon   int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
3371254f889dSBrendon Cahoon   int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
3372254f889dSBrendon Cahoon   if ((LoadOffset >= 0) != (StoreOffset >= 0))
3373254f889dSBrendon Cahoon     return false;
3374254f889dSBrendon Cahoon 
3375254f889dSBrendon Cahoon   // Set the return value once we determine that we return true.
3376254f889dSBrendon Cahoon   BasePos = BasePosLd;
3377254f889dSBrendon Cahoon   OffsetPos = OffsetPosLd;
3378254f889dSBrendon Cahoon   NewBase = PrevReg;
3379254f889dSBrendon Cahoon   Offset = StoreOffset;
3380254f889dSBrendon Cahoon   return true;
3381254f889dSBrendon Cahoon }
3382254f889dSBrendon Cahoon 
3383254f889dSBrendon Cahoon /// Apply changes to the instruction if needed. The changes are need
3384254f889dSBrendon Cahoon /// to improve the scheduling and depend up on the final schedule.
3385254f889dSBrendon Cahoon MachineInstr *SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
3386254f889dSBrendon Cahoon                                                   SMSchedule &Schedule,
3387254f889dSBrendon Cahoon                                                   bool UpdateDAG) {
3388254f889dSBrendon Cahoon   SUnit *SU = getSUnit(MI);
3389254f889dSBrendon Cahoon   DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3390254f889dSBrendon Cahoon       InstrChanges.find(SU);
3391254f889dSBrendon Cahoon   if (It != InstrChanges.end()) {
3392254f889dSBrendon Cahoon     std::pair<unsigned, int64_t> RegAndOffset = It->second;
3393254f889dSBrendon Cahoon     unsigned BasePos, OffsetPos;
33948fb181caSKrzysztof Parzyszek     if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
3395254f889dSBrendon Cahoon       return nullptr;
3396254f889dSBrendon Cahoon     unsigned BaseReg = MI->getOperand(BasePos).getReg();
3397254f889dSBrendon Cahoon     MachineInstr *LoopDef = findDefInLoop(BaseReg);
3398254f889dSBrendon Cahoon     int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
3399254f889dSBrendon Cahoon     int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
3400254f889dSBrendon Cahoon     int BaseStageNum = Schedule.stageScheduled(SU);
3401254f889dSBrendon Cahoon     int BaseCycleNum = Schedule.cycleScheduled(SU);
3402254f889dSBrendon Cahoon     if (BaseStageNum < DefStageNum) {
3403254f889dSBrendon Cahoon       MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3404254f889dSBrendon Cahoon       int OffsetDiff = DefStageNum - BaseStageNum;
3405254f889dSBrendon Cahoon       if (DefCycleNum < BaseCycleNum) {
3406254f889dSBrendon Cahoon         NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
3407254f889dSBrendon Cahoon         if (OffsetDiff > 0)
3408254f889dSBrendon Cahoon           --OffsetDiff;
3409254f889dSBrendon Cahoon       }
3410254f889dSBrendon Cahoon       int64_t NewOffset =
3411254f889dSBrendon Cahoon           MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
3412254f889dSBrendon Cahoon       NewMI->getOperand(OffsetPos).setImm(NewOffset);
3413254f889dSBrendon Cahoon       if (UpdateDAG) {
3414254f889dSBrendon Cahoon         SU->setInstr(NewMI);
3415254f889dSBrendon Cahoon         MISUnitMap[NewMI] = SU;
3416254f889dSBrendon Cahoon       }
3417254f889dSBrendon Cahoon       NewMIs.insert(NewMI);
3418254f889dSBrendon Cahoon       return NewMI;
3419254f889dSBrendon Cahoon     }
3420254f889dSBrendon Cahoon   }
3421254f889dSBrendon Cahoon   return nullptr;
3422254f889dSBrendon Cahoon }
3423254f889dSBrendon Cahoon 
3424254f889dSBrendon Cahoon /// Return true for an order dependence that is loop carried potentially.
3425254f889dSBrendon Cahoon /// An order dependence is loop carried if the destination defines a value
3426254f889dSBrendon Cahoon /// that may be used by the source in a subsequent iteration.
3427254f889dSBrendon Cahoon bool SwingSchedulerDAG::isLoopCarriedOrder(SUnit *Source, const SDep &Dep,
3428254f889dSBrendon Cahoon                                            bool isSucc) {
3429254f889dSBrendon Cahoon   if (!isOrder(Source, Dep) || Dep.isArtificial())
3430254f889dSBrendon Cahoon     return false;
3431254f889dSBrendon Cahoon 
3432254f889dSBrendon Cahoon   if (!SwpPruneLoopCarried)
3433254f889dSBrendon Cahoon     return true;
3434254f889dSBrendon Cahoon 
3435254f889dSBrendon Cahoon   MachineInstr *SI = Source->getInstr();
3436254f889dSBrendon Cahoon   MachineInstr *DI = Dep.getSUnit()->getInstr();
3437254f889dSBrendon Cahoon   if (!isSucc)
3438254f889dSBrendon Cahoon     std::swap(SI, DI);
3439254f889dSBrendon Cahoon   assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
3440254f889dSBrendon Cahoon 
3441254f889dSBrendon Cahoon   // Assume ordered loads and stores may have a loop carried dependence.
3442254f889dSBrendon Cahoon   if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
3443254f889dSBrendon Cahoon       SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
3444254f889dSBrendon Cahoon     return true;
3445254f889dSBrendon Cahoon 
3446254f889dSBrendon Cahoon   // Only chain dependences between a load and store can be loop carried.
3447254f889dSBrendon Cahoon   if (!DI->mayStore() || !SI->mayLoad())
3448254f889dSBrendon Cahoon     return false;
3449254f889dSBrendon Cahoon 
3450254f889dSBrendon Cahoon   unsigned DeltaS, DeltaD;
3451254f889dSBrendon Cahoon   if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
3452254f889dSBrendon Cahoon     return true;
3453254f889dSBrendon Cahoon 
3454254f889dSBrendon Cahoon   unsigned BaseRegS, BaseRegD;
3455254f889dSBrendon Cahoon   int64_t OffsetS, OffsetD;
3456254f889dSBrendon Cahoon   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3457254f889dSBrendon Cahoon   if (!TII->getMemOpBaseRegImmOfs(*SI, BaseRegS, OffsetS, TRI) ||
3458254f889dSBrendon Cahoon       !TII->getMemOpBaseRegImmOfs(*DI, BaseRegD, OffsetD, TRI))
3459254f889dSBrendon Cahoon     return true;
3460254f889dSBrendon Cahoon 
3461254f889dSBrendon Cahoon   if (BaseRegS != BaseRegD)
3462254f889dSBrendon Cahoon     return true;
3463254f889dSBrendon Cahoon 
3464254f889dSBrendon Cahoon   uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
3465254f889dSBrendon Cahoon   uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
3466254f889dSBrendon Cahoon 
3467254f889dSBrendon Cahoon   // This is the main test, which checks the offset values and the loop
3468254f889dSBrendon Cahoon   // increment value to determine if the accesses may be loop carried.
3469254f889dSBrendon Cahoon   if (OffsetS >= OffsetD)
3470254f889dSBrendon Cahoon     return OffsetS + AccessSizeS > DeltaS;
3471254f889dSBrendon Cahoon   else if (OffsetS < OffsetD)
3472254f889dSBrendon Cahoon     return OffsetD + AccessSizeD > DeltaD;
3473254f889dSBrendon Cahoon 
3474254f889dSBrendon Cahoon   return true;
3475254f889dSBrendon Cahoon }
3476254f889dSBrendon Cahoon 
3477254f889dSBrendon Cahoon /// Try to schedule the node at the specified StartCycle and continue
3478254f889dSBrendon Cahoon /// until the node is schedule or the EndCycle is reached.  This function
3479254f889dSBrendon Cahoon /// returns true if the node is scheduled.  This routine may search either
3480254f889dSBrendon Cahoon /// forward or backward for a place to insert the instruction based upon
3481254f889dSBrendon Cahoon /// the relative values of StartCycle and EndCycle.
3482254f889dSBrendon Cahoon bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
3483254f889dSBrendon Cahoon   bool forward = true;
3484254f889dSBrendon Cahoon   if (StartCycle > EndCycle)
3485254f889dSBrendon Cahoon     forward = false;
3486254f889dSBrendon Cahoon 
3487254f889dSBrendon Cahoon   // The terminating condition depends on the direction.
3488254f889dSBrendon Cahoon   int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
3489254f889dSBrendon Cahoon   for (int curCycle = StartCycle; curCycle != termCycle;
3490254f889dSBrendon Cahoon        forward ? ++curCycle : --curCycle) {
3491254f889dSBrendon Cahoon 
3492254f889dSBrendon Cahoon     // Add the already scheduled instructions at the specified cycle to the DFA.
3493254f889dSBrendon Cahoon     Resources->clearResources();
3494254f889dSBrendon Cahoon     for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
3495254f889dSBrendon Cahoon          checkCycle <= LastCycle; checkCycle += II) {
3496254f889dSBrendon Cahoon       std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
3497254f889dSBrendon Cahoon 
3498254f889dSBrendon Cahoon       for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(),
3499254f889dSBrendon Cahoon                                          E = cycleInstrs.end();
3500254f889dSBrendon Cahoon            I != E; ++I) {
3501254f889dSBrendon Cahoon         if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
3502254f889dSBrendon Cahoon           continue;
3503254f889dSBrendon Cahoon         assert(Resources->canReserveResources(*(*I)->getInstr()) &&
3504254f889dSBrendon Cahoon                "These instructions have already been scheduled.");
3505254f889dSBrendon Cahoon         Resources->reserveResources(*(*I)->getInstr());
3506254f889dSBrendon Cahoon       }
3507254f889dSBrendon Cahoon     }
3508254f889dSBrendon Cahoon     if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
3509254f889dSBrendon Cahoon         Resources->canReserveResources(*SU->getInstr())) {
3510254f889dSBrendon Cahoon       DEBUG({
3511254f889dSBrendon Cahoon         dbgs() << "\tinsert at cycle " << curCycle << " ";
3512254f889dSBrendon Cahoon         SU->getInstr()->dump();
3513254f889dSBrendon Cahoon       });
3514254f889dSBrendon Cahoon 
3515254f889dSBrendon Cahoon       ScheduledInstrs[curCycle].push_back(SU);
3516254f889dSBrendon Cahoon       InstrToCycle.insert(std::make_pair(SU, curCycle));
3517254f889dSBrendon Cahoon       if (curCycle > LastCycle)
3518254f889dSBrendon Cahoon         LastCycle = curCycle;
3519254f889dSBrendon Cahoon       if (curCycle < FirstCycle)
3520254f889dSBrendon Cahoon         FirstCycle = curCycle;
3521254f889dSBrendon Cahoon       return true;
3522254f889dSBrendon Cahoon     }
3523254f889dSBrendon Cahoon     DEBUG({
3524254f889dSBrendon Cahoon       dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
3525254f889dSBrendon Cahoon       SU->getInstr()->dump();
3526254f889dSBrendon Cahoon     });
3527254f889dSBrendon Cahoon   }
3528254f889dSBrendon Cahoon   return false;
3529254f889dSBrendon Cahoon }
3530254f889dSBrendon Cahoon 
3531254f889dSBrendon Cahoon // Return the cycle of the earliest scheduled instruction in the chain.
3532254f889dSBrendon Cahoon int SMSchedule::earliestCycleInChain(const SDep &Dep) {
3533254f889dSBrendon Cahoon   SmallPtrSet<SUnit *, 8> Visited;
3534254f889dSBrendon Cahoon   SmallVector<SDep, 8> Worklist;
3535254f889dSBrendon Cahoon   Worklist.push_back(Dep);
3536254f889dSBrendon Cahoon   int EarlyCycle = INT_MAX;
3537254f889dSBrendon Cahoon   while (!Worklist.empty()) {
3538254f889dSBrendon Cahoon     const SDep &Cur = Worklist.pop_back_val();
3539254f889dSBrendon Cahoon     SUnit *PrevSU = Cur.getSUnit();
3540254f889dSBrendon Cahoon     if (Visited.count(PrevSU))
3541254f889dSBrendon Cahoon       continue;
3542254f889dSBrendon Cahoon     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
3543254f889dSBrendon Cahoon     if (it == InstrToCycle.end())
3544254f889dSBrendon Cahoon       continue;
3545254f889dSBrendon Cahoon     EarlyCycle = std::min(EarlyCycle, it->second);
3546254f889dSBrendon Cahoon     for (const auto &PI : PrevSU->Preds)
3547254f889dSBrendon Cahoon       if (SwingSchedulerDAG::isOrder(PrevSU, PI))
3548254f889dSBrendon Cahoon         Worklist.push_back(PI);
3549254f889dSBrendon Cahoon     Visited.insert(PrevSU);
3550254f889dSBrendon Cahoon   }
3551254f889dSBrendon Cahoon   return EarlyCycle;
3552254f889dSBrendon Cahoon }
3553254f889dSBrendon Cahoon 
3554254f889dSBrendon Cahoon // Return the cycle of the latest scheduled instruction in the chain.
3555254f889dSBrendon Cahoon int SMSchedule::latestCycleInChain(const SDep &Dep) {
3556254f889dSBrendon Cahoon   SmallPtrSet<SUnit *, 8> Visited;
3557254f889dSBrendon Cahoon   SmallVector<SDep, 8> Worklist;
3558254f889dSBrendon Cahoon   Worklist.push_back(Dep);
3559254f889dSBrendon Cahoon   int LateCycle = INT_MIN;
3560254f889dSBrendon Cahoon   while (!Worklist.empty()) {
3561254f889dSBrendon Cahoon     const SDep &Cur = Worklist.pop_back_val();
3562254f889dSBrendon Cahoon     SUnit *SuccSU = Cur.getSUnit();
3563254f889dSBrendon Cahoon     if (Visited.count(SuccSU))
3564254f889dSBrendon Cahoon       continue;
3565254f889dSBrendon Cahoon     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
3566254f889dSBrendon Cahoon     if (it == InstrToCycle.end())
3567254f889dSBrendon Cahoon       continue;
3568254f889dSBrendon Cahoon     LateCycle = std::max(LateCycle, it->second);
3569254f889dSBrendon Cahoon     for (const auto &SI : SuccSU->Succs)
3570254f889dSBrendon Cahoon       if (SwingSchedulerDAG::isOrder(SuccSU, SI))
3571254f889dSBrendon Cahoon         Worklist.push_back(SI);
3572254f889dSBrendon Cahoon     Visited.insert(SuccSU);
3573254f889dSBrendon Cahoon   }
3574254f889dSBrendon Cahoon   return LateCycle;
3575254f889dSBrendon Cahoon }
3576254f889dSBrendon Cahoon 
3577254f889dSBrendon Cahoon /// If an instruction has a use that spans multiple iterations, then
3578254f889dSBrendon Cahoon /// return true. These instructions are characterized by having a back-ege
3579254f889dSBrendon Cahoon /// to a Phi, which contains a reference to another Phi.
3580254f889dSBrendon Cahoon static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
3581254f889dSBrendon Cahoon   for (auto &P : SU->Preds)
3582254f889dSBrendon Cahoon     if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
3583254f889dSBrendon Cahoon       for (auto &S : P.getSUnit()->Succs)
3584254f889dSBrendon Cahoon         if (S.getKind() == SDep::Order && S.getSUnit()->getInstr()->isPHI())
3585254f889dSBrendon Cahoon           return P.getSUnit();
3586254f889dSBrendon Cahoon   return nullptr;
3587254f889dSBrendon Cahoon }
3588254f889dSBrendon Cahoon 
3589254f889dSBrendon Cahoon /// Compute the scheduling start slot for the instruction.  The start slot
3590254f889dSBrendon Cahoon /// depends on any predecessor or successor nodes scheduled already.
3591254f889dSBrendon Cahoon void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
3592254f889dSBrendon Cahoon                               int *MinEnd, int *MaxStart, int II,
3593254f889dSBrendon Cahoon                               SwingSchedulerDAG *DAG) {
3594254f889dSBrendon Cahoon   // Iterate over each instruction that has been scheduled already.  The start
3595254f889dSBrendon Cahoon   // slot computuation depends on whether the previously scheduled instruction
3596254f889dSBrendon Cahoon   // is a predecessor or successor of the specified instruction.
3597254f889dSBrendon Cahoon   for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
3598254f889dSBrendon Cahoon 
3599254f889dSBrendon Cahoon     // Iterate over each instruction in the current cycle.
3600254f889dSBrendon Cahoon     for (SUnit *I : getInstructions(cycle)) {
3601254f889dSBrendon Cahoon       // Because we're processing a DAG for the dependences, we recognize
3602254f889dSBrendon Cahoon       // the back-edge in recurrences by anti dependences.
3603254f889dSBrendon Cahoon       for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
3604254f889dSBrendon Cahoon         const SDep &Dep = SU->Preds[i];
3605254f889dSBrendon Cahoon         if (Dep.getSUnit() == I) {
3606254f889dSBrendon Cahoon           if (!DAG->isBackedge(SU, Dep)) {
3607254f889dSBrendon Cahoon             int EarlyStart = cycle + DAG->getLatency(SU, Dep) -
3608254f889dSBrendon Cahoon                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3609254f889dSBrendon Cahoon             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
3610254f889dSBrendon Cahoon             if (DAG->isLoopCarriedOrder(SU, Dep, false)) {
3611254f889dSBrendon Cahoon               int End = earliestCycleInChain(Dep) + (II - 1);
3612254f889dSBrendon Cahoon               *MinEnd = std::min(*MinEnd, End);
3613254f889dSBrendon Cahoon             }
3614254f889dSBrendon Cahoon           } else {
3615254f889dSBrendon Cahoon             int LateStart = cycle - DAG->getLatency(SU, Dep) +
3616254f889dSBrendon Cahoon                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3617254f889dSBrendon Cahoon             *MinLateStart = std::min(*MinLateStart, LateStart);
3618254f889dSBrendon Cahoon           }
3619254f889dSBrendon Cahoon         }
3620254f889dSBrendon Cahoon         // For instruction that requires multiple iterations, make sure that
3621254f889dSBrendon Cahoon         // the dependent instruction is not scheduled past the definition.
3622254f889dSBrendon Cahoon         SUnit *BE = multipleIterations(I, DAG);
3623254f889dSBrendon Cahoon         if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
3624254f889dSBrendon Cahoon             !SU->isPred(I))
3625254f889dSBrendon Cahoon           *MinLateStart = std::min(*MinLateStart, cycle);
3626254f889dSBrendon Cahoon       }
3627254f889dSBrendon Cahoon       for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i)
3628254f889dSBrendon Cahoon         if (SU->Succs[i].getSUnit() == I) {
3629254f889dSBrendon Cahoon           const SDep &Dep = SU->Succs[i];
3630254f889dSBrendon Cahoon           if (!DAG->isBackedge(SU, Dep)) {
3631254f889dSBrendon Cahoon             int LateStart = cycle - DAG->getLatency(SU, Dep) +
3632254f889dSBrendon Cahoon                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3633254f889dSBrendon Cahoon             *MinLateStart = std::min(*MinLateStart, LateStart);
3634254f889dSBrendon Cahoon             if (DAG->isLoopCarriedOrder(SU, Dep)) {
3635254f889dSBrendon Cahoon               int Start = latestCycleInChain(Dep) + 1 - II;
3636254f889dSBrendon Cahoon               *MaxStart = std::max(*MaxStart, Start);
3637254f889dSBrendon Cahoon             }
3638254f889dSBrendon Cahoon           } else {
3639254f889dSBrendon Cahoon             int EarlyStart = cycle + DAG->getLatency(SU, Dep) -
3640254f889dSBrendon Cahoon                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3641254f889dSBrendon Cahoon             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
3642254f889dSBrendon Cahoon           }
3643254f889dSBrendon Cahoon         }
3644254f889dSBrendon Cahoon     }
3645254f889dSBrendon Cahoon   }
3646254f889dSBrendon Cahoon }
3647254f889dSBrendon Cahoon 
3648254f889dSBrendon Cahoon /// Order the instructions within a cycle so that the definitions occur
3649254f889dSBrendon Cahoon /// before the uses. Returns true if the instruction is added to the start
3650254f889dSBrendon Cahoon /// of the list, or false if added to the end.
3651254f889dSBrendon Cahoon bool SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
3652254f889dSBrendon Cahoon                                  std::deque<SUnit *> &Insts) {
3653254f889dSBrendon Cahoon   MachineInstr *MI = SU->getInstr();
3654254f889dSBrendon Cahoon   bool OrderBeforeUse = false;
3655254f889dSBrendon Cahoon   bool OrderAfterDef = false;
3656254f889dSBrendon Cahoon   bool OrderBeforeDef = false;
3657254f889dSBrendon Cahoon   unsigned MoveDef = 0;
3658254f889dSBrendon Cahoon   unsigned MoveUse = 0;
3659254f889dSBrendon Cahoon   int StageInst1 = stageScheduled(SU);
3660254f889dSBrendon Cahoon 
3661254f889dSBrendon Cahoon   unsigned Pos = 0;
3662254f889dSBrendon Cahoon   for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
3663254f889dSBrendon Cahoon        ++I, ++Pos) {
3664254f889dSBrendon Cahoon     // Relative order of Phis does not matter.
3665254f889dSBrendon Cahoon     if (MI->isPHI() && (*I)->getInstr()->isPHI())
3666254f889dSBrendon Cahoon       continue;
3667254f889dSBrendon Cahoon     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3668254f889dSBrendon Cahoon       MachineOperand &MO = MI->getOperand(i);
3669254f889dSBrendon Cahoon       if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
3670254f889dSBrendon Cahoon         continue;
3671254f889dSBrendon Cahoon       unsigned Reg = MO.getReg();
3672254f889dSBrendon Cahoon       unsigned BasePos, OffsetPos;
36738fb181caSKrzysztof Parzyszek       if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
3674254f889dSBrendon Cahoon         if (MI->getOperand(BasePos).getReg() == Reg)
3675254f889dSBrendon Cahoon           if (unsigned NewReg = SSD->getInstrBaseReg(SU))
3676254f889dSBrendon Cahoon             Reg = NewReg;
3677254f889dSBrendon Cahoon       bool Reads, Writes;
3678254f889dSBrendon Cahoon       std::tie(Reads, Writes) =
3679254f889dSBrendon Cahoon           (*I)->getInstr()->readsWritesVirtualRegister(Reg);
3680254f889dSBrendon Cahoon       if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
3681254f889dSBrendon Cahoon         OrderBeforeUse = true;
3682254f889dSBrendon Cahoon         MoveUse = Pos;
3683254f889dSBrendon Cahoon       } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
3684254f889dSBrendon Cahoon         // Add the instruction after the scheduled instruction.
3685254f889dSBrendon Cahoon         OrderAfterDef = true;
3686254f889dSBrendon Cahoon         MoveDef = Pos;
3687254f889dSBrendon Cahoon       } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
3688254f889dSBrendon Cahoon         if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
3689254f889dSBrendon Cahoon           OrderBeforeUse = true;
3690254f889dSBrendon Cahoon           MoveUse = Pos;
3691254f889dSBrendon Cahoon         } else {
3692254f889dSBrendon Cahoon           OrderAfterDef = true;
3693254f889dSBrendon Cahoon           MoveDef = Pos;
3694254f889dSBrendon Cahoon         }
3695254f889dSBrendon Cahoon       } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
3696254f889dSBrendon Cahoon         OrderBeforeUse = true;
3697254f889dSBrendon Cahoon         MoveUse = Pos;
3698254f889dSBrendon Cahoon         if (MoveUse != 0) {
3699254f889dSBrendon Cahoon           OrderAfterDef = true;
3700254f889dSBrendon Cahoon           MoveDef = Pos - 1;
3701254f889dSBrendon Cahoon         }
3702254f889dSBrendon Cahoon       } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
3703254f889dSBrendon Cahoon         // Add the instruction before the scheduled instruction.
3704254f889dSBrendon Cahoon         OrderBeforeUse = true;
3705254f889dSBrendon Cahoon         MoveUse = Pos;
3706254f889dSBrendon Cahoon       } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
3707254f889dSBrendon Cahoon                  isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
3708254f889dSBrendon Cahoon         OrderBeforeDef = true;
3709254f889dSBrendon Cahoon         MoveUse = Pos;
3710254f889dSBrendon Cahoon       }
3711254f889dSBrendon Cahoon     }
3712254f889dSBrendon Cahoon     // Check for order dependences between instructions. Make sure the source
3713254f889dSBrendon Cahoon     // is ordered before the destination.
3714254f889dSBrendon Cahoon     for (auto &S : SU->Succs)
3715254f889dSBrendon Cahoon       if (S.getKind() == SDep::Order) {
3716254f889dSBrendon Cahoon         if (S.getSUnit() == *I && stageScheduled(*I) == StageInst1) {
3717254f889dSBrendon Cahoon           OrderBeforeUse = true;
3718254f889dSBrendon Cahoon           MoveUse = Pos;
3719254f889dSBrendon Cahoon         }
3720254f889dSBrendon Cahoon       } else if (TargetRegisterInfo::isPhysicalRegister(S.getReg())) {
3721254f889dSBrendon Cahoon         if (cycleScheduled(SU) != cycleScheduled(S.getSUnit())) {
3722254f889dSBrendon Cahoon           if (S.isAssignedRegDep()) {
3723254f889dSBrendon Cahoon             OrderAfterDef = true;
3724254f889dSBrendon Cahoon             MoveDef = Pos;
3725254f889dSBrendon Cahoon           }
3726254f889dSBrendon Cahoon         } else {
3727254f889dSBrendon Cahoon           OrderBeforeUse = true;
3728254f889dSBrendon Cahoon           MoveUse = Pos;
3729254f889dSBrendon Cahoon         }
3730254f889dSBrendon Cahoon       }
3731254f889dSBrendon Cahoon     for (auto &P : SU->Preds)
3732254f889dSBrendon Cahoon       if (P.getKind() == SDep::Order) {
3733254f889dSBrendon Cahoon         if (P.getSUnit() == *I && stageScheduled(*I) == StageInst1) {
3734254f889dSBrendon Cahoon           OrderAfterDef = true;
3735254f889dSBrendon Cahoon           MoveDef = Pos;
3736254f889dSBrendon Cahoon         }
3737254f889dSBrendon Cahoon       } else if (TargetRegisterInfo::isPhysicalRegister(P.getReg())) {
3738254f889dSBrendon Cahoon         if (cycleScheduled(SU) != cycleScheduled(P.getSUnit())) {
3739254f889dSBrendon Cahoon           if (P.isAssignedRegDep()) {
3740254f889dSBrendon Cahoon             OrderBeforeUse = true;
3741254f889dSBrendon Cahoon             MoveUse = Pos;
3742254f889dSBrendon Cahoon           }
3743254f889dSBrendon Cahoon         } else {
3744254f889dSBrendon Cahoon           OrderAfterDef = true;
3745254f889dSBrendon Cahoon           MoveDef = Pos;
3746254f889dSBrendon Cahoon         }
3747254f889dSBrendon Cahoon       }
3748254f889dSBrendon Cahoon   }
3749254f889dSBrendon Cahoon 
3750254f889dSBrendon Cahoon   // A circular dependence.
3751254f889dSBrendon Cahoon   if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
3752254f889dSBrendon Cahoon     OrderBeforeUse = false;
3753254f889dSBrendon Cahoon 
3754254f889dSBrendon Cahoon   // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
3755254f889dSBrendon Cahoon   // to a loop-carried dependence.
3756254f889dSBrendon Cahoon   if (OrderBeforeDef)
3757254f889dSBrendon Cahoon     OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
3758254f889dSBrendon Cahoon 
3759254f889dSBrendon Cahoon   // The uncommon case when the instruction order needs to be updated because
3760254f889dSBrendon Cahoon   // there is both a use and def.
3761254f889dSBrendon Cahoon   if (OrderBeforeUse && OrderAfterDef) {
3762254f889dSBrendon Cahoon     SUnit *UseSU = Insts.at(MoveUse);
3763254f889dSBrendon Cahoon     SUnit *DefSU = Insts.at(MoveDef);
3764254f889dSBrendon Cahoon     if (MoveUse > MoveDef) {
3765254f889dSBrendon Cahoon       Insts.erase(Insts.begin() + MoveUse);
3766254f889dSBrendon Cahoon       Insts.erase(Insts.begin() + MoveDef);
3767254f889dSBrendon Cahoon     } else {
3768254f889dSBrendon Cahoon       Insts.erase(Insts.begin() + MoveDef);
3769254f889dSBrendon Cahoon       Insts.erase(Insts.begin() + MoveUse);
3770254f889dSBrendon Cahoon     }
3771254f889dSBrendon Cahoon     if (orderDependence(SSD, UseSU, Insts)) {
3772254f889dSBrendon Cahoon       Insts.push_front(SU);
3773254f889dSBrendon Cahoon       orderDependence(SSD, DefSU, Insts);
3774254f889dSBrendon Cahoon       return true;
3775254f889dSBrendon Cahoon     }
3776254f889dSBrendon Cahoon     Insts.pop_back();
3777254f889dSBrendon Cahoon     Insts.push_back(SU);
3778254f889dSBrendon Cahoon     Insts.push_back(UseSU);
3779254f889dSBrendon Cahoon     orderDependence(SSD, DefSU, Insts);
3780254f889dSBrendon Cahoon     return false;
3781254f889dSBrendon Cahoon   }
3782254f889dSBrendon Cahoon   // Put the new instruction first if there is a use in the list. Otherwise,
3783254f889dSBrendon Cahoon   // put it at the end of the list.
3784254f889dSBrendon Cahoon   if (OrderBeforeUse)
3785254f889dSBrendon Cahoon     Insts.push_front(SU);
3786254f889dSBrendon Cahoon   else
3787254f889dSBrendon Cahoon     Insts.push_back(SU);
3788254f889dSBrendon Cahoon   return OrderBeforeUse;
3789254f889dSBrendon Cahoon }
3790254f889dSBrendon Cahoon 
3791254f889dSBrendon Cahoon /// Return true if the scheduled Phi has a loop carried operand.
3792254f889dSBrendon Cahoon bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
3793254f889dSBrendon Cahoon   if (!Phi.isPHI())
3794254f889dSBrendon Cahoon     return false;
3795254f889dSBrendon Cahoon   assert(Phi.isPHI() && "Expecing a Phi.");
3796254f889dSBrendon Cahoon   SUnit *DefSU = SSD->getSUnit(&Phi);
3797254f889dSBrendon Cahoon   unsigned DefCycle = cycleScheduled(DefSU);
3798254f889dSBrendon Cahoon   int DefStage = stageScheduled(DefSU);
3799254f889dSBrendon Cahoon 
3800254f889dSBrendon Cahoon   unsigned InitVal = 0;
3801254f889dSBrendon Cahoon   unsigned LoopVal = 0;
3802254f889dSBrendon Cahoon   getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
3803254f889dSBrendon Cahoon   SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
3804254f889dSBrendon Cahoon   if (!UseSU)
3805254f889dSBrendon Cahoon     return true;
3806254f889dSBrendon Cahoon   if (UseSU->getInstr()->isPHI())
3807254f889dSBrendon Cahoon     return true;
3808254f889dSBrendon Cahoon   unsigned LoopCycle = cycleScheduled(UseSU);
3809254f889dSBrendon Cahoon   int LoopStage = stageScheduled(UseSU);
38103d8482a8SSimon Pilgrim   return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
3811254f889dSBrendon Cahoon }
3812254f889dSBrendon Cahoon 
3813254f889dSBrendon Cahoon /// Return true if the instruction is a definition that is loop carried
3814254f889dSBrendon Cahoon /// and defines the use on the next iteration.
3815254f889dSBrendon Cahoon ///        v1 = phi(v2, v3)
3816254f889dSBrendon Cahoon ///  (Def) v3 = op v1
3817254f889dSBrendon Cahoon ///  (MO)   = v1
3818254f889dSBrendon Cahoon /// If MO appears before Def, then then v1 and v3 may get assigned to the same
3819254f889dSBrendon Cahoon /// register.
3820254f889dSBrendon Cahoon bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
3821254f889dSBrendon Cahoon                                        MachineInstr *Def, MachineOperand &MO) {
3822254f889dSBrendon Cahoon   if (!MO.isReg())
3823254f889dSBrendon Cahoon     return false;
3824254f889dSBrendon Cahoon   if (Def->isPHI())
3825254f889dSBrendon Cahoon     return false;
3826254f889dSBrendon Cahoon   MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
3827254f889dSBrendon Cahoon   if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
3828254f889dSBrendon Cahoon     return false;
3829254f889dSBrendon Cahoon   if (!isLoopCarried(SSD, *Phi))
3830254f889dSBrendon Cahoon     return false;
3831254f889dSBrendon Cahoon   unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
3832254f889dSBrendon Cahoon   for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
3833254f889dSBrendon Cahoon     MachineOperand &DMO = Def->getOperand(i);
3834254f889dSBrendon Cahoon     if (!DMO.isReg() || !DMO.isDef())
3835254f889dSBrendon Cahoon       continue;
3836254f889dSBrendon Cahoon     if (DMO.getReg() == LoopReg)
3837254f889dSBrendon Cahoon       return true;
3838254f889dSBrendon Cahoon   }
3839254f889dSBrendon Cahoon   return false;
3840254f889dSBrendon Cahoon }
3841254f889dSBrendon Cahoon 
3842254f889dSBrendon Cahoon // Check if the generated schedule is valid. This function checks if
3843254f889dSBrendon Cahoon // an instruction that uses a physical register is scheduled in a
3844254f889dSBrendon Cahoon // different stage than the definition. The pipeliner does not handle
3845254f889dSBrendon Cahoon // physical register values that may cross a basic block boundary.
3846254f889dSBrendon Cahoon bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
3847254f889dSBrendon Cahoon   for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
3848254f889dSBrendon Cahoon     SUnit &SU = SSD->SUnits[i];
3849254f889dSBrendon Cahoon     if (!SU.hasPhysRegDefs)
3850254f889dSBrendon Cahoon       continue;
3851254f889dSBrendon Cahoon     int StageDef = stageScheduled(&SU);
3852254f889dSBrendon Cahoon     assert(StageDef != -1 && "Instruction should have been scheduled.");
3853254f889dSBrendon Cahoon     for (auto &SI : SU.Succs)
3854254f889dSBrendon Cahoon       if (SI.isAssignedRegDep())
3855b39236b6SSimon Pilgrim         if (ST.getRegisterInfo()->isPhysicalRegister(SI.getReg()))
3856254f889dSBrendon Cahoon           if (stageScheduled(SI.getSUnit()) != StageDef)
3857254f889dSBrendon Cahoon             return false;
3858254f889dSBrendon Cahoon   }
3859254f889dSBrendon Cahoon   return true;
3860254f889dSBrendon Cahoon }
3861254f889dSBrendon Cahoon 
3862254f889dSBrendon Cahoon /// After the schedule has been formed, call this function to combine
3863254f889dSBrendon Cahoon /// the instructions from the different stages/cycles.  That is, this
3864254f889dSBrendon Cahoon /// function creates a schedule that represents a single iteration.
3865254f889dSBrendon Cahoon void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
3866254f889dSBrendon Cahoon   // Move all instructions to the first stage from later stages.
3867254f889dSBrendon Cahoon   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3868254f889dSBrendon Cahoon     for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
3869254f889dSBrendon Cahoon          ++stage) {
3870254f889dSBrendon Cahoon       std::deque<SUnit *> &cycleInstrs =
3871254f889dSBrendon Cahoon           ScheduledInstrs[cycle + (stage * InitiationInterval)];
3872254f889dSBrendon Cahoon       for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
3873254f889dSBrendon Cahoon                                                  E = cycleInstrs.rend();
3874254f889dSBrendon Cahoon            I != E; ++I)
3875254f889dSBrendon Cahoon         ScheduledInstrs[cycle].push_front(*I);
3876254f889dSBrendon Cahoon     }
3877254f889dSBrendon Cahoon   }
3878254f889dSBrendon Cahoon   // Iterate over the definitions in each instruction, and compute the
3879254f889dSBrendon Cahoon   // stage difference for each use.  Keep the maximum value.
3880254f889dSBrendon Cahoon   for (auto &I : InstrToCycle) {
3881254f889dSBrendon Cahoon     int DefStage = stageScheduled(I.first);
3882254f889dSBrendon Cahoon     MachineInstr *MI = I.first->getInstr();
3883254f889dSBrendon Cahoon     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3884254f889dSBrendon Cahoon       MachineOperand &Op = MI->getOperand(i);
3885254f889dSBrendon Cahoon       if (!Op.isReg() || !Op.isDef())
3886254f889dSBrendon Cahoon         continue;
3887254f889dSBrendon Cahoon 
3888254f889dSBrendon Cahoon       unsigned Reg = Op.getReg();
3889254f889dSBrendon Cahoon       unsigned MaxDiff = 0;
3890254f889dSBrendon Cahoon       bool PhiIsSwapped = false;
3891254f889dSBrendon Cahoon       for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(Reg),
3892254f889dSBrendon Cahoon                                              EI = MRI.use_end();
3893254f889dSBrendon Cahoon            UI != EI; ++UI) {
3894254f889dSBrendon Cahoon         MachineOperand &UseOp = *UI;
3895254f889dSBrendon Cahoon         MachineInstr *UseMI = UseOp.getParent();
3896254f889dSBrendon Cahoon         SUnit *SUnitUse = SSD->getSUnit(UseMI);
3897254f889dSBrendon Cahoon         int UseStage = stageScheduled(SUnitUse);
3898254f889dSBrendon Cahoon         unsigned Diff = 0;
3899254f889dSBrendon Cahoon         if (UseStage != -1 && UseStage >= DefStage)
3900254f889dSBrendon Cahoon           Diff = UseStage - DefStage;
3901254f889dSBrendon Cahoon         if (MI->isPHI()) {
3902254f889dSBrendon Cahoon           if (isLoopCarried(SSD, *MI))
3903254f889dSBrendon Cahoon             ++Diff;
3904254f889dSBrendon Cahoon           else
3905254f889dSBrendon Cahoon             PhiIsSwapped = true;
3906254f889dSBrendon Cahoon         }
3907254f889dSBrendon Cahoon         MaxDiff = std::max(Diff, MaxDiff);
3908254f889dSBrendon Cahoon       }
3909254f889dSBrendon Cahoon       RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
3910254f889dSBrendon Cahoon     }
3911254f889dSBrendon Cahoon   }
3912254f889dSBrendon Cahoon 
3913254f889dSBrendon Cahoon   // Erase all the elements in the later stages. Only one iteration should
3914254f889dSBrendon Cahoon   // remain in the scheduled list, and it contains all the instructions.
3915254f889dSBrendon Cahoon   for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
3916254f889dSBrendon Cahoon     ScheduledInstrs.erase(cycle);
3917254f889dSBrendon Cahoon 
3918254f889dSBrendon Cahoon   // Change the registers in instruction as specified in the InstrChanges
3919254f889dSBrendon Cahoon   // map. We need to use the new registers to create the correct order.
3920254f889dSBrendon Cahoon   for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
3921254f889dSBrendon Cahoon     SUnit *SU = &SSD->SUnits[i];
3922254f889dSBrendon Cahoon     SSD->applyInstrChange(SU->getInstr(), *this, true);
3923254f889dSBrendon Cahoon   }
3924254f889dSBrendon Cahoon 
3925254f889dSBrendon Cahoon   // Reorder the instructions in each cycle to fix and improve the
3926254f889dSBrendon Cahoon   // generated code.
3927254f889dSBrendon Cahoon   for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
3928254f889dSBrendon Cahoon     std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
3929254f889dSBrendon Cahoon     std::deque<SUnit *> newOrderZC;
3930254f889dSBrendon Cahoon     // Put the zero-cost, pseudo instructions at the start of the cycle.
3931254f889dSBrendon Cahoon     for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
3932254f889dSBrendon Cahoon       SUnit *SU = cycleInstrs[i];
3933254f889dSBrendon Cahoon       if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()))
3934254f889dSBrendon Cahoon         orderDependence(SSD, SU, newOrderZC);
3935254f889dSBrendon Cahoon     }
3936254f889dSBrendon Cahoon     std::deque<SUnit *> newOrderI;
3937254f889dSBrendon Cahoon     // Then, add the regular instructions back.
3938254f889dSBrendon Cahoon     for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
3939254f889dSBrendon Cahoon       SUnit *SU = cycleInstrs[i];
3940254f889dSBrendon Cahoon       if (!ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()))
3941254f889dSBrendon Cahoon         orderDependence(SSD, SU, newOrderI);
3942254f889dSBrendon Cahoon     }
3943254f889dSBrendon Cahoon     // Replace the old order with the new order.
3944254f889dSBrendon Cahoon     cycleInstrs.swap(newOrderZC);
3945254f889dSBrendon Cahoon     cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
3946254f889dSBrendon Cahoon   }
3947254f889dSBrendon Cahoon 
3948254f889dSBrendon Cahoon   DEBUG(dump(););
3949254f889dSBrendon Cahoon }
3950254f889dSBrendon Cahoon 
3951254f889dSBrendon Cahoon /// Print the schedule information to the given output.
3952254f889dSBrendon Cahoon void SMSchedule::print(raw_ostream &os) const {
3953254f889dSBrendon Cahoon   // Iterate over each cycle.
3954254f889dSBrendon Cahoon   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3955254f889dSBrendon Cahoon     // Iterate over each instruction in the cycle.
3956254f889dSBrendon Cahoon     const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
3957254f889dSBrendon Cahoon     for (SUnit *CI : cycleInstrs->second) {
3958254f889dSBrendon Cahoon       os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
3959254f889dSBrendon Cahoon       os << "(" << CI->NodeNum << ") ";
3960254f889dSBrendon Cahoon       CI->getInstr()->print(os);
3961254f889dSBrendon Cahoon       os << "\n";
3962254f889dSBrendon Cahoon     }
3963254f889dSBrendon Cahoon   }
3964254f889dSBrendon Cahoon }
3965254f889dSBrendon Cahoon 
3966254f889dSBrendon Cahoon /// Utility function used for debugging to print the schedule.
3967254f889dSBrendon Cahoon void SMSchedule::dump() const { print(dbgs()); }
3968