blob: 167c05f9ef4e2b9633b5449ed62de2c277833d51 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Brendon Cahoon254f8892016-07-29 16:44:44 +00006//
7//===----------------------------------------------------------------------===//
8//
9// An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
10//
Brendon Cahoon254f8892016-07-29 16:44:44 +000011// This SMS implementation is a target-independent back-end pass. When enabled,
12// the pass runs just prior to the register allocation pass, while the machine
13// IR is in SSA form. If software pipelining is successful, then the original
14// loop is replaced by the optimized loop. The optimized loop contains one or
15// more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
16// the instructions cannot be scheduled in a given MII, we increase the MII by
17// one and try again.
18//
19// The SMS implementation is an extension of the ScheduleDAGInstrs class. We
20// represent loop carried dependences in the DAG as order edges to the Phi
21// nodes. We also perform several passes over the DAG to eliminate unnecessary
22// edges that inhibit the ability to pipeline. The implementation uses the
23// DFAPacketizer class to compute the minimum initiation interval and the check
24// where an instruction may be inserted in the pipelined schedule.
25//
26// In order for the SMS pass to work, several target specific hooks need to be
27// implemented to get information about the loop structure and to rewrite
28// instructions.
29//
30//===----------------------------------------------------------------------===//
31
Eugene Zelenkocdc71612016-08-11 17:20:18 +000032#include "llvm/ADT/ArrayRef.h"
33#include "llvm/ADT/BitVector.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000034#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/MapVector.h"
36#include "llvm/ADT/PriorityQueue.h"
37#include "llvm/ADT/SetVector.h"
38#include "llvm/ADT/SmallPtrSet.h"
39#include "llvm/ADT/SmallSet.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000040#include "llvm/ADT/SmallVector.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000041#include "llvm/ADT/Statistic.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000042#include "llvm/ADT/iterator_range.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000043#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000044#include "llvm/Analysis/MemoryLocation.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000045#include "llvm/Analysis/ValueTracking.h"
46#include "llvm/CodeGen/DFAPacketizer.h"
Matthias Braunf8422972017-12-13 02:51:04 +000047#include "llvm/CodeGen/LiveIntervals.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000048#include "llvm/CodeGen/MachineBasicBlock.h"
49#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000050#include "llvm/CodeGen/MachineFunction.h"
51#include "llvm/CodeGen/MachineFunctionPass.h"
52#include "llvm/CodeGen/MachineInstr.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000053#include "llvm/CodeGen/MachineInstrBuilder.h"
54#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000055#include "llvm/CodeGen/MachineMemOperand.h"
56#include "llvm/CodeGen/MachineOperand.h"
Adrian Prantlfa2e3582019-01-14 17:24:11 +000057#include "llvm/CodeGen/MachinePipeliner.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000058#include "llvm/CodeGen/MachineRegisterInfo.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000059#include "llvm/CodeGen/RegisterPressure.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000060#include "llvm/CodeGen/ScheduleDAG.h"
Krzysztof Parzyszek88391242016-12-22 19:21:20 +000061#include "llvm/CodeGen/ScheduleDAGMutation.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000062#include "llvm/CodeGen/TargetOpcodes.h"
63#include "llvm/CodeGen/TargetRegisterInfo.h"
64#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000065#include "llvm/Config/llvm-config.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000066#include "llvm/IR/Attributes.h"
67#include "llvm/IR/DebugLoc.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000068#include "llvm/IR/Function.h"
69#include "llvm/MC/LaneBitmask.h"
70#include "llvm/MC/MCInstrDesc.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000071#include "llvm/MC/MCInstrItineraries.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000072#include "llvm/MC/MCRegisterInfo.h"
73#include "llvm/Pass.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000074#include "llvm/Support/CommandLine.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000075#include "llvm/Support/Compiler.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000076#include "llvm/Support/Debug.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000077#include "llvm/Support/MathExtras.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000078#include "llvm/Support/raw_ostream.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000079#include <algorithm>
80#include <cassert>
Brendon Cahoon254f8892016-07-29 16:44:44 +000081#include <climits>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000082#include <cstdint>
Brendon Cahoon254f8892016-07-29 16:44:44 +000083#include <deque>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000084#include <functional>
85#include <iterator>
Brendon Cahoon254f8892016-07-29 16:44:44 +000086#include <map>
Eugene Zelenko32a40562017-09-11 23:00:48 +000087#include <memory>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000088#include <tuple>
89#include <utility>
90#include <vector>
Brendon Cahoon254f8892016-07-29 16:44:44 +000091
92using namespace llvm;
93
94#define DEBUG_TYPE "pipeliner"
95
96STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
97STATISTIC(NumPipelined, "Number of loops software pipelined");
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +000098STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
Jinsong Ji18e7bf52019-05-31 15:35:19 +000099STATISTIC(NumFailBranch, "Pipeliner abort due to unknown branch");
100STATISTIC(NumFailLoop, "Pipeliner abort due to unsupported loop");
101STATISTIC(NumFailPreheader, "Pipeliner abort due to missing preheader");
102STATISTIC(NumFailLargeMaxMII, "Pipeliner abort due to MaxMII too large");
103STATISTIC(NumFailZeroMII, "Pipeliner abort due to zero MII");
104STATISTIC(NumFailNoSchedule, "Pipeliner abort due to no schedule found");
105STATISTIC(NumFailZeroStage, "Pipeliner abort due to zero stage");
106STATISTIC(NumFailLargeMaxStage, "Pipeliner abort due to too many stages");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000107
108/// A command line option to turn software pipelining on or off.
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000109static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
110 cl::ZeroOrMore,
111 cl::desc("Enable Software Pipelining"));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000112
113/// A command line option to enable SWP at -Os.
114static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
115 cl::desc("Enable SWP at Os."), cl::Hidden,
116 cl::init(false));
117
118/// A command line argument to limit minimum initial interval for pipelining.
119static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
Hiroshi Inoue8f976ba2018-01-17 12:29:38 +0000120 cl::desc("Size limit for the MII."),
Brendon Cahoon254f8892016-07-29 16:44:44 +0000121 cl::Hidden, cl::init(27));
122
123/// A command line argument to limit the number of stages in the pipeline.
124static cl::opt<int>
125 SwpMaxStages("pipeliner-max-stages",
126 cl::desc("Maximum stages allowed in the generated scheduled."),
127 cl::Hidden, cl::init(3));
128
129/// A command line option to disable the pruning of chain dependences due to
130/// an unrelated Phi.
131static cl::opt<bool>
132 SwpPruneDeps("pipeliner-prune-deps",
133 cl::desc("Prune dependences between unrelated Phi nodes."),
134 cl::Hidden, cl::init(true));
135
136/// A command line option to disable the pruning of loop carried order
137/// dependences.
138static cl::opt<bool>
139 SwpPruneLoopCarried("pipeliner-prune-loop-carried",
140 cl::desc("Prune loop carried order dependences."),
141 cl::Hidden, cl::init(true));
142
143#ifndef NDEBUG
144static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
145#endif
146
147static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
148 cl::ReallyHidden, cl::init(false),
149 cl::ZeroOrMore, cl::desc("Ignore RecMII"));
150
Jinsong Jiba438402019-06-18 20:24:49 +0000151static cl::opt<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden,
152 cl::init(false));
153static cl::opt<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden,
154 cl::init(false));
155
Adrian Prantlfa2e3582019-01-14 17:24:11 +0000156namespace llvm {
157
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +0000158// A command line option to enable the CopyToPhi DAG mutation.
Adrian Prantlfa2e3582019-01-14 17:24:11 +0000159cl::opt<bool>
Aleksandr Urakov00d4c382018-10-23 14:27:45 +0000160 SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
161 cl::init(true), cl::ZeroOrMore,
162 cl::desc("Enable CopyToPhi DAG Mutation"));
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +0000163
Adrian Prantlfa2e3582019-01-14 17:24:11 +0000164} // end namespace llvm
Brendon Cahoon254f8892016-07-29 16:44:44 +0000165
166unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
167char MachinePipeliner::ID = 0;
168#ifndef NDEBUG
169int MachinePipeliner::NumTries = 0;
170#endif
171char &llvm::MachinePipelinerID = MachinePipeliner::ID;
Eugene Zelenko32a40562017-09-11 23:00:48 +0000172
Matthias Braun1527baa2017-05-25 21:26:32 +0000173INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
Brendon Cahoon254f8892016-07-29 16:44:44 +0000174 "Modulo Software Pipelining", false, false)
175INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
176INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
177INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
178INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Matthias Braun1527baa2017-05-25 21:26:32 +0000179INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
Brendon Cahoon254f8892016-07-29 16:44:44 +0000180 "Modulo Software Pipelining", false, false)
181
182/// The "main" function for implementing Swing Modulo Scheduling.
183bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000184 if (skipFunction(mf.getFunction()))
Brendon Cahoon254f8892016-07-29 16:44:44 +0000185 return false;
186
187 if (!EnableSWP)
188 return false;
189
Matthias Braunf1caa282017-12-15 22:22:58 +0000190 if (mf.getFunction().getAttributes().hasAttribute(
Reid Klecknerb5180542017-03-21 16:57:19 +0000191 AttributeList::FunctionIndex, Attribute::OptimizeForSize) &&
Brendon Cahoon254f8892016-07-29 16:44:44 +0000192 !EnableSWPOptSize.getPosition())
193 return false;
194
Jinsong Jief2d6d92019-06-11 17:40:39 +0000195 if (!mf.getSubtarget().enableMachinePipeliner())
196 return false;
197
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000198 // Cannot pipeline loops without instruction itineraries if we are using
199 // DFA for the pipeliner.
200 if (mf.getSubtarget().useDFAforSMS() &&
201 (!mf.getSubtarget().getInstrItineraryData() ||
202 mf.getSubtarget().getInstrItineraryData()->isEmpty()))
203 return false;
204
Brendon Cahoon254f8892016-07-29 16:44:44 +0000205 MF = &mf;
206 MLI = &getAnalysis<MachineLoopInfo>();
207 MDT = &getAnalysis<MachineDominatorTree>();
208 TII = MF->getSubtarget().getInstrInfo();
209 RegClassInfo.runOnMachineFunction(*MF);
210
211 for (auto &L : *MLI)
212 scheduleLoop(*L);
213
214 return false;
215}
216
217/// Attempt to perform the SMS algorithm on the specified loop. This function is
218/// the main entry point for the algorithm. The function identifies candidate
219/// loops, calculates the minimum initiation interval, and attempts to schedule
220/// the loop.
221bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
222 bool Changed = false;
223 for (auto &InnerLoop : L)
224 Changed |= scheduleLoop(*InnerLoop);
225
226#ifndef NDEBUG
227 // Stop trying after reaching the limit (if any).
228 int Limit = SwpLoopLimit;
229 if (Limit >= 0) {
230 if (NumTries >= SwpLoopLimit)
231 return Changed;
232 NumTries++;
233 }
234#endif
235
Brendon Cahoon59d99732019-01-23 03:26:10 +0000236 setPragmaPipelineOptions(L);
237 if (!canPipelineLoop(L)) {
238 LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000239 return Changed;
Brendon Cahoon59d99732019-01-23 03:26:10 +0000240 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000241
242 ++NumTrytoPipeline;
243
244 Changed = swingModuloScheduler(L);
245
246 return Changed;
247}
248
Brendon Cahoon59d99732019-01-23 03:26:10 +0000249void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) {
250 MachineBasicBlock *LBLK = L.getTopBlock();
251
252 if (LBLK == nullptr)
253 return;
254
255 const BasicBlock *BBLK = LBLK->getBasicBlock();
256 if (BBLK == nullptr)
257 return;
258
259 const Instruction *TI = BBLK->getTerminator();
260 if (TI == nullptr)
261 return;
262
263 MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop);
264 if (LoopID == nullptr)
265 return;
266
267 assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
268 assert(LoopID->getOperand(0) == LoopID && "invalid loop");
269
270 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
271 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
272
273 if (MD == nullptr)
274 continue;
275
276 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
277
278 if (S == nullptr)
279 continue;
280
281 if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
282 assert(MD->getNumOperands() == 2 &&
283 "Pipeline initiation interval hint metadata should have two operands.");
284 II_setByPragma =
285 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
286 assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
287 } else if (S->getString() == "llvm.loop.pipeline.disable") {
288 disabledByPragma = true;
289 }
290 }
291}
292
Brendon Cahoon254f8892016-07-29 16:44:44 +0000293/// Return true if the loop can be software pipelined. The algorithm is
294/// restricted to loops with a single basic block. Make sure that the
295/// branch in the loop can be analyzed.
296bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
297 if (L.getNumBlocks() != 1)
298 return false;
299
Brendon Cahoon59d99732019-01-23 03:26:10 +0000300 if (disabledByPragma)
301 return false;
302
Brendon Cahoon254f8892016-07-29 16:44:44 +0000303 // Check if the branch can't be understood because we can't do pipelining
304 // if that's the case.
305 LI.TBB = nullptr;
306 LI.FBB = nullptr;
307 LI.BrCond.clear();
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000308 if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) {
309 LLVM_DEBUG(
310 dbgs() << "Unable to analyzeBranch, can NOT pipeline current Loop\n");
311 NumFailBranch++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000312 return false;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000313 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000314
315 LI.LoopInductionVar = nullptr;
316 LI.LoopCompare = nullptr;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000317 if (TII->analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare)) {
318 LLVM_DEBUG(
319 dbgs() << "Unable to analyzeLoop, can NOT pipeline current Loop\n");
320 NumFailLoop++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000321 return false;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000322 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000323
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000324 if (!L.getLoopPreheader()) {
325 LLVM_DEBUG(
326 dbgs() << "Preheader not found, can NOT pipeline current Loop\n");
327 NumFailPreheader++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000328 return false;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000329 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000330
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000331 // Remove any subregisters from inputs to phi nodes.
332 preprocessPhiNodes(*L.getHeader());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000333 return true;
334}
335
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000336void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
337 MachineRegisterInfo &MRI = MF->getRegInfo();
338 SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
339
340 for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) {
341 MachineOperand &DefOp = PI.getOperand(0);
342 assert(DefOp.getSubReg() == 0);
343 auto *RC = MRI.getRegClass(DefOp.getReg());
344
345 for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
346 MachineOperand &RegOp = PI.getOperand(i);
347 if (RegOp.getSubReg() == 0)
348 continue;
349
350 // If the operand uses a subregister, replace it with a new register
351 // without subregisters, and generate a copy to the new register.
352 unsigned NewReg = MRI.createVirtualRegister(RC);
353 MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
354 MachineBasicBlock::iterator At = PredB.getFirstTerminator();
355 const DebugLoc &DL = PredB.findDebugLoc(At);
356 auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
357 .addReg(RegOp.getReg(), getRegState(RegOp),
358 RegOp.getSubReg());
359 Slots.insertMachineInstrInMaps(*Copy);
360 RegOp.setReg(NewReg);
361 RegOp.setSubReg(0);
362 }
363 }
364}
365
Brendon Cahoon254f8892016-07-29 16:44:44 +0000366/// The SMS algorithm consists of the following main steps:
367/// 1. Computation and analysis of the dependence graph.
368/// 2. Ordering of the nodes (instructions).
369/// 3. Attempt to Schedule the loop.
370bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
371 assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
372
Brendon Cahoon59d99732019-01-23 03:26:10 +0000373 SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo,
374 II_setByPragma);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000375
376 MachineBasicBlock *MBB = L.getHeader();
377 // The kernel should not include any terminator instructions. These
378 // will be added back later.
379 SMS.startBlock(MBB);
380
381 // Compute the number of 'real' instructions in the basic block by
382 // ignoring terminators.
383 unsigned size = MBB->size();
384 for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
385 E = MBB->instr_end();
386 I != E; ++I, --size)
387 ;
388
389 SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
390 SMS.schedule();
391 SMS.exitRegion();
392
393 SMS.finishBlock();
394 return SMS.hasNewSchedule();
395}
396
Brendon Cahoon59d99732019-01-23 03:26:10 +0000397void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
398 if (II_setByPragma > 0)
399 MII = II_setByPragma;
400 else
401 MII = std::max(ResMII, RecMII);
402}
403
404void SwingSchedulerDAG::setMAX_II() {
405 if (II_setByPragma > 0)
406 MAX_II = II_setByPragma;
407 else
408 MAX_II = MII + 10;
409}
410
Brendon Cahoon254f8892016-07-29 16:44:44 +0000411/// We override the schedule function in ScheduleDAGInstrs to implement the
412/// scheduling part of the Swing Modulo Scheduling algorithm.
413void SwingSchedulerDAG::schedule() {
414 AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
415 buildSchedGraph(AA);
416 addLoopCarriedDependences(AA);
417 updatePhiDependences();
418 Topo.InitDAGTopologicalSorting();
419 changeDependences();
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +0000420 postprocessDAG();
Matthias Braun726e12c2018-09-19 00:23:35 +0000421 LLVM_DEBUG(dump());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000422
423 NodeSetType NodeSets;
424 findCircuits(NodeSets);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +0000425 NodeSetType Circuits = NodeSets;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000426
427 // Calculate the MII.
428 unsigned ResMII = calculateResMII();
429 unsigned RecMII = calculateRecMII(NodeSets);
430
431 fuseRecs(NodeSets);
432
433 // This flag is used for testing and can cause correctness problems.
434 if (SwpIgnoreRecMII)
435 RecMII = 0;
436
Brendon Cahoon59d99732019-01-23 03:26:10 +0000437 setMII(ResMII, RecMII);
438 setMAX_II();
439
440 LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
441 << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000442
443 // Can't schedule a loop without a valid MII.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000444 if (MII == 0) {
445 LLVM_DEBUG(
446 dbgs()
447 << "0 is not a valid Minimal Initiation Interval, can NOT schedule\n");
448 NumFailZeroMII++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000449 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000450 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000451
452 // Don't pipeline large loops.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000453 if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) {
454 LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
455 << ", we don't pipleline large loops\n");
456 NumFailLargeMaxMII++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000457 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000458 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000459
460 computeNodeFunctions(NodeSets);
461
462 registerPressureFilter(NodeSets);
463
464 colocateNodeSets(NodeSets);
465
466 checkNodeSets(NodeSets);
467
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000468 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +0000469 for (auto &I : NodeSets) {
470 dbgs() << " Rec NodeSet ";
471 I.dump();
472 }
473 });
474
Fangrui Songefd94c52019-04-23 14:51:27 +0000475 llvm::stable_sort(NodeSets, std::greater<NodeSet>());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000476
477 groupRemainingNodes(NodeSets);
478
479 removeDuplicateNodes(NodeSets);
480
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000481 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +0000482 for (auto &I : NodeSets) {
483 dbgs() << " NodeSet ";
484 I.dump();
485 }
486 });
487
488 computeNodeOrder(NodeSets);
489
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +0000490 // check for node order issues
491 checkValidNodeOrder(Circuits);
492
Brendon Cahoon254f8892016-07-29 16:44:44 +0000493 SMSchedule Schedule(Pass.MF);
494 Scheduled = schedulePipeline(Schedule);
495
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000496 if (!Scheduled){
497 LLVM_DEBUG(dbgs() << "No schedule found, return\n");
498 NumFailNoSchedule++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000499 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000500 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000501
502 unsigned numStages = Schedule.getMaxStageCount();
503 // No need to generate pipeline if there are no overlapped iterations.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000504 if (numStages == 0) {
505 LLVM_DEBUG(
506 dbgs() << "No overlapped iterations, no need to generate pipeline\n");
507 NumFailZeroStage++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000508 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000509 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000510 // Check that the maximum stage count is less than user-defined limit.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000511 if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) {
512 LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages
513 << " : too many stages, abort\n");
514 NumFailLargeMaxStage++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000515 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000516 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000517
518 generatePipelinedLoop(Schedule);
519 ++NumPipelined;
520}
521
522/// Clean up after the software pipeliner runs.
523void SwingSchedulerDAG::finishBlock() {
524 for (MachineInstr *I : NewMIs)
525 MF.DeleteMachineInstr(I);
526 NewMIs.clear();
527
528 // Call the superclass.
529 ScheduleDAGInstrs::finishBlock();
530}
531
532/// Return the register values for the operands of a Phi instruction.
533/// This function assume the instruction is a Phi.
534static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
535 unsigned &InitVal, unsigned &LoopVal) {
536 assert(Phi.isPHI() && "Expecting a Phi.");
537
538 InitVal = 0;
539 LoopVal = 0;
540 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
541 if (Phi.getOperand(i + 1).getMBB() != Loop)
542 InitVal = Phi.getOperand(i).getReg();
Simon Pilgrimfbfb19b2017-03-16 19:52:00 +0000543 else
Brendon Cahoon254f8892016-07-29 16:44:44 +0000544 LoopVal = Phi.getOperand(i).getReg();
545
546 assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
547}
548
549/// Return the Phi register value that comes from the incoming block.
550static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
551 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
552 if (Phi.getOperand(i + 1).getMBB() != LoopBB)
553 return Phi.getOperand(i).getReg();
554 return 0;
555}
556
Hiroshi Inoue8f976ba2018-01-17 12:29:38 +0000557/// Return the Phi register value that comes the loop block.
Brendon Cahoon254f8892016-07-29 16:44:44 +0000558static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
559 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
560 if (Phi.getOperand(i + 1).getMBB() == LoopBB)
561 return Phi.getOperand(i).getReg();
562 return 0;
563}
564
565/// Return true if SUb can be reached from SUa following the chain edges.
566static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
567 SmallPtrSet<SUnit *, 8> Visited;
568 SmallVector<SUnit *, 8> Worklist;
569 Worklist.push_back(SUa);
570 while (!Worklist.empty()) {
571 const SUnit *SU = Worklist.pop_back_val();
572 for (auto &SI : SU->Succs) {
573 SUnit *SuccSU = SI.getSUnit();
574 if (SI.getKind() == SDep::Order) {
575 if (Visited.count(SuccSU))
576 continue;
577 if (SuccSU == SUb)
578 return true;
579 Worklist.push_back(SuccSU);
580 Visited.insert(SuccSU);
581 }
582 }
583 }
584 return false;
585}
586
587/// Return true if the instruction causes a chain between memory
588/// references before and after it.
589static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
Ulrich Weigand6c5d5ce2019-06-05 22:33:10 +0000590 return MI.isCall() || MI.mayRaiseFPException() ||
591 MI.hasUnmodeledSideEffects() ||
Brendon Cahoon254f8892016-07-29 16:44:44 +0000592 (MI.hasOrderedMemoryRef() &&
Justin Lebard98cf002016-09-10 01:03:20 +0000593 (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000594}
595
596/// Return the underlying objects for the memory references of an instruction.
597/// This function calls the code in ValueTracking, but first checks that the
598/// instruction has a memory operand.
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000599static void getUnderlyingObjects(const MachineInstr *MI,
600 SmallVectorImpl<const Value *> &Objs,
Brendon Cahoon254f8892016-07-29 16:44:44 +0000601 const DataLayout &DL) {
602 if (!MI->hasOneMemOperand())
603 return;
604 MachineMemOperand *MM = *MI->memoperands_begin();
605 if (!MM->getValue())
606 return;
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000607 GetUnderlyingObjects(MM->getValue(), Objs, DL);
608 for (const Value *V : Objs) {
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000609 if (!isIdentifiedObject(V)) {
610 Objs.clear();
611 return;
612 }
613 Objs.push_back(V);
614 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000615}
616
617/// Add a chain edge between a load and store if the store can be an
618/// alias of the load on a subsequent iteration, i.e., a loop carried
619/// dependence. This code is very similar to the code in ScheduleDAGInstrs
620/// but that code doesn't create loop carried dependences.
621void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000622 MapVector<const Value *, SmallVector<SUnit *, 4>> PendingLoads;
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000623 Value *UnknownValue =
624 UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000625 for (auto &SU : SUnits) {
626 MachineInstr &MI = *SU.getInstr();
627 if (isDependenceBarrier(MI, AA))
628 PendingLoads.clear();
629 else if (MI.mayLoad()) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000630 SmallVector<const Value *, 4> Objs;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000631 getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000632 if (Objs.empty())
633 Objs.push_back(UnknownValue);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000634 for (auto V : Objs) {
635 SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
636 SUs.push_back(&SU);
637 }
638 } else if (MI.mayStore()) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000639 SmallVector<const Value *, 4> Objs;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000640 getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000641 if (Objs.empty())
642 Objs.push_back(UnknownValue);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000643 for (auto V : Objs) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000644 MapVector<const Value *, SmallVector<SUnit *, 4>>::iterator I =
Brendon Cahoon254f8892016-07-29 16:44:44 +0000645 PendingLoads.find(V);
646 if (I == PendingLoads.end())
647 continue;
648 for (auto Load : I->second) {
649 if (isSuccOrder(Load, &SU))
650 continue;
651 MachineInstr &LdMI = *Load->getInstr();
652 // First, perform the cheaper check that compares the base register.
653 // If they are the same and the load offset is less than the store
654 // offset, then mark the dependence as loop carried potentially.
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +0000655 const MachineOperand *BaseOp1, *BaseOp2;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000656 int64_t Offset1, Offset2;
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +0000657 if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1, TRI) &&
658 TII->getMemOperandWithOffset(MI, BaseOp2, Offset2, TRI)) {
659 if (BaseOp1->isIdenticalTo(*BaseOp2) &&
660 (int)Offset1 < (int)Offset2) {
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000661 assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI, AA) &&
662 "What happened to the chain edge?");
663 SDep Dep(Load, SDep::Barrier);
664 Dep.setLatency(1);
665 SU.addPred(Dep);
666 continue;
667 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000668 }
669 // Second, the more expensive check that uses alias analysis on the
670 // base registers. If they alias, and the load offset is less than
671 // the store offset, the mark the dependence as loop carried.
672 if (!AA) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000673 SDep Dep(Load, SDep::Barrier);
674 Dep.setLatency(1);
675 SU.addPred(Dep);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000676 continue;
677 }
678 MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
679 MachineMemOperand *MMO2 = *MI.memoperands_begin();
680 if (!MMO1->getValue() || !MMO2->getValue()) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000681 SDep Dep(Load, SDep::Barrier);
682 Dep.setLatency(1);
683 SU.addPred(Dep);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000684 continue;
685 }
686 if (MMO1->getValue() == MMO2->getValue() &&
687 MMO1->getOffset() <= MMO2->getOffset()) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000688 SDep Dep(Load, SDep::Barrier);
689 Dep.setLatency(1);
690 SU.addPred(Dep);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000691 continue;
692 }
693 AliasResult AAResult = AA->alias(
George Burgess IV6ef80022018-10-10 21:28:44 +0000694 MemoryLocation(MMO1->getValue(), LocationSize::unknown(),
Brendon Cahoon254f8892016-07-29 16:44:44 +0000695 MMO1->getAAInfo()),
George Burgess IV6ef80022018-10-10 21:28:44 +0000696 MemoryLocation(MMO2->getValue(), LocationSize::unknown(),
Brendon Cahoon254f8892016-07-29 16:44:44 +0000697 MMO2->getAAInfo()));
698
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000699 if (AAResult != NoAlias) {
700 SDep Dep(Load, SDep::Barrier);
701 Dep.setLatency(1);
702 SU.addPred(Dep);
703 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000704 }
705 }
706 }
707 }
708}
709
710/// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
711/// processes dependences for PHIs. This function adds true dependences
712/// from a PHI to a use, and a loop carried dependence from the use to the
713/// PHI. The loop carried dependence is represented as an anti dependence
714/// edge. This function also removes chain dependences between unrelated
715/// PHIs.
716void SwingSchedulerDAG::updatePhiDependences() {
717 SmallVector<SDep, 4> RemoveDeps;
718 const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
719
720 // Iterate over each DAG node.
721 for (SUnit &I : SUnits) {
722 RemoveDeps.clear();
723 // Set to true if the instruction has an operand defined by a Phi.
724 unsigned HasPhiUse = 0;
725 unsigned HasPhiDef = 0;
726 MachineInstr *MI = I.getInstr();
727 // Iterate over each operand, and we process the definitions.
728 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
729 MOE = MI->operands_end();
730 MOI != MOE; ++MOI) {
731 if (!MOI->isReg())
732 continue;
733 unsigned Reg = MOI->getReg();
734 if (MOI->isDef()) {
735 // If the register is used by a Phi, then create an anti dependence.
736 for (MachineRegisterInfo::use_instr_iterator
737 UI = MRI.use_instr_begin(Reg),
738 UE = MRI.use_instr_end();
739 UI != UE; ++UI) {
740 MachineInstr *UseMI = &*UI;
741 SUnit *SU = getSUnit(UseMI);
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000742 if (SU != nullptr && UseMI->isPHI()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +0000743 if (!MI->isPHI()) {
744 SDep Dep(SU, SDep::Anti, Reg);
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000745 Dep.setLatency(1);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000746 I.addPred(Dep);
747 } else {
748 HasPhiDef = Reg;
749 // Add a chain edge to a dependent Phi that isn't an existing
750 // predecessor.
751 if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
752 I.addPred(SDep(SU, SDep::Barrier));
753 }
754 }
755 }
756 } else if (MOI->isUse()) {
757 // If the register is defined by a Phi, then create a true dependence.
758 MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000759 if (DefMI == nullptr)
Brendon Cahoon254f8892016-07-29 16:44:44 +0000760 continue;
761 SUnit *SU = getSUnit(DefMI);
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000762 if (SU != nullptr && DefMI->isPHI()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +0000763 if (!MI->isPHI()) {
764 SDep Dep(SU, SDep::Data, Reg);
765 Dep.setLatency(0);
766 ST.adjustSchedDependency(SU, &I, Dep);
767 I.addPred(Dep);
768 } else {
769 HasPhiUse = Reg;
770 // Add a chain edge to a dependent Phi that isn't an existing
771 // predecessor.
772 if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
773 I.addPred(SDep(SU, SDep::Barrier));
774 }
775 }
776 }
777 }
778 // Remove order dependences from an unrelated Phi.
779 if (!SwpPruneDeps)
780 continue;
781 for (auto &PI : I.Preds) {
782 MachineInstr *PMI = PI.getSUnit()->getInstr();
783 if (PMI->isPHI() && PI.getKind() == SDep::Order) {
784 if (I.getInstr()->isPHI()) {
785 if (PMI->getOperand(0).getReg() == HasPhiUse)
786 continue;
787 if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
788 continue;
789 }
790 RemoveDeps.push_back(PI);
791 }
792 }
793 for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
794 I.removePred(RemoveDeps[i]);
795 }
796}
797
798/// Iterate over each DAG node and see if we can change any dependences
799/// in order to reduce the recurrence MII.
800void SwingSchedulerDAG::changeDependences() {
801 // See if an instruction can use a value from the previous iteration.
802 // If so, we update the base and offset of the instruction and change
803 // the dependences.
804 for (SUnit &I : SUnits) {
805 unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
806 int64_t NewOffset = 0;
807 if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
808 NewOffset))
809 continue;
810
811 // Get the MI and SUnit for the instruction that defines the original base.
812 unsigned OrigBase = I.getInstr()->getOperand(BasePos).getReg();
813 MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
814 if (!DefMI)
815 continue;
816 SUnit *DefSU = getSUnit(DefMI);
817 if (!DefSU)
818 continue;
819 // Get the MI and SUnit for the instruction that defins the new base.
820 MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
821 if (!LastMI)
822 continue;
823 SUnit *LastSU = getSUnit(LastMI);
824 if (!LastSU)
825 continue;
826
827 if (Topo.IsReachable(&I, LastSU))
828 continue;
829
830 // Remove the dependence. The value now depends on a prior iteration.
831 SmallVector<SDep, 4> Deps;
832 for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E;
833 ++P)
834 if (P->getSUnit() == DefSU)
835 Deps.push_back(*P);
836 for (int i = 0, e = Deps.size(); i != e; i++) {
837 Topo.RemovePred(&I, Deps[i].getSUnit());
838 I.removePred(Deps[i]);
839 }
840 // Remove the chain dependence between the instructions.
841 Deps.clear();
842 for (auto &P : LastSU->Preds)
843 if (P.getSUnit() == &I && P.getKind() == SDep::Order)
844 Deps.push_back(P);
845 for (int i = 0, e = Deps.size(); i != e; i++) {
846 Topo.RemovePred(LastSU, Deps[i].getSUnit());
847 LastSU->removePred(Deps[i]);
848 }
849
850 // Add a dependence between the new instruction and the instruction
851 // that defines the new base.
852 SDep Dep(&I, SDep::Anti, NewBase);
Sumanth Gundapaneni8916e432018-10-11 19:42:46 +0000853 Topo.AddPred(LastSU, &I);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000854 LastSU->addPred(Dep);
855
856 // Remember the base and offset information so that we can update the
857 // instruction during code generation.
858 InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
859 }
860}
861
862namespace {
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000863
Brendon Cahoon254f8892016-07-29 16:44:44 +0000864// FuncUnitSorter - Comparison operator used to sort instructions by
865// the number of functional unit choices.
866struct FuncUnitSorter {
867 const InstrItineraryData *InstrItins;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000868 const MCSubtargetInfo *STI;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000869 DenseMap<unsigned, unsigned> Resources;
870
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000871 FuncUnitSorter(const TargetSubtargetInfo &TSI)
872 : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
Eugene Zelenko32a40562017-09-11 23:00:48 +0000873
Brendon Cahoon254f8892016-07-29 16:44:44 +0000874 // Compute the number of functional unit alternatives needed
875 // at each stage, and take the minimum value. We prioritize the
876 // instructions by the least number of choices first.
877 unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const {
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000878 unsigned SchedClass = Inst->getDesc().getSchedClass();
Brendon Cahoon254f8892016-07-29 16:44:44 +0000879 unsigned min = UINT_MAX;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000880 if (InstrItins && !InstrItins->isEmpty()) {
881 for (const InstrStage &IS :
882 make_range(InstrItins->beginStage(SchedClass),
883 InstrItins->endStage(SchedClass))) {
884 unsigned funcUnits = IS.getUnits();
885 unsigned numAlternatives = countPopulation(funcUnits);
886 if (numAlternatives < min) {
887 min = numAlternatives;
888 F = funcUnits;
889 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000890 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000891 return min;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000892 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000893 if (STI && STI->getSchedModel().hasInstrSchedModel()) {
894 const MCSchedClassDesc *SCDesc =
895 STI->getSchedModel().getSchedClassDesc(SchedClass);
896 if (!SCDesc->isValid())
897 // No valid Schedule Class Desc for schedClass, should be
898 // Pseudo/PostRAPseudo
899 return min;
900
901 for (const MCWriteProcResEntry &PRE :
902 make_range(STI->getWriteProcResBegin(SCDesc),
903 STI->getWriteProcResEnd(SCDesc))) {
904 if (!PRE.Cycles)
905 continue;
906 const MCProcResourceDesc *ProcResource =
907 STI->getSchedModel().getProcResource(PRE.ProcResourceIdx);
908 unsigned NumUnits = ProcResource->NumUnits;
909 if (NumUnits < min) {
910 min = NumUnits;
911 F = PRE.ProcResourceIdx;
912 }
913 }
914 return min;
915 }
916 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000917 }
918
919 // Compute the critical resources needed by the instruction. This
920 // function records the functional units needed by instructions that
921 // must use only one functional unit. We use this as a tie breaker
922 // for computing the resource MII. The instrutions that require
923 // the same, highly used, functional unit have high priority.
924 void calcCriticalResources(MachineInstr &MI) {
925 unsigned SchedClass = MI.getDesc().getSchedClass();
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000926 if (InstrItins && !InstrItins->isEmpty()) {
927 for (const InstrStage &IS :
928 make_range(InstrItins->beginStage(SchedClass),
929 InstrItins->endStage(SchedClass))) {
930 unsigned FuncUnits = IS.getUnits();
931 if (countPopulation(FuncUnits) == 1)
932 Resources[FuncUnits]++;
933 }
934 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000935 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000936 if (STI && STI->getSchedModel().hasInstrSchedModel()) {
937 const MCSchedClassDesc *SCDesc =
938 STI->getSchedModel().getSchedClassDesc(SchedClass);
939 if (!SCDesc->isValid())
940 // No valid Schedule Class Desc for schedClass, should be
941 // Pseudo/PostRAPseudo
942 return;
943
944 for (const MCWriteProcResEntry &PRE :
945 make_range(STI->getWriteProcResBegin(SCDesc),
946 STI->getWriteProcResEnd(SCDesc))) {
947 if (!PRE.Cycles)
948 continue;
949 Resources[PRE.ProcResourceIdx]++;
950 }
951 return;
952 }
953 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000954 }
955
Brendon Cahoon254f8892016-07-29 16:44:44 +0000956 /// Return true if IS1 has less priority than IS2.
957 bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
958 unsigned F1 = 0, F2 = 0;
959 unsigned MFUs1 = minFuncUnits(IS1, F1);
960 unsigned MFUs2 = minFuncUnits(IS2, F2);
961 if (MFUs1 == 1 && MFUs2 == 1)
962 return Resources.lookup(F1) < Resources.lookup(F2);
963 return MFUs1 > MFUs2;
964 }
965};
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000966
967} // end anonymous namespace
Brendon Cahoon254f8892016-07-29 16:44:44 +0000968
969/// Calculate the resource constrained minimum initiation interval for the
970/// specified loop. We use the DFA to model the resources needed for
971/// each instruction, and we ignore dependences. A different DFA is created
972/// for each cycle that is required. When adding a new instruction, we attempt
973/// to add it to each existing DFA, until a legal space is found. If the
974/// instruction cannot be reserved in an existing DFA, we create a new one.
975unsigned SwingSchedulerDAG::calculateResMII() {
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000976
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000977 LLVM_DEBUG(dbgs() << "calculateResMII:\n");
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000978 SmallVector<ResourceManager*, 8> Resources;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000979 MachineBasicBlock *MBB = Loop.getHeader();
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000980 Resources.push_back(new ResourceManager(&MF.getSubtarget()));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000981
982 // Sort the instructions by the number of available choices for scheduling,
983 // least to most. Use the number of critical resources as the tie breaker.
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000984 FuncUnitSorter FUS = FuncUnitSorter(MF.getSubtarget());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000985 for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
986 E = MBB->getFirstTerminator();
987 I != E; ++I)
988 FUS.calcCriticalResources(*I);
989 PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
990 FuncUnitOrder(FUS);
991
992 for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
993 E = MBB->getFirstTerminator();
994 I != E; ++I)
995 FuncUnitOrder.push(&*I);
996
997 while (!FuncUnitOrder.empty()) {
998 MachineInstr *MI = FuncUnitOrder.top();
999 FuncUnitOrder.pop();
1000 if (TII->isZeroCost(MI->getOpcode()))
1001 continue;
1002 // Attempt to reserve the instruction in an existing DFA. At least one
1003 // DFA is needed for each cycle.
1004 unsigned NumCycles = getSUnit(MI)->Latency;
1005 unsigned ReservedCycles = 0;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00001006 SmallVectorImpl<ResourceManager *>::iterator RI = Resources.begin();
1007 SmallVectorImpl<ResourceManager *>::iterator RE = Resources.end();
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001008 LLVM_DEBUG({
1009 dbgs() << "Trying to reserve resource for " << NumCycles
1010 << " cycles for \n";
1011 MI->dump();
1012 });
Brendon Cahoon254f8892016-07-29 16:44:44 +00001013 for (unsigned C = 0; C < NumCycles; ++C)
1014 while (RI != RE) {
Jinsong Jifee855b2019-06-25 21:50:56 +00001015 if ((*RI)->canReserveResources(*MI)) {
1016 (*RI)->reserveResources(*MI);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001017 ++ReservedCycles;
1018 break;
1019 }
Jinsong Jifee855b2019-06-25 21:50:56 +00001020 RI++;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001021 }
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001022 LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
1023 << ", NumCycles:" << NumCycles << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001024 // Add new DFAs, if needed, to reserve resources.
1025 for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
Jinsong Jiba438402019-06-18 20:24:49 +00001026 LLVM_DEBUG(if (SwpDebugResource) dbgs()
1027 << "NewResource created to reserve resources"
1028 << "\n");
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00001029 ResourceManager *NewResource = new ResourceManager(&MF.getSubtarget());
Brendon Cahoon254f8892016-07-29 16:44:44 +00001030 assert(NewResource->canReserveResources(*MI) && "Reserve error.");
1031 NewResource->reserveResources(*MI);
1032 Resources.push_back(NewResource);
1033 }
1034 }
1035 int Resmii = Resources.size();
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001036 LLVM_DEBUG(dbgs() << "Retrun Res MII:" << Resmii << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001037 // Delete the memory for each of the DFAs that were created earlier.
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00001038 for (ResourceManager *RI : Resources) {
1039 ResourceManager *D = RI;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001040 delete D;
1041 }
1042 Resources.clear();
1043 return Resmii;
1044}
1045
1046/// Calculate the recurrence-constrainted minimum initiation interval.
1047/// Iterate over each circuit. Compute the delay(c) and distance(c)
1048/// for each circuit. The II needs to satisfy the inequality
1049/// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001050/// II that satisfies the inequality, and the RecMII is the maximum
Brendon Cahoon254f8892016-07-29 16:44:44 +00001051/// of those values.
1052unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1053 unsigned RecMII = 0;
1054
1055 for (NodeSet &Nodes : NodeSets) {
Eugene Zelenko32a40562017-09-11 23:00:48 +00001056 if (Nodes.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001057 continue;
1058
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00001059 unsigned Delay = Nodes.getLatency();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001060 unsigned Distance = 1;
1061
1062 // ii = ceil(delay / distance)
1063 unsigned CurMII = (Delay + Distance - 1) / Distance;
1064 Nodes.setRecMII(CurMII);
1065 if (CurMII > RecMII)
1066 RecMII = CurMII;
1067 }
1068
1069 return RecMII;
1070}
1071
1072/// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1073/// but we do this to find the circuits, and then change them back.
1074static void swapAntiDependences(std::vector<SUnit> &SUnits) {
1075 SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
1076 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1077 SUnit *SU = &SUnits[i];
1078 for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end();
1079 IP != EP; ++IP) {
1080 if (IP->getKind() != SDep::Anti)
1081 continue;
1082 DepsAdded.push_back(std::make_pair(SU, *IP));
1083 }
1084 }
1085 for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(),
1086 E = DepsAdded.end();
1087 I != E; ++I) {
1088 // Remove this anti dependency and add one in the reverse direction.
1089 SUnit *SU = I->first;
1090 SDep &D = I->second;
1091 SUnit *TargetSU = D.getSUnit();
1092 unsigned Reg = D.getReg();
1093 unsigned Lat = D.getLatency();
1094 SU->removePred(D);
1095 SDep Dep(SU, SDep::Anti, Reg);
1096 Dep.setLatency(Lat);
1097 TargetSU->addPred(Dep);
1098 }
1099}
1100
1101/// Create the adjacency structure of the nodes in the graph.
1102void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1103 SwingSchedulerDAG *DAG) {
1104 BitVector Added(SUnits.size());
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001105 DenseMap<int, int> OutputDeps;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001106 for (int i = 0, e = SUnits.size(); i != e; ++i) {
1107 Added.reset();
1108 // Add any successor to the adjacency matrix and exclude duplicates.
1109 for (auto &SI : SUnits[i].Succs) {
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001110 // Only create a back-edge on the first and last nodes of a dependence
1111 // chain. This records any chains and adds them later.
1112 if (SI.getKind() == SDep::Output) {
1113 int N = SI.getSUnit()->NodeNum;
1114 int BackEdge = i;
1115 auto Dep = OutputDeps.find(BackEdge);
1116 if (Dep != OutputDeps.end()) {
1117 BackEdge = Dep->second;
1118 OutputDeps.erase(Dep);
1119 }
1120 OutputDeps[N] = BackEdge;
1121 }
Sumanth Gundapaneniada0f512018-10-25 21:27:08 +00001122 // Do not process a boundary node, an artificial node.
1123 // A back-edge is processed only if it goes to a Phi.
1124 if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() ||
Brendon Cahoon254f8892016-07-29 16:44:44 +00001125 (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
1126 continue;
1127 int N = SI.getSUnit()->NodeNum;
1128 if (!Added.test(N)) {
1129 AdjK[i].push_back(N);
1130 Added.set(N);
1131 }
1132 }
1133 // A chain edge between a store and a load is treated as a back-edge in the
1134 // adjacency matrix.
1135 for (auto &PI : SUnits[i].Preds) {
1136 if (!SUnits[i].getInstr()->mayStore() ||
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001137 !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001138 continue;
1139 if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1140 int N = PI.getSUnit()->NodeNum;
1141 if (!Added.test(N)) {
1142 AdjK[i].push_back(N);
1143 Added.set(N);
1144 }
1145 }
1146 }
1147 }
Hiroshi Inouedad8c6a2019-01-09 05:11:10 +00001148 // Add back-edges in the adjacency matrix for the output dependences.
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001149 for (auto &OD : OutputDeps)
1150 if (!Added.test(OD.second)) {
1151 AdjK[OD.first].push_back(OD.second);
1152 Added.set(OD.second);
1153 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00001154}
1155
1156/// Identify an elementary circuit in the dependence graph starting at the
1157/// specified node.
1158bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
1159 bool HasBackedge) {
1160 SUnit *SV = &SUnits[V];
1161 bool F = false;
1162 Stack.insert(SV);
1163 Blocked.set(V);
1164
1165 for (auto W : AdjK[V]) {
1166 if (NumPaths > MaxPaths)
1167 break;
1168 if (W < S)
1169 continue;
1170 if (W == S) {
1171 if (!HasBackedge)
1172 NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
1173 F = true;
1174 ++NumPaths;
1175 break;
1176 } else if (!Blocked.test(W)) {
Sumanth Gundapaneni77418a32018-10-11 19:45:07 +00001177 if (circuit(W, S, NodeSets,
1178 Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001179 F = true;
1180 }
1181 }
1182
1183 if (F)
1184 unblock(V);
1185 else {
1186 for (auto W : AdjK[V]) {
1187 if (W < S)
1188 continue;
1189 if (B[W].count(SV) == 0)
1190 B[W].insert(SV);
1191 }
1192 }
1193 Stack.pop_back();
1194 return F;
1195}
1196
1197/// Unblock a node in the circuit finding algorithm.
1198void SwingSchedulerDAG::Circuits::unblock(int U) {
1199 Blocked.reset(U);
1200 SmallPtrSet<SUnit *, 4> &BU = B[U];
1201 while (!BU.empty()) {
1202 SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
1203 assert(SI != BU.end() && "Invalid B set.");
1204 SUnit *W = *SI;
1205 BU.erase(W);
1206 if (Blocked.test(W->NodeNum))
1207 unblock(W->NodeNum);
1208 }
1209}
1210
1211/// Identify all the elementary circuits in the dependence graph using
1212/// Johnson's circuit algorithm.
1213void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1214 // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1215 // but we do this to find the circuits, and then change them back.
1216 swapAntiDependences(SUnits);
1217
Sumanth Gundapaneni77418a32018-10-11 19:45:07 +00001218 Circuits Cir(SUnits, Topo);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001219 // Create the adjacency structure.
1220 Cir.createAdjacencyStructure(this);
1221 for (int i = 0, e = SUnits.size(); i != e; ++i) {
1222 Cir.reset();
1223 Cir.circuit(i, i, NodeSets);
1224 }
1225
1226 // Change the dependences back so that we've created a DAG again.
1227 swapAntiDependences(SUnits);
1228}
1229
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +00001230// Create artificial dependencies between the source of COPY/REG_SEQUENCE that
1231// is loop-carried to the USE in next iteration. This will help pipeliner avoid
1232// additional copies that are needed across iterations. An artificial dependence
1233// edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
1234
1235// PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
1236// SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
1237// PHI-------True-Dep------> USEOfPhi
1238
1239// The mutation creates
1240// USEOfPHI -------Artificial-Dep---> SRCOfCopy
1241
1242// This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
1243// (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
1244// late to avoid additional copies across iterations. The possible scheduling
1245// order would be
1246// USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE.
1247
1248void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
1249 for (SUnit &SU : DAG->SUnits) {
1250 // Find the COPY/REG_SEQUENCE instruction.
1251 if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
1252 continue;
1253
1254 // Record the loop carried PHIs.
1255 SmallVector<SUnit *, 4> PHISUs;
1256 // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
1257 SmallVector<SUnit *, 4> SrcSUs;
1258
1259 for (auto &Dep : SU.Preds) {
1260 SUnit *TmpSU = Dep.getSUnit();
1261 MachineInstr *TmpMI = TmpSU->getInstr();
1262 SDep::Kind DepKind = Dep.getKind();
1263 // Save the loop carried PHI.
1264 if (DepKind == SDep::Anti && TmpMI->isPHI())
1265 PHISUs.push_back(TmpSU);
1266 // Save the source of COPY/REG_SEQUENCE.
1267 // If the source has no pre-decessors, we will end up creating cycles.
1268 else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
1269 SrcSUs.push_back(TmpSU);
1270 }
1271
1272 if (PHISUs.size() == 0 || SrcSUs.size() == 0)
1273 continue;
1274
1275 // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
1276 // SUnit to the container.
1277 SmallVector<SUnit *, 8> UseSUs;
1278 for (auto I = PHISUs.begin(); I != PHISUs.end(); ++I) {
1279 for (auto &Dep : (*I)->Succs) {
1280 if (Dep.getKind() != SDep::Data)
1281 continue;
1282
1283 SUnit *TmpSU = Dep.getSUnit();
1284 MachineInstr *TmpMI = TmpSU->getInstr();
1285 if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
1286 PHISUs.push_back(TmpSU);
1287 continue;
1288 }
1289 UseSUs.push_back(TmpSU);
1290 }
1291 }
1292
1293 if (UseSUs.size() == 0)
1294 continue;
1295
1296 SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
1297 // Add the artificial dependencies if it does not form a cycle.
1298 for (auto I : UseSUs) {
1299 for (auto Src : SrcSUs) {
1300 if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
1301 Src->addPred(SDep(I, SDep::Artificial));
1302 SDAG->Topo.AddPred(Src, I);
1303 }
1304 }
1305 }
1306 }
1307}
1308
Brendon Cahoon254f8892016-07-29 16:44:44 +00001309/// Return true for DAG nodes that we ignore when computing the cost functions.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001310/// We ignore the back-edge recurrence in order to avoid unbounded recursion
Brendon Cahoon254f8892016-07-29 16:44:44 +00001311/// in the calculation of the ASAP, ALAP, etc functions.
1312static bool ignoreDependence(const SDep &D, bool isPred) {
1313 if (D.isArtificial())
1314 return true;
1315 return D.getKind() == SDep::Anti && isPred;
1316}
1317
1318/// Compute several functions need to order the nodes for scheduling.
1319/// ASAP - Earliest time to schedule a node.
1320/// ALAP - Latest time to schedule a node.
1321/// MOV - Mobility function, difference between ALAP and ASAP.
1322/// D - Depth of each node.
1323/// H - Height of each node.
1324void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001325 ScheduleInfo.resize(SUnits.size());
1326
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001327 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001328 for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1329 E = Topo.end();
1330 I != E; ++I) {
Matthias Braun726e12c2018-09-19 00:23:35 +00001331 const SUnit &SU = SUnits[*I];
1332 dumpNode(SU);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001333 }
1334 });
1335
1336 int maxASAP = 0;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001337 // Compute ASAP and ZeroLatencyDepth.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001338 for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1339 E = Topo.end();
1340 I != E; ++I) {
1341 int asap = 0;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001342 int zeroLatencyDepth = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001343 SUnit *SU = &SUnits[*I];
1344 for (SUnit::const_pred_iterator IP = SU->Preds.begin(),
1345 EP = SU->Preds.end();
1346 IP != EP; ++IP) {
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001347 SUnit *pred = IP->getSUnit();
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001348 if (IP->getLatency() == 0)
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001349 zeroLatencyDepth =
1350 std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001351 if (ignoreDependence(*IP, true))
1352 continue;
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001353 asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() -
Brendon Cahoon254f8892016-07-29 16:44:44 +00001354 getDistance(pred, SU, *IP) * MII));
1355 }
1356 maxASAP = std::max(maxASAP, asap);
1357 ScheduleInfo[*I].ASAP = asap;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001358 ScheduleInfo[*I].ZeroLatencyDepth = zeroLatencyDepth;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001359 }
1360
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001361 // Compute ALAP, ZeroLatencyHeight, and MOV.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001362 for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(),
1363 E = Topo.rend();
1364 I != E; ++I) {
1365 int alap = maxASAP;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001366 int zeroLatencyHeight = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001367 SUnit *SU = &SUnits[*I];
1368 for (SUnit::const_succ_iterator IS = SU->Succs.begin(),
1369 ES = SU->Succs.end();
1370 IS != ES; ++IS) {
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001371 SUnit *succ = IS->getSUnit();
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001372 if (IS->getLatency() == 0)
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001373 zeroLatencyHeight =
1374 std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001375 if (ignoreDependence(*IS, true))
1376 continue;
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001377 alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() +
Brendon Cahoon254f8892016-07-29 16:44:44 +00001378 getDistance(SU, succ, *IS) * MII));
1379 }
1380
1381 ScheduleInfo[*I].ALAP = alap;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001382 ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001383 }
1384
1385 // After computing the node functions, compute the summary for each node set.
1386 for (NodeSet &I : NodeSets)
1387 I.computeNodeSetInfo(this);
1388
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001389 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001390 for (unsigned i = 0; i < SUnits.size(); i++) {
1391 dbgs() << "\tNode " << i << ":\n";
1392 dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n";
1393 dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n";
1394 dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n";
1395 dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n";
1396 dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n";
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001397 dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
1398 dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
Brendon Cahoon254f8892016-07-29 16:44:44 +00001399 }
1400 });
1401}
1402
1403/// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1404/// as the predecessors of the elements of NodeOrder that are not also in
1405/// NodeOrder.
1406static bool pred_L(SetVector<SUnit *> &NodeOrder,
1407 SmallSetVector<SUnit *, 8> &Preds,
1408 const NodeSet *S = nullptr) {
1409 Preds.clear();
1410 for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1411 I != E; ++I) {
1412 for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end();
1413 PI != PE; ++PI) {
1414 if (S && S->count(PI->getSUnit()) == 0)
1415 continue;
1416 if (ignoreDependence(*PI, true))
1417 continue;
1418 if (NodeOrder.count(PI->getSUnit()) == 0)
1419 Preds.insert(PI->getSUnit());
1420 }
1421 // Back-edges are predecessors with an anti-dependence.
1422 for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(),
1423 ES = (*I)->Succs.end();
1424 IS != ES; ++IS) {
1425 if (IS->getKind() != SDep::Anti)
1426 continue;
1427 if (S && S->count(IS->getSUnit()) == 0)
1428 continue;
1429 if (NodeOrder.count(IS->getSUnit()) == 0)
1430 Preds.insert(IS->getSUnit());
1431 }
1432 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001433 return !Preds.empty();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001434}
1435
1436/// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1437/// as the successors of the elements of NodeOrder that are not also in
1438/// NodeOrder.
1439static bool succ_L(SetVector<SUnit *> &NodeOrder,
1440 SmallSetVector<SUnit *, 8> &Succs,
1441 const NodeSet *S = nullptr) {
1442 Succs.clear();
1443 for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1444 I != E; ++I) {
1445 for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end();
1446 SI != SE; ++SI) {
1447 if (S && S->count(SI->getSUnit()) == 0)
1448 continue;
1449 if (ignoreDependence(*SI, false))
1450 continue;
1451 if (NodeOrder.count(SI->getSUnit()) == 0)
1452 Succs.insert(SI->getSUnit());
1453 }
1454 for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(),
1455 PE = (*I)->Preds.end();
1456 PI != PE; ++PI) {
1457 if (PI->getKind() != SDep::Anti)
1458 continue;
1459 if (S && S->count(PI->getSUnit()) == 0)
1460 continue;
1461 if (NodeOrder.count(PI->getSUnit()) == 0)
1462 Succs.insert(PI->getSUnit());
1463 }
1464 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001465 return !Succs.empty();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001466}
1467
1468/// Return true if there is a path from the specified node to any of the nodes
1469/// in DestNodes. Keep track and return the nodes in any path.
1470static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
1471 SetVector<SUnit *> &DestNodes,
1472 SetVector<SUnit *> &Exclude,
1473 SmallPtrSet<SUnit *, 8> &Visited) {
1474 if (Cur->isBoundaryNode())
1475 return false;
1476 if (Exclude.count(Cur) != 0)
1477 return false;
1478 if (DestNodes.count(Cur) != 0)
1479 return true;
1480 if (!Visited.insert(Cur).second)
1481 return Path.count(Cur) != 0;
1482 bool FoundPath = false;
1483 for (auto &SI : Cur->Succs)
1484 FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
1485 for (auto &PI : Cur->Preds)
1486 if (PI.getKind() == SDep::Anti)
1487 FoundPath |=
1488 computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
1489 if (FoundPath)
1490 Path.insert(Cur);
1491 return FoundPath;
1492}
1493
1494/// Return true if Set1 is a subset of Set2.
1495template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
1496 for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I)
1497 if (Set2.count(*I) == 0)
1498 return false;
1499 return true;
1500}
1501
1502/// Compute the live-out registers for the instructions in a node-set.
1503/// The live-out registers are those that are defined in the node-set,
1504/// but not used. Except for use operands of Phis.
1505static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
1506 NodeSet &NS) {
1507 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1508 MachineRegisterInfo &MRI = MF.getRegInfo();
1509 SmallVector<RegisterMaskPair, 8> LiveOutRegs;
1510 SmallSet<unsigned, 4> Uses;
1511 for (SUnit *SU : NS) {
1512 const MachineInstr *MI = SU->getInstr();
1513 if (MI->isPHI())
1514 continue;
Matthias Braunfc371552016-10-24 21:36:43 +00001515 for (const MachineOperand &MO : MI->operands())
1516 if (MO.isReg() && MO.isUse()) {
1517 unsigned Reg = MO.getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001518 if (TargetRegisterInfo::isVirtualRegister(Reg))
1519 Uses.insert(Reg);
1520 else if (MRI.isAllocatable(Reg))
1521 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1522 Uses.insert(*Units);
1523 }
1524 }
1525 for (SUnit *SU : NS)
Matthias Braunfc371552016-10-24 21:36:43 +00001526 for (const MachineOperand &MO : SU->getInstr()->operands())
1527 if (MO.isReg() && MO.isDef() && !MO.isDead()) {
1528 unsigned Reg = MO.getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001529 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1530 if (!Uses.count(Reg))
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001531 LiveOutRegs.push_back(RegisterMaskPair(Reg,
1532 LaneBitmask::getNone()));
Brendon Cahoon254f8892016-07-29 16:44:44 +00001533 } else if (MRI.isAllocatable(Reg)) {
1534 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1535 if (!Uses.count(*Units))
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001536 LiveOutRegs.push_back(RegisterMaskPair(*Units,
1537 LaneBitmask::getNone()));
Brendon Cahoon254f8892016-07-29 16:44:44 +00001538 }
1539 }
1540 RPTracker.addLiveRegs(LiveOutRegs);
1541}
1542
1543/// A heuristic to filter nodes in recurrent node-sets if the register
1544/// pressure of a set is too high.
1545void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
1546 for (auto &NS : NodeSets) {
1547 // Skip small node-sets since they won't cause register pressure problems.
1548 if (NS.size() <= 2)
1549 continue;
1550 IntervalPressure RecRegPressure;
1551 RegPressureTracker RecRPTracker(RecRegPressure);
1552 RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
1553 computeLiveOuts(MF, RecRPTracker, NS);
1554 RecRPTracker.closeBottom();
1555
1556 std::vector<SUnit *> SUnits(NS.begin(), NS.end());
Fangrui Song0cac7262018-09-27 02:13:45 +00001557 llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001558 return A->NodeNum > B->NodeNum;
1559 });
1560
1561 for (auto &SU : SUnits) {
1562 // Since we're computing the register pressure for a subset of the
1563 // instructions in a block, we need to set the tracker for each
1564 // instruction in the node-set. The tracker is set to the instruction
1565 // just after the one we're interested in.
1566 MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
1567 RecRPTracker.setPos(std::next(CurInstI));
1568
1569 RegPressureDelta RPDelta;
1570 ArrayRef<PressureChange> CriticalPSets;
1571 RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
1572 CriticalPSets,
1573 RecRegPressure.MaxSetPressure);
1574 if (RPDelta.Excess.isValid()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001575 LLVM_DEBUG(
1576 dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
1577 << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
1578 << ":" << RPDelta.Excess.getUnitInc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00001579 NS.setExceedPressure(SU);
1580 break;
1581 }
1582 RecRPTracker.recede();
1583 }
1584 }
1585}
1586
1587/// A heuristic to colocate node sets that have the same set of
1588/// successors.
1589void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
1590 unsigned Colocate = 0;
1591 for (int i = 0, e = NodeSets.size(); i < e; ++i) {
1592 NodeSet &N1 = NodeSets[i];
1593 SmallSetVector<SUnit *, 8> S1;
1594 if (N1.empty() || !succ_L(N1, S1))
1595 continue;
1596 for (int j = i + 1; j < e; ++j) {
1597 NodeSet &N2 = NodeSets[j];
1598 if (N1.compareRecMII(N2) != 0)
1599 continue;
1600 SmallSetVector<SUnit *, 8> S2;
1601 if (N2.empty() || !succ_L(N2, S2))
1602 continue;
1603 if (isSubset(S1, S2) && S1.size() == S2.size()) {
1604 N1.setColocate(++Colocate);
1605 N2.setColocate(Colocate);
1606 break;
1607 }
1608 }
1609 }
1610}
1611
1612/// Check if the existing node-sets are profitable. If not, then ignore the
1613/// recurrent node-sets, and attempt to schedule all nodes together. This is
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001614/// a heuristic. If the MII is large and all the recurrent node-sets are small,
1615/// then it's best to try to schedule all instructions together instead of
1616/// starting with the recurrent node-sets.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001617void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
1618 // Look for loops with a large MII.
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001619 if (MII < 17)
Brendon Cahoon254f8892016-07-29 16:44:44 +00001620 return;
1621 // Check if the node-set contains only a simple add recurrence.
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001622 for (auto &NS : NodeSets) {
1623 if (NS.getRecMII() > 2)
Brendon Cahoon254f8892016-07-29 16:44:44 +00001624 return;
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001625 if (NS.getMaxDepth() > MII)
Brendon Cahoon254f8892016-07-29 16:44:44 +00001626 return;
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001627 }
1628 NodeSets.clear();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001629 LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001630 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001631}
1632
1633/// Add the nodes that do not belong to a recurrence set into groups
1634/// based upon connected componenets.
1635void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
1636 SetVector<SUnit *> NodesAdded;
1637 SmallPtrSet<SUnit *, 8> Visited;
1638 // Add the nodes that are on a path between the previous node sets and
1639 // the current node set.
1640 for (NodeSet &I : NodeSets) {
1641 SmallSetVector<SUnit *, 8> N;
1642 // Add the nodes from the current node set to the previous node set.
1643 if (succ_L(I, N)) {
1644 SetVector<SUnit *> Path;
1645 for (SUnit *NI : N) {
1646 Visited.clear();
1647 computePath(NI, Path, NodesAdded, I, Visited);
1648 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001649 if (!Path.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001650 I.insert(Path.begin(), Path.end());
1651 }
1652 // Add the nodes from the previous node set to the current node set.
1653 N.clear();
1654 if (succ_L(NodesAdded, N)) {
1655 SetVector<SUnit *> Path;
1656 for (SUnit *NI : N) {
1657 Visited.clear();
1658 computePath(NI, Path, I, NodesAdded, Visited);
1659 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001660 if (!Path.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001661 I.insert(Path.begin(), Path.end());
1662 }
1663 NodesAdded.insert(I.begin(), I.end());
1664 }
1665
1666 // Create a new node set with the connected nodes of any successor of a node
1667 // in a recurrent set.
1668 NodeSet NewSet;
1669 SmallSetVector<SUnit *, 8> N;
1670 if (succ_L(NodesAdded, N))
1671 for (SUnit *I : N)
1672 addConnectedNodes(I, NewSet, NodesAdded);
Eugene Zelenko32a40562017-09-11 23:00:48 +00001673 if (!NewSet.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001674 NodeSets.push_back(NewSet);
1675
1676 // Create a new node set with the connected nodes of any predecessor of a node
1677 // in a recurrent set.
1678 NewSet.clear();
1679 if (pred_L(NodesAdded, N))
1680 for (SUnit *I : N)
1681 addConnectedNodes(I, NewSet, NodesAdded);
Eugene Zelenko32a40562017-09-11 23:00:48 +00001682 if (!NewSet.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001683 NodeSets.push_back(NewSet);
1684
Hiroshi Inoue372ffa12018-04-13 11:37:06 +00001685 // Create new nodes sets with the connected nodes any remaining node that
Brendon Cahoon254f8892016-07-29 16:44:44 +00001686 // has no predecessor.
1687 for (unsigned i = 0; i < SUnits.size(); ++i) {
1688 SUnit *SU = &SUnits[i];
1689 if (NodesAdded.count(SU) == 0) {
1690 NewSet.clear();
1691 addConnectedNodes(SU, NewSet, NodesAdded);
Eugene Zelenko32a40562017-09-11 23:00:48 +00001692 if (!NewSet.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001693 NodeSets.push_back(NewSet);
1694 }
1695 }
1696}
1697
Alexey Lapshin31f47b82019-01-25 21:59:53 +00001698/// Add the node to the set, and add all of its connected nodes to the set.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001699void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
1700 SetVector<SUnit *> &NodesAdded) {
1701 NewSet.insert(SU);
1702 NodesAdded.insert(SU);
1703 for (auto &SI : SU->Succs) {
1704 SUnit *Successor = SI.getSUnit();
1705 if (!SI.isArtificial() && NodesAdded.count(Successor) == 0)
1706 addConnectedNodes(Successor, NewSet, NodesAdded);
1707 }
1708 for (auto &PI : SU->Preds) {
1709 SUnit *Predecessor = PI.getSUnit();
1710 if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
1711 addConnectedNodes(Predecessor, NewSet, NodesAdded);
1712 }
1713}
1714
1715/// Return true if Set1 contains elements in Set2. The elements in common
1716/// are returned in a different container.
1717static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
1718 SmallSetVector<SUnit *, 8> &Result) {
1719 Result.clear();
1720 for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
1721 SUnit *SU = Set1[i];
1722 if (Set2.count(SU) != 0)
1723 Result.insert(SU);
1724 }
1725 return !Result.empty();
1726}
1727
1728/// Merge the recurrence node sets that have the same initial node.
1729void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
1730 for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1731 ++I) {
1732 NodeSet &NI = *I;
1733 for (NodeSetType::iterator J = I + 1; J != E;) {
1734 NodeSet &NJ = *J;
1735 if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
1736 if (NJ.compareRecMII(NI) > 0)
1737 NI.setRecMII(NJ.getRecMII());
1738 for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI;
1739 ++NII)
1740 I->insert(*NII);
1741 NodeSets.erase(J);
1742 E = NodeSets.end();
1743 } else {
1744 ++J;
1745 }
1746 }
1747 }
1748}
1749
1750/// Remove nodes that have been scheduled in previous NodeSets.
1751void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
1752 for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1753 ++I)
1754 for (NodeSetType::iterator J = I + 1; J != E;) {
1755 J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
1756
Eugene Zelenko32a40562017-09-11 23:00:48 +00001757 if (J->empty()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001758 NodeSets.erase(J);
1759 E = NodeSets.end();
1760 } else {
1761 ++J;
1762 }
1763 }
1764}
1765
Brendon Cahoon254f8892016-07-29 16:44:44 +00001766/// Compute an ordered list of the dependence graph nodes, which
1767/// indicates the order that the nodes will be scheduled. This is a
1768/// two-level algorithm. First, a partial order is created, which
1769/// consists of a list of sets ordered from highest to lowest priority.
1770void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
1771 SmallSetVector<SUnit *, 8> R;
1772 NodeOrder.clear();
1773
1774 for (auto &Nodes : NodeSets) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001775 LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001776 OrderKind Order;
1777 SmallSetVector<SUnit *, 8> N;
1778 if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) {
1779 R.insert(N.begin(), N.end());
1780 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001781 LLVM_DEBUG(dbgs() << " Bottom up (preds) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001782 } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) {
1783 R.insert(N.begin(), N.end());
1784 Order = TopDown;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001785 LLVM_DEBUG(dbgs() << " Top down (succs) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001786 } else if (isIntersect(N, Nodes, R)) {
1787 // If some of the successors are in the existing node-set, then use the
1788 // top-down ordering.
1789 Order = TopDown;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001790 LLVM_DEBUG(dbgs() << " Top down (intersect) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001791 } else if (NodeSets.size() == 1) {
1792 for (auto &N : Nodes)
1793 if (N->Succs.size() == 0)
1794 R.insert(N);
1795 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001796 LLVM_DEBUG(dbgs() << " Bottom up (all) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001797 } else {
1798 // Find the node with the highest ASAP.
1799 SUnit *maxASAP = nullptr;
1800 for (SUnit *SU : Nodes) {
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00001801 if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
1802 (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001803 maxASAP = SU;
1804 }
1805 R.insert(maxASAP);
1806 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001807 LLVM_DEBUG(dbgs() << " Bottom up (default) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001808 }
1809
1810 while (!R.empty()) {
1811 if (Order == TopDown) {
1812 // Choose the node with the maximum height. If more than one, choose
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00001813 // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001814 // choose the node with the lowest MOV.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001815 while (!R.empty()) {
1816 SUnit *maxHeight = nullptr;
1817 for (SUnit *I : R) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001818 if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001819 maxHeight = I;
1820 else if (getHeight(I) == getHeight(maxHeight) &&
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001821 getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001822 maxHeight = I;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001823 else if (getHeight(I) == getHeight(maxHeight) &&
1824 getZeroLatencyHeight(I) ==
1825 getZeroLatencyHeight(maxHeight) &&
1826 getMOV(I) < getMOV(maxHeight))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001827 maxHeight = I;
1828 }
1829 NodeOrder.insert(maxHeight);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001830 LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001831 R.remove(maxHeight);
1832 for (const auto &I : maxHeight->Succs) {
1833 if (Nodes.count(I.getSUnit()) == 0)
1834 continue;
1835 if (NodeOrder.count(I.getSUnit()) != 0)
1836 continue;
1837 if (ignoreDependence(I, false))
1838 continue;
1839 R.insert(I.getSUnit());
1840 }
1841 // Back-edges are predecessors with an anti-dependence.
1842 for (const auto &I : maxHeight->Preds) {
1843 if (I.getKind() != SDep::Anti)
1844 continue;
1845 if (Nodes.count(I.getSUnit()) == 0)
1846 continue;
1847 if (NodeOrder.count(I.getSUnit()) != 0)
1848 continue;
1849 R.insert(I.getSUnit());
1850 }
1851 }
1852 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001853 LLVM_DEBUG(dbgs() << "\n Switching order to bottom up ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001854 SmallSetVector<SUnit *, 8> N;
1855 if (pred_L(NodeOrder, N, &Nodes))
1856 R.insert(N.begin(), N.end());
1857 } else {
1858 // Choose the node with the maximum depth. If more than one, choose
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001859 // the node with the maximum ZeroLatencyDepth. If still more than one,
1860 // choose the node with the lowest MOV.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001861 while (!R.empty()) {
1862 SUnit *maxDepth = nullptr;
1863 for (SUnit *I : R) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001864 if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001865 maxDepth = I;
1866 else if (getDepth(I) == getDepth(maxDepth) &&
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001867 getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001868 maxDepth = I;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001869 else if (getDepth(I) == getDepth(maxDepth) &&
1870 getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
1871 getMOV(I) < getMOV(maxDepth))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001872 maxDepth = I;
1873 }
1874 NodeOrder.insert(maxDepth);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001875 LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001876 R.remove(maxDepth);
1877 if (Nodes.isExceedSU(maxDepth)) {
1878 Order = TopDown;
1879 R.clear();
1880 R.insert(Nodes.getNode(0));
1881 break;
1882 }
1883 for (const auto &I : maxDepth->Preds) {
1884 if (Nodes.count(I.getSUnit()) == 0)
1885 continue;
1886 if (NodeOrder.count(I.getSUnit()) != 0)
1887 continue;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001888 R.insert(I.getSUnit());
1889 }
1890 // Back-edges are predecessors with an anti-dependence.
1891 for (const auto &I : maxDepth->Succs) {
1892 if (I.getKind() != SDep::Anti)
1893 continue;
1894 if (Nodes.count(I.getSUnit()) == 0)
1895 continue;
1896 if (NodeOrder.count(I.getSUnit()) != 0)
1897 continue;
1898 R.insert(I.getSUnit());
1899 }
1900 }
1901 Order = TopDown;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001902 LLVM_DEBUG(dbgs() << "\n Switching order to top down ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001903 SmallSetVector<SUnit *, 8> N;
1904 if (succ_L(NodeOrder, N, &Nodes))
1905 R.insert(N.begin(), N.end());
1906 }
1907 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001908 LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001909 }
1910
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001911 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001912 dbgs() << "Node order: ";
1913 for (SUnit *I : NodeOrder)
1914 dbgs() << " " << I->NodeNum << " ";
1915 dbgs() << "\n";
1916 });
1917}
1918
1919/// Process the nodes in the computed order and create the pipelined schedule
1920/// of the instructions, if possible. Return true if a schedule is found.
1921bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001922
1923 if (NodeOrder.empty()){
1924 LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
Brendon Cahoon254f8892016-07-29 16:44:44 +00001925 return false;
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001926 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00001927
1928 bool scheduleFound = false;
Brendon Cahoon59d99732019-01-23 03:26:10 +00001929 unsigned II = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001930 // Keep increasing II until a valid schedule is found.
Brendon Cahoon59d99732019-01-23 03:26:10 +00001931 for (II = MII; II <= MAX_II && !scheduleFound; ++II) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001932 Schedule.reset();
1933 Schedule.setInitiationInterval(II);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001934 LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001935
1936 SetVector<SUnit *>::iterator NI = NodeOrder.begin();
1937 SetVector<SUnit *>::iterator NE = NodeOrder.end();
1938 do {
1939 SUnit *SU = *NI;
1940
1941 // Compute the schedule time for the instruction, which is based
1942 // upon the scheduled time for any predecessors/successors.
1943 int EarlyStart = INT_MIN;
1944 int LateStart = INT_MAX;
1945 // These values are set when the size of the schedule window is limited
1946 // due to chain dependences.
1947 int SchedEnd = INT_MAX;
1948 int SchedStart = INT_MIN;
1949 Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
1950 II, this);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001951 LLVM_DEBUG({
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001952 dbgs() << "\n";
Brendon Cahoon254f8892016-07-29 16:44:44 +00001953 dbgs() << "Inst (" << SU->NodeNum << ") ";
1954 SU->getInstr()->dump();
1955 dbgs() << "\n";
1956 });
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001957 LLVM_DEBUG({
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001958 dbgs() << format("\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart,
1959 LateStart, SchedEnd, SchedStart);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001960 });
1961
1962 if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
1963 SchedStart > LateStart)
1964 scheduleFound = false;
1965 else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
1966 SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
1967 scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
1968 } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
1969 SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
1970 scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
1971 } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
1972 SchedEnd =
1973 std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
1974 // When scheduling a Phi it is better to start at the late cycle and go
1975 // backwards. The default order may insert the Phi too far away from
1976 // its first dependence.
1977 if (SU->getInstr()->isPHI())
1978 scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
1979 else
1980 scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
1981 } else {
1982 int FirstCycle = Schedule.getFirstCycle();
1983 scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
1984 FirstCycle + getASAP(SU) + II - 1, II);
1985 }
1986 // Even if we find a schedule, make sure the schedule doesn't exceed the
1987 // allowable number of stages. We keep trying if this happens.
1988 if (scheduleFound)
1989 if (SwpMaxStages > -1 &&
1990 Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
1991 scheduleFound = false;
1992
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001993 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001994 if (!scheduleFound)
1995 dbgs() << "\tCan't schedule\n";
1996 });
1997 } while (++NI != NE && scheduleFound);
1998
1999 // If a schedule is found, check if it is a valid schedule too.
2000 if (scheduleFound)
2001 scheduleFound = Schedule.isValidSchedule(this);
2002 }
2003
Brendon Cahoon59d99732019-01-23 03:26:10 +00002004 LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound << " (II=" << II
2005 << ")\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00002006
2007 if (scheduleFound)
2008 Schedule.finalizeSchedule(this);
2009 else
2010 Schedule.reset();
2011
2012 return scheduleFound && Schedule.getMaxStageCount() > 0;
2013}
2014
2015/// Given a schedule for the loop, generate a new version of the loop,
2016/// and replace the old version. This function generates a prolog
2017/// that contains the initial iterations in the pipeline, and kernel
2018/// loop, and the epilogue that contains the code for the final
2019/// iterations.
2020void SwingSchedulerDAG::generatePipelinedLoop(SMSchedule &Schedule) {
2021 // Create a new basic block for the kernel and add it to the CFG.
2022 MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
2023
2024 unsigned MaxStageCount = Schedule.getMaxStageCount();
2025
2026 // Remember the registers that are used in different stages. The index is
2027 // the iteration, or stage, that the instruction is scheduled in. This is
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002028 // a map between register names in the original block and the names created
Brendon Cahoon254f8892016-07-29 16:44:44 +00002029 // in each stage of the pipelined loop.
2030 ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
2031 InstrMapTy InstrMap;
2032
2033 SmallVector<MachineBasicBlock *, 4> PrologBBs;
Jinsong Jief2d6d92019-06-11 17:40:39 +00002034
2035 MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader();
2036 assert(PreheaderBB != nullptr &&
2037 "Need to add code to handle loops w/o preheader");
Brendon Cahoon254f8892016-07-29 16:44:44 +00002038 // Generate the prolog instructions that set up the pipeline.
2039 generateProlog(Schedule, MaxStageCount, KernelBB, VRMap, PrologBBs);
2040 MF.insert(BB->getIterator(), KernelBB);
2041
2042 // Rearrange the instructions to generate the new, pipelined loop,
2043 // and update register names as needed.
2044 for (int Cycle = Schedule.getFirstCycle(),
2045 LastCycle = Schedule.getFinalCycle();
2046 Cycle <= LastCycle; ++Cycle) {
2047 std::deque<SUnit *> &CycleInstrs = Schedule.getInstructions(Cycle);
2048 // This inner loop schedules each instruction in the cycle.
2049 for (SUnit *CI : CycleInstrs) {
2050 if (CI->getInstr()->isPHI())
2051 continue;
2052 unsigned StageNum = Schedule.stageScheduled(getSUnit(CI->getInstr()));
2053 MachineInstr *NewMI = cloneInstr(CI->getInstr(), MaxStageCount, StageNum);
2054 updateInstruction(NewMI, false, MaxStageCount, StageNum, Schedule, VRMap);
2055 KernelBB->push_back(NewMI);
2056 InstrMap[NewMI] = CI->getInstr();
2057 }
2058 }
2059
2060 // Copy any terminator instructions to the new kernel, and update
2061 // names as needed.
2062 for (MachineBasicBlock::iterator I = BB->getFirstTerminator(),
2063 E = BB->instr_end();
2064 I != E; ++I) {
2065 MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
2066 updateInstruction(NewMI, false, MaxStageCount, 0, Schedule, VRMap);
2067 KernelBB->push_back(NewMI);
2068 InstrMap[NewMI] = &*I;
2069 }
2070
2071 KernelBB->transferSuccessors(BB);
2072 KernelBB->replaceSuccessor(BB, KernelBB);
2073
2074 generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule,
2075 VRMap, InstrMap, MaxStageCount, MaxStageCount, false);
2076 generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule, VRMap,
2077 InstrMap, MaxStageCount, MaxStageCount, false);
2078
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002079 LLVM_DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
Brendon Cahoon254f8892016-07-29 16:44:44 +00002080
2081 SmallVector<MachineBasicBlock *, 4> EpilogBBs;
2082 // Generate the epilog instructions to complete the pipeline.
2083 generateEpilog(Schedule, MaxStageCount, KernelBB, VRMap, EpilogBBs,
2084 PrologBBs);
2085
2086 // We need this step because the register allocation doesn't handle some
2087 // situations well, so we insert copies to help out.
2088 splitLifetimes(KernelBB, EpilogBBs, Schedule);
2089
2090 // Remove dead instructions due to loop induction variables.
2091 removeDeadInstructions(KernelBB, EpilogBBs);
2092
2093 // Add branches between prolog and epilog blocks.
Jinsong Jief2d6d92019-06-11 17:40:39 +00002094 addBranches(*PreheaderBB, PrologBBs, KernelBB, EpilogBBs, Schedule, VRMap);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002095
2096 // Remove the original loop since it's no longer referenced.
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00002097 for (auto &I : *BB)
2098 LIS.RemoveMachineInstrFromMaps(I);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002099 BB->clear();
2100 BB->eraseFromParent();
2101
2102 delete[] VRMap;
2103}
2104
2105/// Generate the pipeline prolog code.
2106void SwingSchedulerDAG::generateProlog(SMSchedule &Schedule, unsigned LastStage,
2107 MachineBasicBlock *KernelBB,
2108 ValueMapTy *VRMap,
2109 MBBVectorTy &PrologBBs) {
2110 MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader();
Eugene Zelenko32a40562017-09-11 23:00:48 +00002111 assert(PreheaderBB != nullptr &&
Brendon Cahoon254f8892016-07-29 16:44:44 +00002112 "Need to add code to handle loops w/o preheader");
2113 MachineBasicBlock *PredBB = PreheaderBB;
2114 InstrMapTy InstrMap;
2115
2116 // Generate a basic block for each stage, not including the last stage,
2117 // which will be generated in the kernel. Each basic block may contain
2118 // instructions from multiple stages/iterations.
2119 for (unsigned i = 0; i < LastStage; ++i) {
2120 // Create and insert the prolog basic block prior to the original loop
2121 // basic block. The original loop is removed later.
2122 MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
2123 PrologBBs.push_back(NewBB);
2124 MF.insert(BB->getIterator(), NewBB);
2125 NewBB->transferSuccessors(PredBB);
2126 PredBB->addSuccessor(NewBB);
2127 PredBB = NewBB;
2128
2129 // Generate instructions for each appropriate stage. Process instructions
2130 // in original program order.
2131 for (int StageNum = i; StageNum >= 0; --StageNum) {
2132 for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2133 BBE = BB->getFirstTerminator();
2134 BBI != BBE; ++BBI) {
2135 if (Schedule.isScheduledAtStage(getSUnit(&*BBI), (unsigned)StageNum)) {
2136 if (BBI->isPHI())
2137 continue;
2138 MachineInstr *NewMI =
2139 cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum, Schedule);
2140 updateInstruction(NewMI, false, i, (unsigned)StageNum, Schedule,
2141 VRMap);
2142 NewBB->push_back(NewMI);
2143 InstrMap[NewMI] = &*BBI;
2144 }
2145 }
2146 }
2147 rewritePhiValues(NewBB, i, Schedule, VRMap, InstrMap);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002148 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00002149 dbgs() << "prolog:\n";
2150 NewBB->dump();
2151 });
2152 }
2153
2154 PredBB->replaceSuccessor(BB, KernelBB);
2155
2156 // Check if we need to remove the branch from the preheader to the original
2157 // loop, and replace it with a branch to the new loop.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002158 unsigned numBranches = TII->removeBranch(*PreheaderBB);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002159 if (numBranches) {
2160 SmallVector<MachineOperand, 0> Cond;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002161 TII->insertBranch(*PreheaderBB, PrologBBs[0], nullptr, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002162 }
2163}
2164
2165/// Generate the pipeline epilog code. The epilog code finishes the iterations
2166/// that were started in either the prolog or the kernel. We create a basic
2167/// block for each stage that needs to complete.
2168void SwingSchedulerDAG::generateEpilog(SMSchedule &Schedule, unsigned LastStage,
2169 MachineBasicBlock *KernelBB,
2170 ValueMapTy *VRMap,
2171 MBBVectorTy &EpilogBBs,
2172 MBBVectorTy &PrologBBs) {
2173 // We need to change the branch from the kernel to the first epilog block, so
2174 // this call to analyze branch uses the kernel rather than the original BB.
2175 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2176 SmallVector<MachineOperand, 4> Cond;
2177 bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
2178 assert(!checkBranch && "generateEpilog must be able to analyze the branch");
2179 if (checkBranch)
2180 return;
2181
2182 MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
2183 if (*LoopExitI == KernelBB)
2184 ++LoopExitI;
2185 assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
2186 MachineBasicBlock *LoopExitBB = *LoopExitI;
2187
2188 MachineBasicBlock *PredBB = KernelBB;
2189 MachineBasicBlock *EpilogStart = LoopExitBB;
2190 InstrMapTy InstrMap;
2191
2192 // Generate a basic block for each stage, not including the last stage,
2193 // which was generated for the kernel. Each basic block may contain
2194 // instructions from multiple stages/iterations.
2195 int EpilogStage = LastStage + 1;
2196 for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
2197 MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
2198 EpilogBBs.push_back(NewBB);
2199 MF.insert(BB->getIterator(), NewBB);
2200
2201 PredBB->replaceSuccessor(LoopExitBB, NewBB);
2202 NewBB->addSuccessor(LoopExitBB);
2203
2204 if (EpilogStart == LoopExitBB)
2205 EpilogStart = NewBB;
2206
2207 // Add instructions to the epilog depending on the current block.
2208 // Process instructions in original program order.
2209 for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
2210 for (auto &BBI : *BB) {
2211 if (BBI.isPHI())
2212 continue;
2213 MachineInstr *In = &BBI;
2214 if (Schedule.isScheduledAtStage(getSUnit(In), StageNum)) {
Krzysztof Parzyszek785b6ce2018-03-26 15:45:55 +00002215 // Instructions with memoperands in the epilog are updated with
2216 // conservative values.
2217 MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002218 updateInstruction(NewMI, i == 1, EpilogStage, 0, Schedule, VRMap);
2219 NewBB->push_back(NewMI);
2220 InstrMap[NewMI] = In;
2221 }
2222 }
2223 }
2224 generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule,
2225 VRMap, InstrMap, LastStage, EpilogStage, i == 1);
2226 generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, VRMap,
2227 InstrMap, LastStage, EpilogStage, i == 1);
2228 PredBB = NewBB;
2229
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002230 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00002231 dbgs() << "epilog:\n";
2232 NewBB->dump();
2233 });
2234 }
2235
2236 // Fix any Phi nodes in the loop exit block.
2237 for (MachineInstr &MI : *LoopExitBB) {
2238 if (!MI.isPHI())
2239 break;
2240 for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
2241 MachineOperand &MO = MI.getOperand(i);
2242 if (MO.getMBB() == BB)
2243 MO.setMBB(PredBB);
2244 }
2245 }
2246
2247 // Create a branch to the new epilog from the kernel.
2248 // Remove the original branch and add a new branch to the epilog.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002249 TII->removeBranch(*KernelBB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002250 TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002251 // Add a branch to the loop exit.
2252 if (EpilogBBs.size() > 0) {
2253 MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
2254 SmallVector<MachineOperand, 4> Cond1;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002255 TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002256 }
2257}
2258
2259/// Replace all uses of FromReg that appear outside the specified
2260/// basic block with ToReg.
2261static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
2262 MachineBasicBlock *MBB,
2263 MachineRegisterInfo &MRI,
2264 LiveIntervals &LIS) {
2265 for (MachineRegisterInfo::use_iterator I = MRI.use_begin(FromReg),
2266 E = MRI.use_end();
2267 I != E;) {
2268 MachineOperand &O = *I;
2269 ++I;
2270 if (O.getParent()->getParent() != MBB)
2271 O.setReg(ToReg);
2272 }
2273 if (!LIS.hasInterval(ToReg))
2274 LIS.createEmptyInterval(ToReg);
2275}
2276
2277/// Return true if the register has a use that occurs outside the
2278/// specified loop.
2279static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
2280 MachineRegisterInfo &MRI) {
2281 for (MachineRegisterInfo::use_iterator I = MRI.use_begin(Reg),
2282 E = MRI.use_end();
2283 I != E; ++I)
2284 if (I->getParent()->getParent() != BB)
2285 return true;
2286 return false;
2287}
2288
2289/// Generate Phis for the specific block in the generated pipelined code.
2290/// This function looks at the Phis from the original code to guide the
2291/// creation of new Phis.
2292void SwingSchedulerDAG::generateExistingPhis(
2293 MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2294 MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2295 InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2296 bool IsLast) {
Simon Pilgrim6bdc7552017-03-31 10:59:37 +00002297 // Compute the stage number for the initial value of the Phi, which
Brendon Cahoon254f8892016-07-29 16:44:44 +00002298 // comes from the prolog. The prolog to use depends on to which kernel/
2299 // epilog that we're adding the Phi.
2300 unsigned PrologStage = 0;
2301 unsigned PrevStage = 0;
2302 bool InKernel = (LastStageNum == CurStageNum);
2303 if (InKernel) {
2304 PrologStage = LastStageNum - 1;
2305 PrevStage = CurStageNum;
2306 } else {
2307 PrologStage = LastStageNum - (CurStageNum - LastStageNum);
2308 PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
2309 }
2310
2311 for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2312 BBE = BB->getFirstNonPHI();
2313 BBI != BBE; ++BBI) {
2314 unsigned Def = BBI->getOperand(0).getReg();
2315
2316 unsigned InitVal = 0;
2317 unsigned LoopVal = 0;
2318 getPhiRegs(*BBI, BB, InitVal, LoopVal);
2319
2320 unsigned PhiOp1 = 0;
2321 // The Phi value from the loop body typically is defined in the loop, but
2322 // not always. So, we need to check if the value is defined in the loop.
2323 unsigned PhiOp2 = LoopVal;
2324 if (VRMap[LastStageNum].count(LoopVal))
2325 PhiOp2 = VRMap[LastStageNum][LoopVal];
2326
2327 int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2328 int LoopValStage =
2329 Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
2330 unsigned NumStages = Schedule.getStagesForReg(Def, CurStageNum);
2331 if (NumStages == 0) {
2332 // We don't need to generate a Phi anymore, but we need to rename any uses
2333 // of the Phi value.
2334 unsigned NewReg = VRMap[PrevStage][LoopVal];
2335 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, 0, &*BBI,
Krzysztof Parzyszek16e66f52018-03-26 16:41:36 +00002336 Def, InitVal, NewReg);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002337 if (VRMap[CurStageNum].count(LoopVal))
2338 VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
2339 }
2340 // Adjust the number of Phis needed depending on the number of prologs left,
Krzysztof Parzyszek3f72a6b2018-03-26 16:37:55 +00002341 // and the distance from where the Phi is first scheduled. The number of
2342 // Phis cannot exceed the number of prolog stages. Each stage can
2343 // potentially define two values.
2344 unsigned MaxPhis = PrologStage + 2;
2345 if (!InKernel && (int)PrologStage <= LoopValStage)
2346 MaxPhis = std::max((int)MaxPhis - (int)LoopValStage, 1);
2347 unsigned NumPhis = std::min(NumStages, MaxPhis);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002348
2349 unsigned NewReg = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002350 unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
2351 // In the epilog, we may need to look back one stage to get the correct
2352 // Phi name because the epilog and prolog blocks execute the same stage.
2353 // The correct name is from the previous block only when the Phi has
2354 // been completely scheduled prior to the epilog, and Phi value is not
2355 // needed in multiple stages.
2356 int StageDiff = 0;
2357 if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
2358 NumPhis == 1)
2359 StageDiff = 1;
2360 // Adjust the computations below when the phi and the loop definition
2361 // are scheduled in different stages.
2362 if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
2363 StageDiff = StageScheduled - LoopValStage;
2364 for (unsigned np = 0; np < NumPhis; ++np) {
2365 // If the Phi hasn't been scheduled, then use the initial Phi operand
2366 // value. Otherwise, use the scheduled version of the instruction. This
2367 // is a little complicated when a Phi references another Phi.
2368 if (np > PrologStage || StageScheduled >= (int)LastStageNum)
2369 PhiOp1 = InitVal;
2370 // Check if the Phi has already been scheduled in a prolog stage.
2371 else if (PrologStage >= AccessStage + StageDiff + np &&
2372 VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
2373 PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
Hiroshi Inouedad8c6a2019-01-09 05:11:10 +00002374 // Check if the Phi has already been scheduled, but the loop instruction
Brendon Cahoon254f8892016-07-29 16:44:44 +00002375 // is either another Phi, or doesn't occur in the loop.
2376 else if (PrologStage >= AccessStage + StageDiff + np) {
2377 // If the Phi references another Phi, we need to examine the other
2378 // Phi to get the correct value.
2379 PhiOp1 = LoopVal;
2380 MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
2381 int Indirects = 1;
2382 while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
2383 int PhiStage = Schedule.stageScheduled(getSUnit(InstOp1));
2384 if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
2385 PhiOp1 = getInitPhiReg(*InstOp1, BB);
2386 else
2387 PhiOp1 = getLoopPhiReg(*InstOp1, BB);
2388 InstOp1 = MRI.getVRegDef(PhiOp1);
2389 int PhiOpStage = Schedule.stageScheduled(getSUnit(InstOp1));
2390 int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
2391 if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
2392 VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
2393 PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
2394 break;
2395 }
2396 ++Indirects;
2397 }
2398 } else
2399 PhiOp1 = InitVal;
2400 // If this references a generated Phi in the kernel, get the Phi operand
2401 // from the incoming block.
2402 if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
2403 if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2404 PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2405
2406 MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
2407 bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
2408 // In the epilog, a map lookup is needed to get the value from the kernel,
2409 // or previous epilog block. How is does this depends on if the
2410 // instruction is scheduled in the previous block.
2411 if (!InKernel) {
2412 int StageDiffAdj = 0;
2413 if (LoopValStage != -1 && StageScheduled > LoopValStage)
2414 StageDiffAdj = StageScheduled - LoopValStage;
2415 // Use the loop value defined in the kernel, unless the kernel
2416 // contains the last definition of the Phi.
2417 if (np == 0 && PrevStage == LastStageNum &&
2418 (StageScheduled != 0 || LoopValStage != 0) &&
2419 VRMap[PrevStage - StageDiffAdj].count(LoopVal))
2420 PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
2421 // Use the value defined by the Phi. We add one because we switch
2422 // from looking at the loop value to the Phi definition.
2423 else if (np > 0 && PrevStage == LastStageNum &&
2424 VRMap[PrevStage - np + 1].count(Def))
2425 PhiOp2 = VRMap[PrevStage - np + 1][Def];
2426 // Use the loop value defined in the kernel.
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002427 else if (static_cast<unsigned>(LoopValStage) > PrologStage + 1 &&
Brendon Cahoon254f8892016-07-29 16:44:44 +00002428 VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
2429 PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
2430 // Use the value defined by the Phi, unless we're generating the first
2431 // epilog and the Phi refers to a Phi in a different stage.
2432 else if (VRMap[PrevStage - np].count(Def) &&
2433 (!LoopDefIsPhi || PrevStage != LastStageNum))
2434 PhiOp2 = VRMap[PrevStage - np][Def];
2435 }
2436
2437 // Check if we can reuse an existing Phi. This occurs when a Phi
2438 // references another Phi, and the other Phi is scheduled in an
2439 // earlier stage. We can try to reuse an existing Phi up until the last
2440 // stage of the current Phi.
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002441 if (LoopDefIsPhi) {
2442 if (static_cast<int>(PrologStage - np) >= StageScheduled) {
2443 int LVNumStages = Schedule.getStagesForPhi(LoopVal);
2444 int StageDiff = (StageScheduled - LoopValStage);
2445 LVNumStages -= StageDiff;
2446 // Make sure the loop value Phi has been processed already.
2447 if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) {
2448 NewReg = PhiOp2;
2449 unsigned ReuseStage = CurStageNum;
2450 if (Schedule.isLoopCarried(this, *PhiInst))
2451 ReuseStage -= LVNumStages;
2452 // Check if the Phi to reuse has been generated yet. If not, then
2453 // there is nothing to reuse.
2454 if (VRMap[ReuseStage - np].count(LoopVal)) {
2455 NewReg = VRMap[ReuseStage - np][LoopVal];
Brendon Cahoon254f8892016-07-29 16:44:44 +00002456
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002457 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2458 &*BBI, Def, NewReg);
2459 // Update the map with the new Phi name.
2460 VRMap[CurStageNum - np][Def] = NewReg;
2461 PhiOp2 = NewReg;
2462 if (VRMap[LastStageNum - np - 1].count(LoopVal))
2463 PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
Brendon Cahoon254f8892016-07-29 16:44:44 +00002464
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002465 if (IsLast && np == NumPhis - 1)
2466 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2467 continue;
2468 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002469 }
Brendon Cahoone3841eea2018-08-27 22:04:50 +00002470 }
2471 if (InKernel && StageDiff > 0 &&
2472 VRMap[CurStageNum - StageDiff - np].count(LoopVal))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002473 PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
2474 }
2475
2476 const TargetRegisterClass *RC = MRI.getRegClass(Def);
2477 NewReg = MRI.createVirtualRegister(RC);
2478
2479 MachineInstrBuilder NewPhi =
2480 BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2481 TII->get(TargetOpcode::PHI), NewReg);
2482 NewPhi.addReg(PhiOp1).addMBB(BB1);
2483 NewPhi.addReg(PhiOp2).addMBB(BB2);
2484 if (np == 0)
2485 InstrMap[NewPhi] = &*BBI;
2486
2487 // We define the Phis after creating the new pipelined code, so
2488 // we need to rename the Phi values in scheduled instructions.
2489
2490 unsigned PrevReg = 0;
2491 if (InKernel && VRMap[PrevStage - np].count(LoopVal))
2492 PrevReg = VRMap[PrevStage - np][LoopVal];
2493 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2494 Def, NewReg, PrevReg);
2495 // If the Phi has been scheduled, use the new name for rewriting.
2496 if (VRMap[CurStageNum - np].count(Def)) {
2497 unsigned R = VRMap[CurStageNum - np][Def];
2498 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2499 R, NewReg);
2500 }
2501
2502 // Check if we need to rename any uses that occurs after the loop. The
2503 // register to replace depends on whether the Phi is scheduled in the
2504 // epilog.
2505 if (IsLast && np == NumPhis - 1)
2506 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2507
2508 // In the kernel, a dependent Phi uses the value from this Phi.
2509 if (InKernel)
2510 PhiOp2 = NewReg;
2511
2512 // Update the map with the new Phi name.
2513 VRMap[CurStageNum - np][Def] = NewReg;
2514 }
2515
2516 while (NumPhis++ < NumStages) {
2517 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, NumPhis,
2518 &*BBI, Def, NewReg, 0);
2519 }
2520
2521 // Check if we need to rename a Phi that has been eliminated due to
2522 // scheduling.
2523 if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
2524 replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
2525 }
2526}
2527
2528/// Generate Phis for the specified block in the generated pipelined code.
2529/// These are new Phis needed because the definition is scheduled after the
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002530/// use in the pipelined sequence.
Brendon Cahoon254f8892016-07-29 16:44:44 +00002531void SwingSchedulerDAG::generatePhis(
2532 MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2533 MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2534 InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2535 bool IsLast) {
2536 // Compute the stage number that contains the initial Phi value, and
2537 // the Phi from the previous stage.
2538 unsigned PrologStage = 0;
2539 unsigned PrevStage = 0;
2540 unsigned StageDiff = CurStageNum - LastStageNum;
2541 bool InKernel = (StageDiff == 0);
2542 if (InKernel) {
2543 PrologStage = LastStageNum - 1;
2544 PrevStage = CurStageNum;
2545 } else {
2546 PrologStage = LastStageNum - StageDiff;
2547 PrevStage = LastStageNum + StageDiff - 1;
2548 }
2549
2550 for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
2551 BBE = BB->instr_end();
2552 BBI != BBE; ++BBI) {
2553 for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
2554 MachineOperand &MO = BBI->getOperand(i);
2555 if (!MO.isReg() || !MO.isDef() ||
2556 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2557 continue;
2558
2559 int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2560 assert(StageScheduled != -1 && "Expecting scheduled instruction.");
2561 unsigned Def = MO.getReg();
2562 unsigned NumPhis = Schedule.getStagesForReg(Def, CurStageNum);
2563 // An instruction scheduled in stage 0 and is used after the loop
2564 // requires a phi in the epilog for the last definition from either
2565 // the kernel or prolog.
2566 if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
2567 hasUseAfterLoop(Def, BB, MRI))
2568 NumPhis = 1;
2569 if (!InKernel && (unsigned)StageScheduled > PrologStage)
2570 continue;
2571
2572 unsigned PhiOp2 = VRMap[PrevStage][Def];
2573 if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
2574 if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
2575 PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
2576 // The number of Phis can't exceed the number of prolog stages. The
2577 // prolog stage number is zero based.
2578 if (NumPhis > PrologStage + 1 - StageScheduled)
2579 NumPhis = PrologStage + 1 - StageScheduled;
2580 for (unsigned np = 0; np < NumPhis; ++np) {
2581 unsigned PhiOp1 = VRMap[PrologStage][Def];
2582 if (np <= PrologStage)
2583 PhiOp1 = VRMap[PrologStage - np][Def];
2584 if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) {
2585 if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2586 PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2587 if (InstOp1->isPHI() && InstOp1->getParent() == NewBB)
2588 PhiOp1 = getInitPhiReg(*InstOp1, NewBB);
2589 }
2590 if (!InKernel)
2591 PhiOp2 = VRMap[PrevStage - np][Def];
2592
2593 const TargetRegisterClass *RC = MRI.getRegClass(Def);
2594 unsigned NewReg = MRI.createVirtualRegister(RC);
2595
2596 MachineInstrBuilder NewPhi =
2597 BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2598 TII->get(TargetOpcode::PHI), NewReg);
2599 NewPhi.addReg(PhiOp1).addMBB(BB1);
2600 NewPhi.addReg(PhiOp2).addMBB(BB2);
2601 if (np == 0)
2602 InstrMap[NewPhi] = &*BBI;
2603
2604 // Rewrite uses and update the map. The actions depend upon whether
2605 // we generating code for the kernel or epilog blocks.
2606 if (InKernel) {
2607 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2608 &*BBI, PhiOp1, NewReg);
2609 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2610 &*BBI, PhiOp2, NewReg);
2611
2612 PhiOp2 = NewReg;
2613 VRMap[PrevStage - np - 1][Def] = NewReg;
2614 } else {
2615 VRMap[CurStageNum - np][Def] = NewReg;
2616 if (np == NumPhis - 1)
2617 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2618 &*BBI, Def, NewReg);
2619 }
2620 if (IsLast && np == NumPhis - 1)
2621 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2622 }
2623 }
2624 }
2625}
2626
2627/// Remove instructions that generate values with no uses.
2628/// Typically, these are induction variable operations that generate values
2629/// used in the loop itself. A dead instruction has a definition with
2630/// no uses, or uses that occur in the original loop only.
2631void SwingSchedulerDAG::removeDeadInstructions(MachineBasicBlock *KernelBB,
2632 MBBVectorTy &EpilogBBs) {
2633 // For each epilog block, check that the value defined by each instruction
2634 // is used. If not, delete it.
2635 for (MBBVectorTy::reverse_iterator MBB = EpilogBBs.rbegin(),
2636 MBE = EpilogBBs.rend();
2637 MBB != MBE; ++MBB)
2638 for (MachineBasicBlock::reverse_instr_iterator MI = (*MBB)->instr_rbegin(),
2639 ME = (*MBB)->instr_rend();
2640 MI != ME;) {
2641 // From DeadMachineInstructionElem. Don't delete inline assembly.
2642 if (MI->isInlineAsm()) {
2643 ++MI;
2644 continue;
2645 }
2646 bool SawStore = false;
2647 // Check if it's safe to remove the instruction due to side effects.
2648 // We can, and want to, remove Phis here.
2649 if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
2650 ++MI;
2651 continue;
2652 }
2653 bool used = true;
2654 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
2655 MOE = MI->operands_end();
2656 MOI != MOE; ++MOI) {
2657 if (!MOI->isReg() || !MOI->isDef())
2658 continue;
2659 unsigned reg = MOI->getReg();
Krzysztof Parzyszekb9b75b82018-03-26 15:53:23 +00002660 // Assume physical registers are used, unless they are marked dead.
2661 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
2662 used = !MOI->isDead();
2663 if (used)
2664 break;
2665 continue;
2666 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002667 unsigned realUses = 0;
2668 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(reg),
2669 EI = MRI.use_end();
2670 UI != EI; ++UI) {
2671 // Check if there are any uses that occur only in the original
2672 // loop. If so, that's not a real use.
2673 if (UI->getParent()->getParent() != BB) {
2674 realUses++;
2675 used = true;
2676 break;
2677 }
2678 }
2679 if (realUses > 0)
2680 break;
2681 used = false;
2682 }
2683 if (!used) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00002684 LIS.RemoveMachineInstrFromMaps(*MI);
Duncan P. N. Exon Smith5c001c32016-08-30 00:13:12 +00002685 MI++->eraseFromParent();
Brendon Cahoon254f8892016-07-29 16:44:44 +00002686 continue;
2687 }
2688 ++MI;
2689 }
2690 // In the kernel block, check if we can remove a Phi that generates a value
2691 // used in an instruction removed in the epilog block.
2692 for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(),
2693 BBE = KernelBB->getFirstNonPHI();
2694 BBI != BBE;) {
2695 MachineInstr *MI = &*BBI;
2696 ++BBI;
2697 unsigned reg = MI->getOperand(0).getReg();
2698 if (MRI.use_begin(reg) == MRI.use_end()) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00002699 LIS.RemoveMachineInstrFromMaps(*MI);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002700 MI->eraseFromParent();
2701 }
2702 }
2703}
2704
2705/// For loop carried definitions, we split the lifetime of a virtual register
2706/// that has uses past the definition in the next iteration. A copy with a new
2707/// virtual register is inserted before the definition, which helps with
2708/// generating a better register assignment.
2709///
2710/// v1 = phi(a, v2) v1 = phi(a, v2)
2711/// v2 = phi(b, v3) v2 = phi(b, v3)
2712/// v3 = .. v4 = copy v1
2713/// .. = V1 v3 = ..
2714/// .. = v4
2715void SwingSchedulerDAG::splitLifetimes(MachineBasicBlock *KernelBB,
2716 MBBVectorTy &EpilogBBs,
2717 SMSchedule &Schedule) {
2718 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Bob Wilson90ecac02018-01-04 02:58:15 +00002719 for (auto &PHI : KernelBB->phis()) {
2720 unsigned Def = PHI.getOperand(0).getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00002721 // Check for any Phi definition that used as an operand of another Phi
2722 // in the same block.
2723 for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
2724 E = MRI.use_instr_end();
2725 I != E; ++I) {
2726 if (I->isPHI() && I->getParent() == KernelBB) {
2727 // Get the loop carried definition.
Bob Wilson90ecac02018-01-04 02:58:15 +00002728 unsigned LCDef = getLoopPhiReg(PHI, KernelBB);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002729 if (!LCDef)
2730 continue;
2731 MachineInstr *MI = MRI.getVRegDef(LCDef);
2732 if (!MI || MI->getParent() != KernelBB || MI->isPHI())
2733 continue;
2734 // Search through the rest of the block looking for uses of the Phi
2735 // definition. If one occurs, then split the lifetime.
2736 unsigned SplitReg = 0;
2737 for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
2738 KernelBB->instr_end()))
2739 if (BBJ.readsRegister(Def)) {
2740 // We split the lifetime when we find the first use.
2741 if (SplitReg == 0) {
2742 SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
2743 BuildMI(*KernelBB, MI, MI->getDebugLoc(),
2744 TII->get(TargetOpcode::COPY), SplitReg)
2745 .addReg(Def);
2746 }
2747 BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
2748 }
2749 if (!SplitReg)
2750 continue;
2751 // Search through each of the epilog blocks for any uses to be renamed.
2752 for (auto &Epilog : EpilogBBs)
2753 for (auto &I : *Epilog)
2754 if (I.readsRegister(Def))
2755 I.substituteRegister(Def, SplitReg, 0, *TRI);
2756 break;
2757 }
2758 }
2759 }
2760}
2761
2762/// Remove the incoming block from the Phis in a basic block.
2763static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
2764 for (MachineInstr &MI : *BB) {
2765 if (!MI.isPHI())
2766 break;
2767 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
2768 if (MI.getOperand(i + 1).getMBB() == Incoming) {
2769 MI.RemoveOperand(i + 1);
2770 MI.RemoveOperand(i);
2771 break;
2772 }
2773 }
2774}
2775
2776/// Create branches from each prolog basic block to the appropriate epilog
2777/// block. These edges are needed if the loop ends before reaching the
2778/// kernel.
Jinsong Jief2d6d92019-06-11 17:40:39 +00002779void SwingSchedulerDAG::addBranches(MachineBasicBlock &PreheaderBB,
2780 MBBVectorTy &PrologBBs,
Brendon Cahoon254f8892016-07-29 16:44:44 +00002781 MachineBasicBlock *KernelBB,
2782 MBBVectorTy &EpilogBBs,
2783 SMSchedule &Schedule, ValueMapTy *VRMap) {
2784 assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
2785 MachineInstr *IndVar = Pass.LI.LoopInductionVar;
2786 MachineInstr *Cmp = Pass.LI.LoopCompare;
2787 MachineBasicBlock *LastPro = KernelBB;
2788 MachineBasicBlock *LastEpi = KernelBB;
2789
2790 // Start from the blocks connected to the kernel and work "out"
2791 // to the first prolog and the last epilog blocks.
2792 SmallVector<MachineInstr *, 4> PrevInsts;
2793 unsigned MaxIter = PrologBBs.size() - 1;
2794 unsigned LC = UINT_MAX;
2795 unsigned LCMin = UINT_MAX;
2796 for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
2797 // Add branches to the prolog that go to the corresponding
2798 // epilog, and the fall-thru prolog/kernel block.
2799 MachineBasicBlock *Prolog = PrologBBs[j];
2800 MachineBasicBlock *Epilog = EpilogBBs[i];
2801 // We've executed one iteration, so decrement the loop count and check for
2802 // the loop end.
2803 SmallVector<MachineOperand, 4> Cond;
2804 // Check if the LOOP0 has already been removed. If so, then there is no need
2805 // to reduce the trip count.
2806 if (LC != 0)
Jinsong Jief2d6d92019-06-11 17:40:39 +00002807 LC = TII->reduceLoopCount(*Prolog, PreheaderBB, IndVar, *Cmp, Cond,
2808 PrevInsts, j, MaxIter);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002809
2810 // Record the value of the first trip count, which is used to determine if
2811 // branches and blocks can be removed for constant trip counts.
2812 if (LCMin == UINT_MAX)
2813 LCMin = LC;
2814
2815 unsigned numAdded = 0;
2816 if (TargetRegisterInfo::isVirtualRegister(LC)) {
2817 Prolog->addSuccessor(Epilog);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002818 numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002819 } else if (j >= LCMin) {
2820 Prolog->addSuccessor(Epilog);
2821 Prolog->removeSuccessor(LastPro);
2822 LastEpi->removeSuccessor(Epilog);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002823 numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002824 removePhis(Epilog, LastEpi);
2825 // Remove the blocks that are no longer referenced.
2826 if (LastPro != LastEpi) {
2827 LastEpi->clear();
2828 LastEpi->eraseFromParent();
2829 }
2830 LastPro->clear();
2831 LastPro->eraseFromParent();
2832 } else {
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002833 numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002834 removePhis(Epilog, Prolog);
2835 }
2836 LastPro = Prolog;
2837 LastEpi = Epilog;
2838 for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
2839 E = Prolog->instr_rend();
2840 I != E && numAdded > 0; ++I, --numAdded)
2841 updateInstruction(&*I, false, j, 0, Schedule, VRMap);
2842 }
2843}
2844
2845/// Return true if we can compute the amount the instruction changes
2846/// during each iteration. Set Delta to the amount of the change.
2847bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
2848 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +00002849 const MachineOperand *BaseOp;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002850 int64_t Offset;
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00002851 if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002852 return false;
2853
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00002854 if (!BaseOp->isReg())
2855 return false;
2856
2857 unsigned BaseReg = BaseOp->getReg();
2858
Brendon Cahoon254f8892016-07-29 16:44:44 +00002859 MachineRegisterInfo &MRI = MF.getRegInfo();
2860 // Check if there is a Phi. If so, get the definition in the loop.
2861 MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
2862 if (BaseDef && BaseDef->isPHI()) {
2863 BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
2864 BaseDef = MRI.getVRegDef(BaseReg);
2865 }
2866 if (!BaseDef)
2867 return false;
2868
2869 int D = 0;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002870 if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
Brendon Cahoon254f8892016-07-29 16:44:44 +00002871 return false;
2872
2873 Delta = D;
2874 return true;
2875}
2876
2877/// Update the memory operand with a new offset when the pipeliner
Justin Lebarcf56e922016-08-12 23:58:19 +00002878/// generates a new copy of the instruction that refers to a
Brendon Cahoon254f8892016-07-29 16:44:44 +00002879/// different memory location.
2880void SwingSchedulerDAG::updateMemOperands(MachineInstr &NewMI,
2881 MachineInstr &OldMI, unsigned Num) {
2882 if (Num == 0)
2883 return;
2884 // If the instruction has memory operands, then adjust the offset
2885 // when the instruction appears in different stages.
Chandler Carruthc73c0302018-08-16 21:30:05 +00002886 if (NewMI.memoperands_empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00002887 return;
Chandler Carruthc73c0302018-08-16 21:30:05 +00002888 SmallVector<MachineMemOperand *, 2> NewMMOs;
Justin Lebar0a33a7a2016-08-23 17:18:07 +00002889 for (MachineMemOperand *MMO : NewMI.memoperands()) {
Philip Reames00056ed2019-02-01 22:58:52 +00002890 // TODO: Figure out whether isAtomic is really necessary (see D57601).
2891 if (MMO->isVolatile() || MMO->isAtomic() ||
2892 (MMO->isInvariant() && MMO->isDereferenceable()) ||
Justin Lebaradbf09e2016-09-11 01:38:58 +00002893 (!MMO->getValue())) {
Chandler Carruthc73c0302018-08-16 21:30:05 +00002894 NewMMOs.push_back(MMO);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002895 continue;
2896 }
2897 unsigned Delta;
Krzysztof Parzyszek785b6ce2018-03-26 15:45:55 +00002898 if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00002899 int64_t AdjOffset = Delta * Num;
Chandler Carruthc73c0302018-08-16 21:30:05 +00002900 NewMMOs.push_back(
2901 MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize()));
Krzysztof Parzyszek2d790172018-02-27 22:40:52 +00002902 } else {
Krzysztof Parzyszekcc3f6302018-08-20 20:37:57 +00002903 NewMMOs.push_back(
2904 MF.getMachineMemOperand(MMO, 0, MemoryLocation::UnknownSize));
Krzysztof Parzyszek2d790172018-02-27 22:40:52 +00002905 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002906 }
Chandler Carruthc73c0302018-08-16 21:30:05 +00002907 NewMI.setMemRefs(MF, NewMMOs);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002908}
2909
2910/// Clone the instruction for the new pipelined loop and update the
2911/// memory operands, if needed.
2912MachineInstr *SwingSchedulerDAG::cloneInstr(MachineInstr *OldMI,
2913 unsigned CurStageNum,
2914 unsigned InstStageNum) {
2915 MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
2916 // Check for tied operands in inline asm instructions. This should be handled
2917 // elsewhere, but I'm not sure of the best solution.
2918 if (OldMI->isInlineAsm())
2919 for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
2920 const auto &MO = OldMI->getOperand(i);
2921 if (MO.isReg() && MO.isUse())
2922 break;
2923 unsigned UseIdx;
2924 if (OldMI->isRegTiedToUseOperand(i, &UseIdx))
2925 NewMI->tieOperands(i, UseIdx);
2926 }
2927 updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
2928 return NewMI;
2929}
2930
2931/// Clone the instruction for the new pipelined loop. If needed, this
2932/// function updates the instruction using the values saved in the
2933/// InstrChanges structure.
2934MachineInstr *SwingSchedulerDAG::cloneAndChangeInstr(MachineInstr *OldMI,
2935 unsigned CurStageNum,
2936 unsigned InstStageNum,
2937 SMSchedule &Schedule) {
2938 MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
2939 DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
2940 InstrChanges.find(getSUnit(OldMI));
2941 if (It != InstrChanges.end()) {
2942 std::pair<unsigned, int64_t> RegAndOffset = It->second;
2943 unsigned BasePos, OffsetPos;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002944 if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002945 return nullptr;
2946 int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
2947 MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
2948 if (Schedule.stageScheduled(getSUnit(LoopDef)) > (signed)InstStageNum)
2949 NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
2950 NewMI->getOperand(OffsetPos).setImm(NewOffset);
2951 }
2952 updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
2953 return NewMI;
2954}
2955
2956/// Update the machine instruction with new virtual registers. This
2957/// function may change the defintions and/or uses.
2958void SwingSchedulerDAG::updateInstruction(MachineInstr *NewMI, bool LastDef,
2959 unsigned CurStageNum,
2960 unsigned InstrStageNum,
2961 SMSchedule &Schedule,
2962 ValueMapTy *VRMap) {
2963 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
2964 MachineOperand &MO = NewMI->getOperand(i);
2965 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2966 continue;
2967 unsigned reg = MO.getReg();
2968 if (MO.isDef()) {
2969 // Create a new virtual register for the definition.
2970 const TargetRegisterClass *RC = MRI.getRegClass(reg);
2971 unsigned NewReg = MRI.createVirtualRegister(RC);
2972 MO.setReg(NewReg);
2973 VRMap[CurStageNum][reg] = NewReg;
2974 if (LastDef)
2975 replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
2976 } else if (MO.isUse()) {
2977 MachineInstr *Def = MRI.getVRegDef(reg);
2978 // Compute the stage that contains the last definition for instruction.
2979 int DefStageNum = Schedule.stageScheduled(getSUnit(Def));
2980 unsigned StageNum = CurStageNum;
2981 if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
2982 // Compute the difference in stages between the defintion and the use.
2983 unsigned StageDiff = (InstrStageNum - DefStageNum);
2984 // Make an adjustment to get the last definition.
2985 StageNum -= StageDiff;
2986 }
2987 if (VRMap[StageNum].count(reg))
2988 MO.setReg(VRMap[StageNum][reg]);
2989 }
2990 }
2991}
2992
2993/// Return the instruction in the loop that defines the register.
2994/// If the definition is a Phi, then follow the Phi operand to
2995/// the instruction in the loop.
2996MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) {
2997 SmallPtrSet<MachineInstr *, 8> Visited;
2998 MachineInstr *Def = MRI.getVRegDef(Reg);
2999 while (Def->isPHI()) {
3000 if (!Visited.insert(Def).second)
3001 break;
3002 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
3003 if (Def->getOperand(i + 1).getMBB() == BB) {
3004 Def = MRI.getVRegDef(Def->getOperand(i).getReg());
3005 break;
3006 }
3007 }
3008 return Def;
3009}
3010
3011/// Return the new name for the value from the previous stage.
3012unsigned SwingSchedulerDAG::getPrevMapVal(unsigned StageNum, unsigned PhiStage,
3013 unsigned LoopVal, unsigned LoopStage,
3014 ValueMapTy *VRMap,
3015 MachineBasicBlock *BB) {
3016 unsigned PrevVal = 0;
3017 if (StageNum > PhiStage) {
3018 MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
3019 if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
3020 // The name is defined in the previous stage.
3021 PrevVal = VRMap[StageNum - 1][LoopVal];
3022 else if (VRMap[StageNum].count(LoopVal))
3023 // The previous name is defined in the current stage when the instruction
3024 // order is swapped.
3025 PrevVal = VRMap[StageNum][LoopVal];
Krzysztof Parzyszekdf24da22016-12-22 18:49:55 +00003026 else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003027 // The loop value hasn't yet been scheduled.
3028 PrevVal = LoopVal;
3029 else if (StageNum == PhiStage + 1)
3030 // The loop value is another phi, which has not been scheduled.
3031 PrevVal = getInitPhiReg(*LoopInst, BB);
3032 else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
3033 // The loop value is another phi, which has been scheduled.
3034 PrevVal =
3035 getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
3036 LoopStage, VRMap, BB);
3037 }
3038 return PrevVal;
3039}
3040
3041/// Rewrite the Phi values in the specified block to use the mappings
3042/// from the initial operand. Once the Phi is scheduled, we switch
3043/// to using the loop value instead of the Phi value, so those names
3044/// do not need to be rewritten.
3045void SwingSchedulerDAG::rewritePhiValues(MachineBasicBlock *NewBB,
3046 unsigned StageNum,
3047 SMSchedule &Schedule,
3048 ValueMapTy *VRMap,
3049 InstrMapTy &InstrMap) {
Bob Wilson90ecac02018-01-04 02:58:15 +00003050 for (auto &PHI : BB->phis()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003051 unsigned InitVal = 0;
3052 unsigned LoopVal = 0;
Bob Wilson90ecac02018-01-04 02:58:15 +00003053 getPhiRegs(PHI, BB, InitVal, LoopVal);
3054 unsigned PhiDef = PHI.getOperand(0).getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00003055
3056 unsigned PhiStage =
3057 (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(PhiDef)));
3058 unsigned LoopStage =
3059 (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
3060 unsigned NumPhis = Schedule.getStagesForPhi(PhiDef);
3061 if (NumPhis > StageNum)
3062 NumPhis = StageNum;
3063 for (unsigned np = 0; np <= NumPhis; ++np) {
3064 unsigned NewVal =
3065 getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
3066 if (!NewVal)
3067 NewVal = InitVal;
Bob Wilson90ecac02018-01-04 02:58:15 +00003068 rewriteScheduledInstr(NewBB, Schedule, InstrMap, StageNum - np, np, &PHI,
Brendon Cahoon254f8892016-07-29 16:44:44 +00003069 PhiDef, NewVal);
3070 }
3071 }
3072}
3073
3074/// Rewrite a previously scheduled instruction to use the register value
3075/// from the new instruction. Make sure the instruction occurs in the
3076/// basic block, and we don't change the uses in the new instruction.
3077void SwingSchedulerDAG::rewriteScheduledInstr(
3078 MachineBasicBlock *BB, SMSchedule &Schedule, InstrMapTy &InstrMap,
3079 unsigned CurStageNum, unsigned PhiNum, MachineInstr *Phi, unsigned OldReg,
3080 unsigned NewReg, unsigned PrevReg) {
3081 bool InProlog = (CurStageNum < Schedule.getMaxStageCount());
3082 int StagePhi = Schedule.stageScheduled(getSUnit(Phi)) + PhiNum;
3083 // Rewrite uses that have been scheduled already to use the new
3084 // Phi register.
3085 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(OldReg),
3086 EI = MRI.use_end();
3087 UI != EI;) {
3088 MachineOperand &UseOp = *UI;
3089 MachineInstr *UseMI = UseOp.getParent();
3090 ++UI;
3091 if (UseMI->getParent() != BB)
3092 continue;
3093 if (UseMI->isPHI()) {
3094 if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
3095 continue;
3096 if (getLoopPhiReg(*UseMI, BB) != OldReg)
3097 continue;
3098 }
3099 InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
3100 assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
3101 SUnit *OrigMISU = getSUnit(OrigInstr->second);
3102 int StageSched = Schedule.stageScheduled(OrigMISU);
3103 int CycleSched = Schedule.cycleScheduled(OrigMISU);
3104 unsigned ReplaceReg = 0;
3105 // This is the stage for the scheduled instruction.
3106 if (StagePhi == StageSched && Phi->isPHI()) {
3107 int CyclePhi = Schedule.cycleScheduled(getSUnit(Phi));
3108 if (PrevReg && InProlog)
3109 ReplaceReg = PrevReg;
3110 else if (PrevReg && !Schedule.isLoopCarried(this, *Phi) &&
3111 (CyclePhi <= CycleSched || OrigMISU->getInstr()->isPHI()))
3112 ReplaceReg = PrevReg;
3113 else
3114 ReplaceReg = NewReg;
3115 }
3116 // The scheduled instruction occurs before the scheduled Phi, and the
3117 // Phi is not loop carried.
3118 if (!InProlog && StagePhi + 1 == StageSched &&
3119 !Schedule.isLoopCarried(this, *Phi))
3120 ReplaceReg = NewReg;
3121 if (StagePhi > StageSched && Phi->isPHI())
3122 ReplaceReg = NewReg;
3123 if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
3124 ReplaceReg = NewReg;
3125 if (ReplaceReg) {
3126 MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
3127 UseOp.setReg(ReplaceReg);
3128 }
3129 }
3130}
3131
3132/// Check if we can change the instruction to use an offset value from the
3133/// previous iteration. If so, return true and set the base and offset values
3134/// so that we can rewrite the load, if necessary.
3135/// v1 = Phi(v0, v3)
3136/// v2 = load v1, 0
3137/// v3 = post_store v1, 4, x
3138/// This function enables the load to be rewritten as v2 = load v3, 4.
3139bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
3140 unsigned &BasePos,
3141 unsigned &OffsetPos,
3142 unsigned &NewBase,
3143 int64_t &Offset) {
3144 // Get the load instruction.
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003145 if (TII->isPostIncrement(*MI))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003146 return false;
3147 unsigned BasePosLd, OffsetPosLd;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003148 if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003149 return false;
3150 unsigned BaseReg = MI->getOperand(BasePosLd).getReg();
3151
3152 // Look for the Phi instruction.
Justin Bognerfdf9bf42017-10-10 23:50:49 +00003153 MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
Brendon Cahoon254f8892016-07-29 16:44:44 +00003154 MachineInstr *Phi = MRI.getVRegDef(BaseReg);
3155 if (!Phi || !Phi->isPHI())
3156 return false;
3157 // Get the register defined in the loop block.
3158 unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
3159 if (!PrevReg)
3160 return false;
3161
3162 // Check for the post-increment load/store instruction.
3163 MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
3164 if (!PrevDef || PrevDef == MI)
3165 return false;
3166
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003167 if (!TII->isPostIncrement(*PrevDef))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003168 return false;
3169
3170 unsigned BasePos1 = 0, OffsetPos1 = 0;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003171 if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003172 return false;
3173
Krzysztof Parzyszek40df8a22018-03-26 16:17:06 +00003174 // Make sure that the instructions do not access the same memory location in
3175 // the next iteration.
Brendon Cahoon254f8892016-07-29 16:44:44 +00003176 int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
3177 int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
Krzysztof Parzyszek40df8a22018-03-26 16:17:06 +00003178 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3179 NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
3180 bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
3181 MF.DeleteMachineInstr(NewMI);
3182 if (!Disjoint)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003183 return false;
3184
3185 // Set the return value once we determine that we return true.
3186 BasePos = BasePosLd;
3187 OffsetPos = OffsetPosLd;
3188 NewBase = PrevReg;
3189 Offset = StoreOffset;
3190 return true;
3191}
3192
3193/// Apply changes to the instruction if needed. The changes are need
3194/// to improve the scheduling and depend up on the final schedule.
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003195void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
3196 SMSchedule &Schedule) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003197 SUnit *SU = getSUnit(MI);
3198 DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3199 InstrChanges.find(SU);
3200 if (It != InstrChanges.end()) {
3201 std::pair<unsigned, int64_t> RegAndOffset = It->second;
3202 unsigned BasePos, OffsetPos;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003203 if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003204 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003205 unsigned BaseReg = MI->getOperand(BasePos).getReg();
3206 MachineInstr *LoopDef = findDefInLoop(BaseReg);
3207 int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
3208 int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
3209 int BaseStageNum = Schedule.stageScheduled(SU);
3210 int BaseCycleNum = Schedule.cycleScheduled(SU);
3211 if (BaseStageNum < DefStageNum) {
3212 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3213 int OffsetDiff = DefStageNum - BaseStageNum;
3214 if (DefCycleNum < BaseCycleNum) {
3215 NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
3216 if (OffsetDiff > 0)
3217 --OffsetDiff;
3218 }
3219 int64_t NewOffset =
3220 MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
3221 NewMI->getOperand(OffsetPos).setImm(NewOffset);
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003222 SU->setInstr(NewMI);
3223 MISUnitMap[NewMI] = SU;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003224 NewMIs.insert(NewMI);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003225 }
3226 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003227}
3228
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003229/// Return true for an order or output dependence that is loop carried
3230/// potentially. A dependence is loop carried if the destination defines a valu
3231/// that may be used or defined by the source in a subsequent iteration.
3232bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
3233 bool isSucc) {
3234 if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
3235 Dep.isArtificial())
Brendon Cahoon254f8892016-07-29 16:44:44 +00003236 return false;
3237
3238 if (!SwpPruneLoopCarried)
3239 return true;
3240
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003241 if (Dep.getKind() == SDep::Output)
3242 return true;
3243
Brendon Cahoon254f8892016-07-29 16:44:44 +00003244 MachineInstr *SI = Source->getInstr();
3245 MachineInstr *DI = Dep.getSUnit()->getInstr();
3246 if (!isSucc)
3247 std::swap(SI, DI);
3248 assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
3249
3250 // Assume ordered loads and stores may have a loop carried dependence.
3251 if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
Ulrich Weigand6c5d5ce2019-06-05 22:33:10 +00003252 SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
Brendon Cahoon254f8892016-07-29 16:44:44 +00003253 SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
3254 return true;
3255
3256 // Only chain dependences between a load and store can be loop carried.
3257 if (!DI->mayStore() || !SI->mayLoad())
3258 return false;
3259
3260 unsigned DeltaS, DeltaD;
3261 if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
3262 return true;
3263
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +00003264 const MachineOperand *BaseOpS, *BaseOpD;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003265 int64_t OffsetS, OffsetD;
3266 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00003267 if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, TRI) ||
3268 !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, TRI))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003269 return true;
3270
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00003271 if (!BaseOpS->isIdenticalTo(*BaseOpD))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003272 return true;
3273
Krzysztof Parzyszek8c07d0c2018-03-26 16:58:40 +00003274 // Check that the base register is incremented by a constant value for each
3275 // iteration.
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00003276 MachineInstr *Def = MRI.getVRegDef(BaseOpS->getReg());
Krzysztof Parzyszek8c07d0c2018-03-26 16:58:40 +00003277 if (!Def || !Def->isPHI())
3278 return true;
3279 unsigned InitVal = 0;
3280 unsigned LoopVal = 0;
3281 getPhiRegs(*Def, BB, InitVal, LoopVal);
3282 MachineInstr *LoopDef = MRI.getVRegDef(LoopVal);
3283 int D = 0;
3284 if (!LoopDef || !TII->getIncrementValue(*LoopDef, D))
3285 return true;
3286
Brendon Cahoon254f8892016-07-29 16:44:44 +00003287 uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
3288 uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
3289
3290 // This is the main test, which checks the offset values and the loop
3291 // increment value to determine if the accesses may be loop carried.
Brendon Cahoon57c3d4b2019-04-11 21:57:51 +00003292 if (AccessSizeS == MemoryLocation::UnknownSize ||
3293 AccessSizeD == MemoryLocation::UnknownSize)
3294 return true;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003295
Brendon Cahoon57c3d4b2019-04-11 21:57:51 +00003296 if (DeltaS != DeltaD || DeltaS < AccessSizeS || DeltaD < AccessSizeD)
3297 return true;
3298
3299 return (OffsetS + (int64_t)AccessSizeS < OffsetD + (int64_t)AccessSizeD);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003300}
3301
Krzysztof Parzyszek88391242016-12-22 19:21:20 +00003302void SwingSchedulerDAG::postprocessDAG() {
3303 for (auto &M : Mutations)
3304 M->apply(this);
3305}
3306
Brendon Cahoon254f8892016-07-29 16:44:44 +00003307/// Try to schedule the node at the specified StartCycle and continue
3308/// until the node is schedule or the EndCycle is reached. This function
3309/// returns true if the node is scheduled. This routine may search either
3310/// forward or backward for a place to insert the instruction based upon
3311/// the relative values of StartCycle and EndCycle.
3312bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
3313 bool forward = true;
Jinsong Ji18e7bf52019-05-31 15:35:19 +00003314 LLVM_DEBUG({
3315 dbgs() << "Trying to insert node between " << StartCycle << " and "
3316 << EndCycle << " II: " << II << "\n";
3317 });
Brendon Cahoon254f8892016-07-29 16:44:44 +00003318 if (StartCycle > EndCycle)
3319 forward = false;
3320
3321 // The terminating condition depends on the direction.
3322 int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
3323 for (int curCycle = StartCycle; curCycle != termCycle;
3324 forward ? ++curCycle : --curCycle) {
3325
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003326 // Add the already scheduled instructions at the specified cycle to the
3327 // DFA.
3328 ProcItinResources.clearResources();
Brendon Cahoon254f8892016-07-29 16:44:44 +00003329 for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
3330 checkCycle <= LastCycle; checkCycle += II) {
3331 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
3332
3333 for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(),
3334 E = cycleInstrs.end();
3335 I != E; ++I) {
3336 if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
3337 continue;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003338 assert(ProcItinResources.canReserveResources(*(*I)->getInstr()) &&
Brendon Cahoon254f8892016-07-29 16:44:44 +00003339 "These instructions have already been scheduled.");
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003340 ProcItinResources.reserveResources(*(*I)->getInstr());
Brendon Cahoon254f8892016-07-29 16:44:44 +00003341 }
3342 }
3343 if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003344 ProcItinResources.canReserveResources(*SU->getInstr())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003345 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00003346 dbgs() << "\tinsert at cycle " << curCycle << " ";
3347 SU->getInstr()->dump();
3348 });
3349
3350 ScheduledInstrs[curCycle].push_back(SU);
3351 InstrToCycle.insert(std::make_pair(SU, curCycle));
3352 if (curCycle > LastCycle)
3353 LastCycle = curCycle;
3354 if (curCycle < FirstCycle)
3355 FirstCycle = curCycle;
3356 return true;
3357 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003358 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00003359 dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
3360 SU->getInstr()->dump();
3361 });
3362 }
3363 return false;
3364}
3365
3366// Return the cycle of the earliest scheduled instruction in the chain.
3367int SMSchedule::earliestCycleInChain(const SDep &Dep) {
3368 SmallPtrSet<SUnit *, 8> Visited;
3369 SmallVector<SDep, 8> Worklist;
3370 Worklist.push_back(Dep);
3371 int EarlyCycle = INT_MAX;
3372 while (!Worklist.empty()) {
3373 const SDep &Cur = Worklist.pop_back_val();
3374 SUnit *PrevSU = Cur.getSUnit();
3375 if (Visited.count(PrevSU))
3376 continue;
3377 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
3378 if (it == InstrToCycle.end())
3379 continue;
3380 EarlyCycle = std::min(EarlyCycle, it->second);
3381 for (const auto &PI : PrevSU->Preds)
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003382 if (PI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003383 Worklist.push_back(PI);
3384 Visited.insert(PrevSU);
3385 }
3386 return EarlyCycle;
3387}
3388
3389// Return the cycle of the latest scheduled instruction in the chain.
3390int SMSchedule::latestCycleInChain(const SDep &Dep) {
3391 SmallPtrSet<SUnit *, 8> Visited;
3392 SmallVector<SDep, 8> Worklist;
3393 Worklist.push_back(Dep);
3394 int LateCycle = INT_MIN;
3395 while (!Worklist.empty()) {
3396 const SDep &Cur = Worklist.pop_back_val();
3397 SUnit *SuccSU = Cur.getSUnit();
3398 if (Visited.count(SuccSU))
3399 continue;
3400 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
3401 if (it == InstrToCycle.end())
3402 continue;
3403 LateCycle = std::max(LateCycle, it->second);
3404 for (const auto &SI : SuccSU->Succs)
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003405 if (SI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003406 Worklist.push_back(SI);
3407 Visited.insert(SuccSU);
3408 }
3409 return LateCycle;
3410}
3411
3412/// If an instruction has a use that spans multiple iterations, then
3413/// return true. These instructions are characterized by having a back-ege
3414/// to a Phi, which contains a reference to another Phi.
3415static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
3416 for (auto &P : SU->Preds)
3417 if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
3418 for (auto &S : P.getSUnit()->Succs)
Krzysztof Parzyszekb9b75b82018-03-26 15:53:23 +00003419 if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
Brendon Cahoon254f8892016-07-29 16:44:44 +00003420 return P.getSUnit();
3421 return nullptr;
3422}
3423
3424/// Compute the scheduling start slot for the instruction. The start slot
3425/// depends on any predecessor or successor nodes scheduled already.
3426void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
3427 int *MinEnd, int *MaxStart, int II,
3428 SwingSchedulerDAG *DAG) {
3429 // Iterate over each instruction that has been scheduled already. The start
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003430 // slot computation depends on whether the previously scheduled instruction
Brendon Cahoon254f8892016-07-29 16:44:44 +00003431 // is a predecessor or successor of the specified instruction.
3432 for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
3433
3434 // Iterate over each instruction in the current cycle.
3435 for (SUnit *I : getInstructions(cycle)) {
3436 // Because we're processing a DAG for the dependences, we recognize
3437 // the back-edge in recurrences by anti dependences.
3438 for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
3439 const SDep &Dep = SU->Preds[i];
3440 if (Dep.getSUnit() == I) {
3441 if (!DAG->isBackedge(SU, Dep)) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003442 int EarlyStart = cycle + Dep.getLatency() -
Brendon Cahoon254f8892016-07-29 16:44:44 +00003443 DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3444 *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003445 if (DAG->isLoopCarriedDep(SU, Dep, false)) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003446 int End = earliestCycleInChain(Dep) + (II - 1);
3447 *MinEnd = std::min(*MinEnd, End);
3448 }
3449 } else {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003450 int LateStart = cycle - Dep.getLatency() +
Brendon Cahoon254f8892016-07-29 16:44:44 +00003451 DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3452 *MinLateStart = std::min(*MinLateStart, LateStart);
3453 }
3454 }
3455 // For instruction that requires multiple iterations, make sure that
3456 // the dependent instruction is not scheduled past the definition.
3457 SUnit *BE = multipleIterations(I, DAG);
3458 if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
3459 !SU->isPred(I))
3460 *MinLateStart = std::min(*MinLateStart, cycle);
3461 }
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00003462 for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003463 if (SU->Succs[i].getSUnit() == I) {
3464 const SDep &Dep = SU->Succs[i];
3465 if (!DAG->isBackedge(SU, Dep)) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003466 int LateStart = cycle - Dep.getLatency() +
Brendon Cahoon254f8892016-07-29 16:44:44 +00003467 DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3468 *MinLateStart = std::min(*MinLateStart, LateStart);
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003469 if (DAG->isLoopCarriedDep(SU, Dep)) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003470 int Start = latestCycleInChain(Dep) + 1 - II;
3471 *MaxStart = std::max(*MaxStart, Start);
3472 }
3473 } else {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00003474 int EarlyStart = cycle + Dep.getLatency() -
Brendon Cahoon254f8892016-07-29 16:44:44 +00003475 DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3476 *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
3477 }
3478 }
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00003479 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003480 }
3481 }
3482}
3483
3484/// Order the instructions within a cycle so that the definitions occur
3485/// before the uses. Returns true if the instruction is added to the start
3486/// of the list, or false if added to the end.
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003487void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
Brendon Cahoon254f8892016-07-29 16:44:44 +00003488 std::deque<SUnit *> &Insts) {
3489 MachineInstr *MI = SU->getInstr();
3490 bool OrderBeforeUse = false;
3491 bool OrderAfterDef = false;
3492 bool OrderBeforeDef = false;
3493 unsigned MoveDef = 0;
3494 unsigned MoveUse = 0;
3495 int StageInst1 = stageScheduled(SU);
3496
3497 unsigned Pos = 0;
3498 for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
3499 ++I, ++Pos) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003500 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3501 MachineOperand &MO = MI->getOperand(i);
3502 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
3503 continue;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003504
Brendon Cahoon254f8892016-07-29 16:44:44 +00003505 unsigned Reg = MO.getReg();
3506 unsigned BasePos, OffsetPos;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00003507 if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003508 if (MI->getOperand(BasePos).getReg() == Reg)
3509 if (unsigned NewReg = SSD->getInstrBaseReg(SU))
3510 Reg = NewReg;
3511 bool Reads, Writes;
3512 std::tie(Reads, Writes) =
3513 (*I)->getInstr()->readsWritesVirtualRegister(Reg);
3514 if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
3515 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003516 if (MoveUse == 0)
3517 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003518 } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
3519 // Add the instruction after the scheduled instruction.
3520 OrderAfterDef = true;
3521 MoveDef = Pos;
3522 } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
3523 if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
3524 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003525 if (MoveUse == 0)
3526 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003527 } else {
3528 OrderAfterDef = true;
3529 MoveDef = Pos;
3530 }
3531 } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
3532 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003533 if (MoveUse == 0)
3534 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003535 if (MoveUse != 0) {
3536 OrderAfterDef = true;
3537 MoveDef = Pos - 1;
3538 }
3539 } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
3540 // Add the instruction before the scheduled instruction.
3541 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003542 if (MoveUse == 0)
3543 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003544 } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
3545 isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003546 if (MoveUse == 0) {
3547 OrderBeforeDef = true;
3548 MoveUse = Pos;
3549 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003550 }
3551 }
3552 // Check for order dependences between instructions. Make sure the source
3553 // is ordered before the destination.
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003554 for (auto &S : SU->Succs) {
3555 if (S.getSUnit() != *I)
3556 continue;
3557 if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3558 OrderBeforeUse = true;
3559 if (Pos < MoveUse)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003560 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003561 }
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003562 }
3563 for (auto &P : SU->Preds) {
3564 if (P.getSUnit() != *I)
3565 continue;
3566 if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3567 OrderAfterDef = true;
3568 MoveDef = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003569 }
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00003570 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00003571 }
3572
3573 // A circular dependence.
3574 if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
3575 OrderBeforeUse = false;
3576
3577 // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
3578 // to a loop-carried dependence.
3579 if (OrderBeforeDef)
3580 OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
3581
3582 // The uncommon case when the instruction order needs to be updated because
3583 // there is both a use and def.
3584 if (OrderBeforeUse && OrderAfterDef) {
3585 SUnit *UseSU = Insts.at(MoveUse);
3586 SUnit *DefSU = Insts.at(MoveDef);
3587 if (MoveUse > MoveDef) {
3588 Insts.erase(Insts.begin() + MoveUse);
3589 Insts.erase(Insts.begin() + MoveDef);
3590 } else {
3591 Insts.erase(Insts.begin() + MoveDef);
3592 Insts.erase(Insts.begin() + MoveUse);
3593 }
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003594 orderDependence(SSD, UseSU, Insts);
3595 orderDependence(SSD, SU, Insts);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003596 orderDependence(SSD, DefSU, Insts);
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003597 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003598 }
3599 // Put the new instruction first if there is a use in the list. Otherwise,
3600 // put it at the end of the list.
3601 if (OrderBeforeUse)
3602 Insts.push_front(SU);
3603 else
3604 Insts.push_back(SU);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003605}
3606
3607/// Return true if the scheduled Phi has a loop carried operand.
3608bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
3609 if (!Phi.isPHI())
3610 return false;
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003611 assert(Phi.isPHI() && "Expecting a Phi.");
Brendon Cahoon254f8892016-07-29 16:44:44 +00003612 SUnit *DefSU = SSD->getSUnit(&Phi);
3613 unsigned DefCycle = cycleScheduled(DefSU);
3614 int DefStage = stageScheduled(DefSU);
3615
3616 unsigned InitVal = 0;
3617 unsigned LoopVal = 0;
3618 getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
3619 SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
3620 if (!UseSU)
3621 return true;
3622 if (UseSU->getInstr()->isPHI())
3623 return true;
3624 unsigned LoopCycle = cycleScheduled(UseSU);
3625 int LoopStage = stageScheduled(UseSU);
Simon Pilgrim3d8482a2016-11-14 10:40:23 +00003626 return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003627}
3628
3629/// Return true if the instruction is a definition that is loop carried
3630/// and defines the use on the next iteration.
3631/// v1 = phi(v2, v3)
3632/// (Def) v3 = op v1
3633/// (MO) = v1
3634/// If MO appears before Def, then then v1 and v3 may get assigned to the same
3635/// register.
3636bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
3637 MachineInstr *Def, MachineOperand &MO) {
3638 if (!MO.isReg())
3639 return false;
3640 if (Def->isPHI())
3641 return false;
3642 MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
3643 if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
3644 return false;
3645 if (!isLoopCarried(SSD, *Phi))
3646 return false;
3647 unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
3648 for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
3649 MachineOperand &DMO = Def->getOperand(i);
3650 if (!DMO.isReg() || !DMO.isDef())
3651 continue;
3652 if (DMO.getReg() == LoopReg)
3653 return true;
3654 }
3655 return false;
3656}
3657
3658// Check if the generated schedule is valid. This function checks if
3659// an instruction that uses a physical register is scheduled in a
3660// different stage than the definition. The pipeliner does not handle
3661// physical register values that may cross a basic block boundary.
3662bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00003663 for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
3664 SUnit &SU = SSD->SUnits[i];
3665 if (!SU.hasPhysRegDefs)
3666 continue;
3667 int StageDef = stageScheduled(&SU);
3668 assert(StageDef != -1 && "Instruction should have been scheduled.");
3669 for (auto &SI : SU.Succs)
3670 if (SI.isAssignedRegDep())
Simon Pilgrimb39236b2016-07-29 18:57:32 +00003671 if (ST.getRegisterInfo()->isPhysicalRegister(SI.getReg()))
Brendon Cahoon254f8892016-07-29 16:44:44 +00003672 if (stageScheduled(SI.getSUnit()) != StageDef)
3673 return false;
3674 }
3675 return true;
3676}
3677
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003678/// A property of the node order in swing-modulo-scheduling is
3679/// that for nodes outside circuits the following holds:
3680/// none of them is scheduled after both a successor and a
3681/// predecessor.
3682/// The method below checks whether the property is met.
3683/// If not, debug information is printed and statistics information updated.
3684/// Note that we do not use an assert statement.
3685/// The reason is that although an invalid node oder may prevent
3686/// the pipeliner from finding a pipelined schedule for arbitrary II,
3687/// it does not lead to the generation of incorrect code.
3688void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
3689
3690 // a sorted vector that maps each SUnit to its index in the NodeOrder
3691 typedef std::pair<SUnit *, unsigned> UnitIndex;
3692 std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
3693
3694 for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
3695 Indices.push_back(std::make_pair(NodeOrder[i], i));
3696
3697 auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
3698 return std::get<0>(i1) < std::get<0>(i2);
3699 };
3700
3701 // sort, so that we can perform a binary search
Fangrui Song0cac7262018-09-27 02:13:45 +00003702 llvm::sort(Indices, CompareKey);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003703
3704 bool Valid = true;
David L Kreitzerfebf70a2018-03-16 21:21:23 +00003705 (void)Valid;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003706 // for each SUnit in the NodeOrder, check whether
3707 // it appears after both a successor and a predecessor
3708 // of the SUnit. If this is the case, and the SUnit
3709 // is not part of circuit, then the NodeOrder is not
3710 // valid.
3711 for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
3712 SUnit *SU = NodeOrder[i];
3713 unsigned Index = i;
3714
3715 bool PredBefore = false;
3716 bool SuccBefore = false;
3717
3718 SUnit *Succ;
3719 SUnit *Pred;
David L Kreitzerfebf70a2018-03-16 21:21:23 +00003720 (void)Succ;
3721 (void)Pred;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003722
3723 for (SDep &PredEdge : SU->Preds) {
3724 SUnit *PredSU = PredEdge.getSUnit();
Fangrui Songdc8de602019-06-21 05:40:31 +00003725 unsigned PredIndex = std::get<1>(
3726 *llvm::lower_bound(Indices, std::make_pair(PredSU, 0), CompareKey));
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003727 if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
3728 PredBefore = true;
3729 Pred = PredSU;
3730 break;
3731 }
3732 }
3733
3734 for (SDep &SuccEdge : SU->Succs) {
3735 SUnit *SuccSU = SuccEdge.getSUnit();
Jinsong Ji1c884452019-06-13 21:51:12 +00003736 // Do not process a boundary node, it was not included in NodeOrder,
3737 // hence not in Indices either, call to std::lower_bound() below will
3738 // return Indices.end().
3739 if (SuccSU->isBoundaryNode())
3740 continue;
Fangrui Songdc8de602019-06-21 05:40:31 +00003741 unsigned SuccIndex = std::get<1>(
3742 *llvm::lower_bound(Indices, std::make_pair(SuccSU, 0), CompareKey));
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003743 if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
3744 SuccBefore = true;
3745 Succ = SuccSU;
3746 break;
3747 }
3748 }
3749
3750 if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
3751 // instructions in circuits are allowed to be scheduled
3752 // after both a successor and predecessor.
Fangrui Songdc8de602019-06-21 05:40:31 +00003753 bool InCircuit = llvm::any_of(
3754 Circuits, [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003755 if (InCircuit)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003756 LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003757 else {
3758 Valid = false;
3759 NumNodeOrderIssues++;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003760 LLVM_DEBUG(dbgs() << "Predecessor ";);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003761 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003762 LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
3763 << " are scheduled before node " << SU->NodeNum
3764 << "\n";);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003765 }
3766 }
3767
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003768 LLVM_DEBUG({
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00003769 if (!Valid)
3770 dbgs() << "Invalid node order found!\n";
3771 });
3772}
3773
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003774/// Attempt to fix the degenerate cases when the instruction serialization
3775/// causes the register lifetimes to overlap. For example,
3776/// p' = store_pi(p, b)
3777/// = load p, offset
3778/// In this case p and p' overlap, which means that two registers are needed.
3779/// Instead, this function changes the load to use p' and updates the offset.
3780void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
3781 unsigned OverlapReg = 0;
3782 unsigned NewBaseReg = 0;
3783 for (SUnit *SU : Instrs) {
3784 MachineInstr *MI = SU->getInstr();
3785 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3786 const MachineOperand &MO = MI->getOperand(i);
3787 // Look for an instruction that uses p. The instruction occurs in the
3788 // same cycle but occurs later in the serialized order.
3789 if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
3790 // Check that the instruction appears in the InstrChanges structure,
3791 // which contains instructions that can have the offset updated.
3792 DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3793 InstrChanges.find(SU);
3794 if (It != InstrChanges.end()) {
3795 unsigned BasePos, OffsetPos;
3796 // Update the base register and adjust the offset.
3797 if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
Krzysztof Parzyszek12bdcab2017-10-11 15:59:51 +00003798 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3799 NewMI->getOperand(BasePos).setReg(NewBaseReg);
3800 int64_t NewOffset =
3801 MI->getOperand(OffsetPos).getImm() - It->second.second;
3802 NewMI->getOperand(OffsetPos).setImm(NewOffset);
3803 SU->setInstr(NewMI);
3804 MISUnitMap[NewMI] = SU;
3805 NewMIs.insert(NewMI);
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003806 }
3807 }
3808 OverlapReg = 0;
3809 NewBaseReg = 0;
3810 break;
3811 }
3812 // Look for an instruction of the form p' = op(p), which uses and defines
3813 // two virtual registers that get allocated to the same physical register.
3814 unsigned TiedUseIdx = 0;
3815 if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
3816 // OverlapReg is p in the example above.
3817 OverlapReg = MI->getOperand(TiedUseIdx).getReg();
3818 // NewBaseReg is p' in the example above.
3819 NewBaseReg = MI->getOperand(i).getReg();
3820 break;
3821 }
3822 }
3823 }
3824}
3825
Brendon Cahoon254f8892016-07-29 16:44:44 +00003826/// After the schedule has been formed, call this function to combine
3827/// the instructions from the different stages/cycles. That is, this
3828/// function creates a schedule that represents a single iteration.
3829void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
3830 // Move all instructions to the first stage from later stages.
3831 for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3832 for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
3833 ++stage) {
3834 std::deque<SUnit *> &cycleInstrs =
3835 ScheduledInstrs[cycle + (stage * InitiationInterval)];
3836 for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
3837 E = cycleInstrs.rend();
3838 I != E; ++I)
3839 ScheduledInstrs[cycle].push_front(*I);
3840 }
3841 }
3842 // Iterate over the definitions in each instruction, and compute the
3843 // stage difference for each use. Keep the maximum value.
3844 for (auto &I : InstrToCycle) {
3845 int DefStage = stageScheduled(I.first);
3846 MachineInstr *MI = I.first->getInstr();
3847 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3848 MachineOperand &Op = MI->getOperand(i);
3849 if (!Op.isReg() || !Op.isDef())
3850 continue;
3851
3852 unsigned Reg = Op.getReg();
3853 unsigned MaxDiff = 0;
3854 bool PhiIsSwapped = false;
3855 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(Reg),
3856 EI = MRI.use_end();
3857 UI != EI; ++UI) {
3858 MachineOperand &UseOp = *UI;
3859 MachineInstr *UseMI = UseOp.getParent();
3860 SUnit *SUnitUse = SSD->getSUnit(UseMI);
3861 int UseStage = stageScheduled(SUnitUse);
3862 unsigned Diff = 0;
3863 if (UseStage != -1 && UseStage >= DefStage)
3864 Diff = UseStage - DefStage;
3865 if (MI->isPHI()) {
3866 if (isLoopCarried(SSD, *MI))
3867 ++Diff;
3868 else
3869 PhiIsSwapped = true;
3870 }
3871 MaxDiff = std::max(Diff, MaxDiff);
3872 }
3873 RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
3874 }
3875 }
3876
3877 // Erase all the elements in the later stages. Only one iteration should
3878 // remain in the scheduled list, and it contains all the instructions.
3879 for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
3880 ScheduledInstrs.erase(cycle);
3881
3882 // Change the registers in instruction as specified in the InstrChanges
3883 // map. We need to use the new registers to create the correct order.
3884 for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
3885 SUnit *SU = &SSD->SUnits[i];
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003886 SSD->applyInstrChange(SU->getInstr(), *this);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003887 }
3888
3889 // Reorder the instructions in each cycle to fix and improve the
3890 // generated code.
3891 for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
3892 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003893 std::deque<SUnit *> newOrderPhi;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003894 for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
3895 SUnit *SU = cycleInstrs[i];
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003896 if (SU->getInstr()->isPHI())
3897 newOrderPhi.push_back(SU);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003898 }
3899 std::deque<SUnit *> newOrderI;
Brendon Cahoon254f8892016-07-29 16:44:44 +00003900 for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
3901 SUnit *SU = cycleInstrs[i];
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003902 if (!SU->getInstr()->isPHI())
Brendon Cahoon254f8892016-07-29 16:44:44 +00003903 orderDependence(SSD, SU, newOrderI);
3904 }
3905 // Replace the old order with the new order.
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00003906 cycleInstrs.swap(newOrderPhi);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003907 cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00003908 SSD->fixupRegisterOverlaps(cycleInstrs);
Brendon Cahoon254f8892016-07-29 16:44:44 +00003909 }
3910
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003911 LLVM_DEBUG(dump(););
Brendon Cahoon254f8892016-07-29 16:44:44 +00003912}
3913
Adrian Prantlfa2e3582019-01-14 17:24:11 +00003914void NodeSet::print(raw_ostream &os) const {
3915 os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
3916 << " depth " << MaxDepth << " col " << Colocate << "\n";
3917 for (const auto &I : Nodes)
3918 os << " SU(" << I->NodeNum << ") " << *(I->getInstr());
3919 os << "\n";
3920}
3921
Aaron Ballman615eb472017-10-15 14:32:27 +00003922#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Brendon Cahoon254f8892016-07-29 16:44:44 +00003923/// Print the schedule information to the given output.
3924void SMSchedule::print(raw_ostream &os) const {
3925 // Iterate over each cycle.
3926 for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3927 // Iterate over each instruction in the cycle.
3928 const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
3929 for (SUnit *CI : cycleInstrs->second) {
3930 os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
3931 os << "(" << CI->NodeNum << ") ";
3932 CI->getInstr()->print(os);
3933 os << "\n";
3934 }
3935 }
3936}
3937
3938/// Utility function used for debugging to print the schedule.
Matthias Braun8c209aa2017-01-28 02:02:38 +00003939LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
Adrian Prantlfa2e3582019-01-14 17:24:11 +00003940LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
3941
Matthias Braun8c209aa2017-01-28 02:02:38 +00003942#endif
Adrian Prantlfa2e3582019-01-14 17:24:11 +00003943
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003944void ResourceManager::initProcResourceVectors(
3945 const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
3946 unsigned ProcResourceID = 0;
Adrian Prantlfa2e3582019-01-14 17:24:11 +00003947
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003948 // We currently limit the resource kinds to 64 and below so that we can use
3949 // uint64_t for Masks
3950 assert(SM.getNumProcResourceKinds() < 64 &&
3951 "Too many kinds of resources, unsupported");
3952 // Create a unique bitmask for every processor resource unit.
3953 // Skip resource at index 0, since it always references 'InvalidUnit'.
3954 Masks.resize(SM.getNumProcResourceKinds());
3955 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3956 const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3957 if (Desc.SubUnitsIdxBegin)
3958 continue;
3959 Masks[I] = 1ULL << ProcResourceID;
3960 ProcResourceID++;
3961 }
3962 // Create a unique bitmask for every processor resource group.
3963 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3964 const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3965 if (!Desc.SubUnitsIdxBegin)
3966 continue;
3967 Masks[I] = 1ULL << ProcResourceID;
3968 for (unsigned U = 0; U < Desc.NumUnits; ++U)
3969 Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
3970 ProcResourceID++;
3971 }
3972 LLVM_DEBUG({
Jinsong Jiba438402019-06-18 20:24:49 +00003973 if (SwpShowResMask) {
3974 dbgs() << "ProcResourceDesc:\n";
3975 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3976 const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
3977 dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
3978 ProcResource->Name, I, Masks[I],
3979 ProcResource->NumUnits);
3980 }
3981 dbgs() << " -----------------\n";
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003982 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003983 });
3984}
3985
3986bool ResourceManager::canReserveResources(const MCInstrDesc *MID) const {
3987
Jinsong Jiba438402019-06-18 20:24:49 +00003988 LLVM_DEBUG({
3989 if (SwpDebugResource)
3990 dbgs() << "canReserveResources:\n";
3991 });
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00003992 if (UseDFA)
3993 return DFAResources->canReserveResources(MID);
3994
3995 unsigned InsnClass = MID->getSchedClass();
3996 const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
3997 if (!SCDesc->isValid()) {
3998 LLVM_DEBUG({
3999 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
4000 dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
4001 });
4002 return true;
4003 }
4004
4005 const MCWriteProcResEntry *I = STI->getWriteProcResBegin(SCDesc);
4006 const MCWriteProcResEntry *E = STI->getWriteProcResEnd(SCDesc);
4007 for (; I != E; ++I) {
4008 if (!I->Cycles)
4009 continue;
4010 const MCProcResourceDesc *ProcResource =
4011 SM.getProcResource(I->ProcResourceIdx);
4012 unsigned NumUnits = ProcResource->NumUnits;
4013 LLVM_DEBUG({
Jinsong Jiba438402019-06-18 20:24:49 +00004014 if (SwpDebugResource)
4015 dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
4016 ProcResource->Name, I->ProcResourceIdx,
4017 ProcResourceCount[I->ProcResourceIdx], NumUnits,
4018 I->Cycles);
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00004019 });
4020 if (ProcResourceCount[I->ProcResourceIdx] >= NumUnits)
4021 return false;
4022 }
Jinsong Jiba438402019-06-18 20:24:49 +00004023 LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return true\n\n";);
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00004024 return true;
4025}
4026
4027void ResourceManager::reserveResources(const MCInstrDesc *MID) {
Jinsong Jiba438402019-06-18 20:24:49 +00004028 LLVM_DEBUG({
4029 if (SwpDebugResource)
4030 dbgs() << "reserveResources:\n";
4031 });
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00004032 if (UseDFA)
4033 return DFAResources->reserveResources(MID);
4034
4035 unsigned InsnClass = MID->getSchedClass();
4036 const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
4037 if (!SCDesc->isValid()) {
4038 LLVM_DEBUG({
4039 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
4040 dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
4041 });
4042 return;
4043 }
4044 for (const MCWriteProcResEntry &PRE :
4045 make_range(STI->getWriteProcResBegin(SCDesc),
4046 STI->getWriteProcResEnd(SCDesc))) {
4047 if (!PRE.Cycles)
4048 continue;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00004049 ++ProcResourceCount[PRE.ProcResourceIdx];
4050 LLVM_DEBUG({
Jinsong Jiba438402019-06-18 20:24:49 +00004051 if (SwpDebugResource) {
4052 const MCProcResourceDesc *ProcResource =
4053 SM.getProcResource(PRE.ProcResourceIdx);
4054 dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
4055 ProcResource->Name, PRE.ProcResourceIdx,
4056 ProcResourceCount[PRE.ProcResourceIdx],
4057 ProcResource->NumUnits, PRE.Cycles);
4058 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00004059 });
4060 }
Jinsong Jiba438402019-06-18 20:24:49 +00004061 LLVM_DEBUG({
4062 if (SwpDebugResource)
4063 dbgs() << "reserveResources: done!\n\n";
4064 });
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00004065}
4066
4067bool ResourceManager::canReserveResources(const MachineInstr &MI) const {
4068 return canReserveResources(&MI.getDesc());
4069}
4070
4071void ResourceManager::reserveResources(const MachineInstr &MI) {
4072 return reserveResources(&MI.getDesc());
4073}
4074
4075void ResourceManager::clearResources() {
4076 if (UseDFA)
4077 return DFAResources->clearResources();
4078 std::fill(ProcResourceCount.begin(), ProcResourceCount.end(), 0);
4079}
Adrian Prantlfa2e3582019-01-14 17:24:11 +00004080