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