blob: ff3d2feab5e1d3e1b9b378f6e2f37f1cfb030af3 [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"
James Molloy790a7792019-08-30 18:49:50 +000059#include "llvm/CodeGen/ModuloSchedule.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000060#include "llvm/CodeGen/RegisterPressure.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000061#include "llvm/CodeGen/ScheduleDAG.h"
Krzysztof Parzyszek88391242016-12-22 19:21:20 +000062#include "llvm/CodeGen/ScheduleDAGMutation.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000063#include "llvm/CodeGen/TargetOpcodes.h"
64#include "llvm/CodeGen/TargetRegisterInfo.h"
65#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000066#include "llvm/Config/llvm-config.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000067#include "llvm/IR/Attributes.h"
68#include "llvm/IR/DebugLoc.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000069#include "llvm/IR/Function.h"
70#include "llvm/MC/LaneBitmask.h"
71#include "llvm/MC/MCInstrDesc.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000072#include "llvm/MC/MCInstrItineraries.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000073#include "llvm/MC/MCRegisterInfo.h"
74#include "llvm/Pass.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000075#include "llvm/Support/CommandLine.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000076#include "llvm/Support/Compiler.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000077#include "llvm/Support/Debug.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000078#include "llvm/Support/MathExtras.h"
Brendon Cahoon254f8892016-07-29 16:44:44 +000079#include "llvm/Support/raw_ostream.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000080#include <algorithm>
81#include <cassert>
Brendon Cahoon254f8892016-07-29 16:44:44 +000082#include <climits>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000083#include <cstdint>
Brendon Cahoon254f8892016-07-29 16:44:44 +000084#include <deque>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000085#include <functional>
86#include <iterator>
Brendon Cahoon254f8892016-07-29 16:44:44 +000087#include <map>
Eugene Zelenko32a40562017-09-11 23:00:48 +000088#include <memory>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000089#include <tuple>
90#include <utility>
91#include <vector>
Brendon Cahoon254f8892016-07-29 16:44:44 +000092
93using namespace llvm;
94
95#define DEBUG_TYPE "pipeliner"
96
97STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
98STATISTIC(NumPipelined, "Number of loops software pipelined");
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +000099STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000100STATISTIC(NumFailBranch, "Pipeliner abort due to unknown branch");
101STATISTIC(NumFailLoop, "Pipeliner abort due to unsupported loop");
102STATISTIC(NumFailPreheader, "Pipeliner abort due to missing preheader");
103STATISTIC(NumFailLargeMaxMII, "Pipeliner abort due to MaxMII too large");
104STATISTIC(NumFailZeroMII, "Pipeliner abort due to zero MII");
105STATISTIC(NumFailNoSchedule, "Pipeliner abort due to no schedule found");
106STATISTIC(NumFailZeroStage, "Pipeliner abort due to zero stage");
107STATISTIC(NumFailLargeMaxStage, "Pipeliner abort due to too many stages");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000108
109/// A command line option to turn software pipelining on or off.
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000110static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
111 cl::ZeroOrMore,
112 cl::desc("Enable Software Pipelining"));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000113
114/// A command line option to enable SWP at -Os.
115static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
116 cl::desc("Enable SWP at Os."), cl::Hidden,
117 cl::init(false));
118
119/// A command line argument to limit minimum initial interval for pipelining.
120static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
Hiroshi Inoue8f976ba2018-01-17 12:29:38 +0000121 cl::desc("Size limit for the MII."),
Brendon Cahoon254f8892016-07-29 16:44:44 +0000122 cl::Hidden, cl::init(27));
123
124/// A command line argument to limit the number of stages in the pipeline.
125static cl::opt<int>
126 SwpMaxStages("pipeliner-max-stages",
127 cl::desc("Maximum stages allowed in the generated scheduled."),
128 cl::Hidden, cl::init(3));
129
130/// A command line option to disable the pruning of chain dependences due to
131/// an unrelated Phi.
132static cl::opt<bool>
133 SwpPruneDeps("pipeliner-prune-deps",
134 cl::desc("Prune dependences between unrelated Phi nodes."),
135 cl::Hidden, cl::init(true));
136
137/// A command line option to disable the pruning of loop carried order
138/// dependences.
139static cl::opt<bool>
140 SwpPruneLoopCarried("pipeliner-prune-loop-carried",
141 cl::desc("Prune loop carried order dependences."),
142 cl::Hidden, cl::init(true));
143
144#ifndef NDEBUG
145static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
146#endif
147
148static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
149 cl::ReallyHidden, cl::init(false),
150 cl::ZeroOrMore, cl::desc("Ignore RecMII"));
151
Jinsong Jiba438402019-06-18 20:24:49 +0000152static cl::opt<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden,
153 cl::init(false));
154static cl::opt<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden,
155 cl::init(false));
156
James Molloy93549952019-09-03 08:20:31 +0000157static cl::opt<bool> EmitTestAnnotations(
158 "pipeliner-annotate-for-testing", cl::Hidden, cl::init(false),
159 cl::desc("Instead of emitting the pipelined code, annotate instructions "
160 "with the generated schedule for feeding into the "
161 "-modulo-schedule-test pass"));
162
Adrian Prantlfa2e3582019-01-14 17:24:11 +0000163namespace llvm {
164
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +0000165// A command line option to enable the CopyToPhi DAG mutation.
Adrian Prantlfa2e3582019-01-14 17:24:11 +0000166cl::opt<bool>
Aleksandr Urakov00d4c382018-10-23 14:27:45 +0000167 SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
168 cl::init(true), cl::ZeroOrMore,
169 cl::desc("Enable CopyToPhi DAG Mutation"));
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +0000170
Adrian Prantlfa2e3582019-01-14 17:24:11 +0000171} // end namespace llvm
Brendon Cahoon254f8892016-07-29 16:44:44 +0000172
173unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
174char MachinePipeliner::ID = 0;
175#ifndef NDEBUG
176int MachinePipeliner::NumTries = 0;
177#endif
178char &llvm::MachinePipelinerID = MachinePipeliner::ID;
Eugene Zelenko32a40562017-09-11 23:00:48 +0000179
Matthias Braun1527baa2017-05-25 21:26:32 +0000180INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
Brendon Cahoon254f8892016-07-29 16:44:44 +0000181 "Modulo Software Pipelining", false, false)
182INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
183INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
184INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
185INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Matthias Braun1527baa2017-05-25 21:26:32 +0000186INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
Brendon Cahoon254f8892016-07-29 16:44:44 +0000187 "Modulo Software Pipelining", false, false)
188
189/// The "main" function for implementing Swing Modulo Scheduling.
190bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000191 if (skipFunction(mf.getFunction()))
Brendon Cahoon254f8892016-07-29 16:44:44 +0000192 return false;
193
194 if (!EnableSWP)
195 return false;
196
Matthias Braunf1caa282017-12-15 22:22:58 +0000197 if (mf.getFunction().getAttributes().hasAttribute(
Reid Klecknerb5180542017-03-21 16:57:19 +0000198 AttributeList::FunctionIndex, Attribute::OptimizeForSize) &&
Brendon Cahoon254f8892016-07-29 16:44:44 +0000199 !EnableSWPOptSize.getPosition())
200 return false;
201
Jinsong Jief2d6d92019-06-11 17:40:39 +0000202 if (!mf.getSubtarget().enableMachinePipeliner())
203 return false;
204
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000205 // Cannot pipeline loops without instruction itineraries if we are using
206 // DFA for the pipeliner.
207 if (mf.getSubtarget().useDFAforSMS() &&
208 (!mf.getSubtarget().getInstrItineraryData() ||
209 mf.getSubtarget().getInstrItineraryData()->isEmpty()))
210 return false;
211
Brendon Cahoon254f8892016-07-29 16:44:44 +0000212 MF = &mf;
213 MLI = &getAnalysis<MachineLoopInfo>();
214 MDT = &getAnalysis<MachineDominatorTree>();
215 TII = MF->getSubtarget().getInstrInfo();
216 RegClassInfo.runOnMachineFunction(*MF);
217
218 for (auto &L : *MLI)
219 scheduleLoop(*L);
220
221 return false;
222}
223
224/// Attempt to perform the SMS algorithm on the specified loop. This function is
225/// the main entry point for the algorithm. The function identifies candidate
226/// loops, calculates the minimum initiation interval, and attempts to schedule
227/// the loop.
228bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
229 bool Changed = false;
230 for (auto &InnerLoop : L)
231 Changed |= scheduleLoop(*InnerLoop);
232
233#ifndef NDEBUG
234 // Stop trying after reaching the limit (if any).
235 int Limit = SwpLoopLimit;
236 if (Limit >= 0) {
237 if (NumTries >= SwpLoopLimit)
238 return Changed;
239 NumTries++;
240 }
241#endif
242
Brendon Cahoon59d99732019-01-23 03:26:10 +0000243 setPragmaPipelineOptions(L);
244 if (!canPipelineLoop(L)) {
245 LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000246 return Changed;
Brendon Cahoon59d99732019-01-23 03:26:10 +0000247 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000248
249 ++NumTrytoPipeline;
250
251 Changed = swingModuloScheduler(L);
252
253 return Changed;
254}
255
Brendon Cahoon59d99732019-01-23 03:26:10 +0000256void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) {
257 MachineBasicBlock *LBLK = L.getTopBlock();
258
259 if (LBLK == nullptr)
260 return;
261
262 const BasicBlock *BBLK = LBLK->getBasicBlock();
263 if (BBLK == nullptr)
264 return;
265
266 const Instruction *TI = BBLK->getTerminator();
267 if (TI == nullptr)
268 return;
269
270 MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop);
271 if (LoopID == nullptr)
272 return;
273
274 assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
275 assert(LoopID->getOperand(0) == LoopID && "invalid loop");
276
277 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
278 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
279
280 if (MD == nullptr)
281 continue;
282
283 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
284
285 if (S == nullptr)
286 continue;
287
288 if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
289 assert(MD->getNumOperands() == 2 &&
290 "Pipeline initiation interval hint metadata should have two operands.");
291 II_setByPragma =
292 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
293 assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
294 } else if (S->getString() == "llvm.loop.pipeline.disable") {
295 disabledByPragma = true;
296 }
297 }
298}
299
Brendon Cahoon254f8892016-07-29 16:44:44 +0000300/// Return true if the loop can be software pipelined. The algorithm is
301/// restricted to loops with a single basic block. Make sure that the
302/// branch in the loop can be analyzed.
303bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
304 if (L.getNumBlocks() != 1)
305 return false;
306
Brendon Cahoon59d99732019-01-23 03:26:10 +0000307 if (disabledByPragma)
308 return false;
309
Brendon Cahoon254f8892016-07-29 16:44:44 +0000310 // Check if the branch can't be understood because we can't do pipelining
311 // if that's the case.
312 LI.TBB = nullptr;
313 LI.FBB = nullptr;
314 LI.BrCond.clear();
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000315 if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) {
316 LLVM_DEBUG(
317 dbgs() << "Unable to analyzeBranch, can NOT pipeline current Loop\n");
318 NumFailBranch++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000319 return false;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000320 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000321
322 LI.LoopInductionVar = nullptr;
323 LI.LoopCompare = nullptr;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000324 if (TII->analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare)) {
325 LLVM_DEBUG(
326 dbgs() << "Unable to analyzeLoop, can NOT pipeline current Loop\n");
327 NumFailLoop++;
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
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000331 if (!L.getLoopPreheader()) {
332 LLVM_DEBUG(
333 dbgs() << "Preheader not found, can NOT pipeline current Loop\n");
334 NumFailPreheader++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000335 return false;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000336 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000337
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000338 // Remove any subregisters from inputs to phi nodes.
339 preprocessPhiNodes(*L.getHeader());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000340 return true;
341}
342
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000343void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
344 MachineRegisterInfo &MRI = MF->getRegInfo();
345 SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
346
347 for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) {
348 MachineOperand &DefOp = PI.getOperand(0);
349 assert(DefOp.getSubReg() == 0);
350 auto *RC = MRI.getRegClass(DefOp.getReg());
351
352 for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
353 MachineOperand &RegOp = PI.getOperand(i);
354 if (RegOp.getSubReg() == 0)
355 continue;
356
357 // If the operand uses a subregister, replace it with a new register
358 // without subregisters, and generate a copy to the new register.
Daniel Sanders0c476112019-08-15 19:22:08 +0000359 Register NewReg = MRI.createVirtualRegister(RC);
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000360 MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
361 MachineBasicBlock::iterator At = PredB.getFirstTerminator();
362 const DebugLoc &DL = PredB.findDebugLoc(At);
363 auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
364 .addReg(RegOp.getReg(), getRegState(RegOp),
365 RegOp.getSubReg());
366 Slots.insertMachineInstrInMaps(*Copy);
367 RegOp.setReg(NewReg);
368 RegOp.setSubReg(0);
369 }
370 }
371}
372
Brendon Cahoon254f8892016-07-29 16:44:44 +0000373/// The SMS algorithm consists of the following main steps:
374/// 1. Computation and analysis of the dependence graph.
375/// 2. Ordering of the nodes (instructions).
376/// 3. Attempt to Schedule the loop.
377bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
378 assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
379
Brendon Cahoon59d99732019-01-23 03:26:10 +0000380 SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo,
381 II_setByPragma);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000382
383 MachineBasicBlock *MBB = L.getHeader();
384 // The kernel should not include any terminator instructions. These
385 // will be added back later.
386 SMS.startBlock(MBB);
387
388 // Compute the number of 'real' instructions in the basic block by
389 // ignoring terminators.
390 unsigned size = MBB->size();
391 for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
392 E = MBB->instr_end();
393 I != E; ++I, --size)
394 ;
395
396 SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
397 SMS.schedule();
398 SMS.exitRegion();
399
400 SMS.finishBlock();
401 return SMS.hasNewSchedule();
402}
403
Brendon Cahoon59d99732019-01-23 03:26:10 +0000404void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
405 if (II_setByPragma > 0)
406 MII = II_setByPragma;
407 else
408 MII = std::max(ResMII, RecMII);
409}
410
411void SwingSchedulerDAG::setMAX_II() {
412 if (II_setByPragma > 0)
413 MAX_II = II_setByPragma;
414 else
415 MAX_II = MII + 10;
416}
417
Brendon Cahoon254f8892016-07-29 16:44:44 +0000418/// We override the schedule function in ScheduleDAGInstrs to implement the
419/// scheduling part of the Swing Modulo Scheduling algorithm.
420void SwingSchedulerDAG::schedule() {
421 AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
422 buildSchedGraph(AA);
423 addLoopCarriedDependences(AA);
424 updatePhiDependences();
425 Topo.InitDAGTopologicalSorting();
426 changeDependences();
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +0000427 postprocessDAG();
Matthias Braun726e12c2018-09-19 00:23:35 +0000428 LLVM_DEBUG(dump());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000429
430 NodeSetType NodeSets;
431 findCircuits(NodeSets);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +0000432 NodeSetType Circuits = NodeSets;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000433
434 // Calculate the MII.
435 unsigned ResMII = calculateResMII();
436 unsigned RecMII = calculateRecMII(NodeSets);
437
438 fuseRecs(NodeSets);
439
440 // This flag is used for testing and can cause correctness problems.
441 if (SwpIgnoreRecMII)
442 RecMII = 0;
443
Brendon Cahoon59d99732019-01-23 03:26:10 +0000444 setMII(ResMII, RecMII);
445 setMAX_II();
446
447 LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
448 << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000449
450 // Can't schedule a loop without a valid MII.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000451 if (MII == 0) {
452 LLVM_DEBUG(
453 dbgs()
454 << "0 is not a valid Minimal Initiation Interval, can NOT schedule\n");
455 NumFailZeroMII++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000456 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000457 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000458
459 // Don't pipeline large loops.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000460 if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) {
461 LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
462 << ", we don't pipleline large loops\n");
463 NumFailLargeMaxMII++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000464 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000465 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000466
467 computeNodeFunctions(NodeSets);
468
469 registerPressureFilter(NodeSets);
470
471 colocateNodeSets(NodeSets);
472
473 checkNodeSets(NodeSets);
474
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000475 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +0000476 for (auto &I : NodeSets) {
477 dbgs() << " Rec NodeSet ";
478 I.dump();
479 }
480 });
481
Fangrui Songefd94c52019-04-23 14:51:27 +0000482 llvm::stable_sort(NodeSets, std::greater<NodeSet>());
Brendon Cahoon254f8892016-07-29 16:44:44 +0000483
484 groupRemainingNodes(NodeSets);
485
486 removeDuplicateNodes(NodeSets);
487
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000488 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +0000489 for (auto &I : NodeSets) {
490 dbgs() << " NodeSet ";
491 I.dump();
492 }
493 });
494
495 computeNodeOrder(NodeSets);
496
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +0000497 // check for node order issues
498 checkValidNodeOrder(Circuits);
499
Brendon Cahoon254f8892016-07-29 16:44:44 +0000500 SMSchedule Schedule(Pass.MF);
501 Scheduled = schedulePipeline(Schedule);
502
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000503 if (!Scheduled){
504 LLVM_DEBUG(dbgs() << "No schedule found, return\n");
505 NumFailNoSchedule++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000506 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000507 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000508
509 unsigned numStages = Schedule.getMaxStageCount();
510 // No need to generate pipeline if there are no overlapped iterations.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000511 if (numStages == 0) {
512 LLVM_DEBUG(
513 dbgs() << "No overlapped iterations, no need to generate pipeline\n");
514 NumFailZeroStage++;
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 // Check that the maximum stage count is less than user-defined limit.
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000518 if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) {
519 LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages
520 << " : too many stages, abort\n");
521 NumFailLargeMaxStage++;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000522 return;
Jinsong Ji18e7bf52019-05-31 15:35:19 +0000523 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000524
James Molloy790a7792019-08-30 18:49:50 +0000525 // Generate the schedule as a ModuloSchedule.
526 DenseMap<MachineInstr *, int> Cycles, Stages;
527 std::vector<MachineInstr *> OrderedInsts;
528 for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
529 ++Cycle) {
530 for (SUnit *SU : Schedule.getInstructions(Cycle)) {
531 OrderedInsts.push_back(SU->getInstr());
532 Cycles[SU->getInstr()] = Cycle;
533 Stages[SU->getInstr()] = Schedule.stageScheduled(SU);
534 }
535 }
536 DenseMap<MachineInstr *, std::pair<unsigned, int64_t>> NewInstrChanges;
537 for (auto &KV : NewMIs) {
538 Cycles[KV.first] = Cycles[KV.second];
539 Stages[KV.first] = Stages[KV.second];
540 NewInstrChanges[KV.first] = InstrChanges[getSUnit(KV.first)];
541 }
542
543 ModuloSchedule MS(MF, &Loop, std::move(OrderedInsts), std::move(Cycles),
544 std::move(Stages));
James Molloy93549952019-09-03 08:20:31 +0000545 if (EmitTestAnnotations) {
546 assert(NewInstrChanges.empty() &&
547 "Cannot serialize a schedule with InstrChanges!");
548 ModuloScheduleTestAnnotater MSTI(MF, MS);
549 MSTI.annotate();
550 return;
551 }
James Molloy790a7792019-08-30 18:49:50 +0000552 ModuloScheduleExpander MSE(MF, MS, LIS, std::move(NewInstrChanges));
553 MSE.expand();
Brendon Cahoon254f8892016-07-29 16:44:44 +0000554 ++NumPipelined;
555}
556
557/// Clean up after the software pipeliner runs.
558void SwingSchedulerDAG::finishBlock() {
James Molloy790a7792019-08-30 18:49:50 +0000559 for (auto &KV : NewMIs)
560 MF.DeleteMachineInstr(KV.second);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000561 NewMIs.clear();
562
563 // Call the superclass.
564 ScheduleDAGInstrs::finishBlock();
565}
566
567/// Return the register values for the operands of a Phi instruction.
568/// This function assume the instruction is a Phi.
569static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
570 unsigned &InitVal, unsigned &LoopVal) {
571 assert(Phi.isPHI() && "Expecting a Phi.");
572
573 InitVal = 0;
574 LoopVal = 0;
575 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
576 if (Phi.getOperand(i + 1).getMBB() != Loop)
577 InitVal = Phi.getOperand(i).getReg();
Simon Pilgrimfbfb19b2017-03-16 19:52:00 +0000578 else
Brendon Cahoon254f8892016-07-29 16:44:44 +0000579 LoopVal = Phi.getOperand(i).getReg();
580
581 assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
582}
583
Hiroshi Inoue8f976ba2018-01-17 12:29:38 +0000584/// Return the Phi register value that comes the loop block.
Brendon Cahoon254f8892016-07-29 16:44:44 +0000585static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
586 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
587 if (Phi.getOperand(i + 1).getMBB() == LoopBB)
588 return Phi.getOperand(i).getReg();
589 return 0;
590}
591
592/// Return true if SUb can be reached from SUa following the chain edges.
593static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
594 SmallPtrSet<SUnit *, 8> Visited;
595 SmallVector<SUnit *, 8> Worklist;
596 Worklist.push_back(SUa);
597 while (!Worklist.empty()) {
598 const SUnit *SU = Worklist.pop_back_val();
599 for (auto &SI : SU->Succs) {
600 SUnit *SuccSU = SI.getSUnit();
601 if (SI.getKind() == SDep::Order) {
602 if (Visited.count(SuccSU))
603 continue;
604 if (SuccSU == SUb)
605 return true;
606 Worklist.push_back(SuccSU);
607 Visited.insert(SuccSU);
608 }
609 }
610 }
611 return false;
612}
613
614/// Return true if the instruction causes a chain between memory
615/// references before and after it.
616static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
Ulrich Weigand6c5d5ce2019-06-05 22:33:10 +0000617 return MI.isCall() || MI.mayRaiseFPException() ||
618 MI.hasUnmodeledSideEffects() ||
Brendon Cahoon254f8892016-07-29 16:44:44 +0000619 (MI.hasOrderedMemoryRef() &&
Justin Lebard98cf002016-09-10 01:03:20 +0000620 (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000621}
622
623/// Return the underlying objects for the memory references of an instruction.
624/// This function calls the code in ValueTracking, but first checks that the
625/// instruction has a memory operand.
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000626static void getUnderlyingObjects(const MachineInstr *MI,
627 SmallVectorImpl<const Value *> &Objs,
Brendon Cahoon254f8892016-07-29 16:44:44 +0000628 const DataLayout &DL) {
629 if (!MI->hasOneMemOperand())
630 return;
631 MachineMemOperand *MM = *MI->memoperands_begin();
632 if (!MM->getValue())
633 return;
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000634 GetUnderlyingObjects(MM->getValue(), Objs, DL);
635 for (const Value *V : Objs) {
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000636 if (!isIdentifiedObject(V)) {
637 Objs.clear();
638 return;
639 }
640 Objs.push_back(V);
641 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000642}
643
644/// Add a chain edge between a load and store if the store can be an
645/// alias of the load on a subsequent iteration, i.e., a loop carried
646/// dependence. This code is very similar to the code in ScheduleDAGInstrs
647/// but that code doesn't create loop carried dependences.
648void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000649 MapVector<const Value *, SmallVector<SUnit *, 4>> PendingLoads;
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000650 Value *UnknownValue =
651 UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
Brendon Cahoon254f8892016-07-29 16:44:44 +0000652 for (auto &SU : SUnits) {
653 MachineInstr &MI = *SU.getInstr();
654 if (isDependenceBarrier(MI, AA))
655 PendingLoads.clear();
656 else if (MI.mayLoad()) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000657 SmallVector<const Value *, 4> Objs;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000658 getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000659 if (Objs.empty())
660 Objs.push_back(UnknownValue);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000661 for (auto V : Objs) {
662 SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
663 SUs.push_back(&SU);
664 }
665 } else if (MI.mayStore()) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000666 SmallVector<const Value *, 4> Objs;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000667 getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000668 if (Objs.empty())
669 Objs.push_back(UnknownValue);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000670 for (auto V : Objs) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000671 MapVector<const Value *, SmallVector<SUnit *, 4>>::iterator I =
Brendon Cahoon254f8892016-07-29 16:44:44 +0000672 PendingLoads.find(V);
673 if (I == PendingLoads.end())
674 continue;
675 for (auto Load : I->second) {
676 if (isSuccOrder(Load, &SU))
677 continue;
678 MachineInstr &LdMI = *Load->getInstr();
679 // First, perform the cheaper check that compares the base register.
680 // If they are the same and the load offset is less than the store
681 // offset, then mark the dependence as loop carried potentially.
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +0000682 const MachineOperand *BaseOp1, *BaseOp2;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000683 int64_t Offset1, Offset2;
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +0000684 if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1, TRI) &&
685 TII->getMemOperandWithOffset(MI, BaseOp2, Offset2, TRI)) {
686 if (BaseOp1->isIdenticalTo(*BaseOp2) &&
687 (int)Offset1 < (int)Offset2) {
Krzysztof Parzyszek9f041b12018-03-26 16:50:11 +0000688 assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI, AA) &&
689 "What happened to the chain edge?");
690 SDep Dep(Load, SDep::Barrier);
691 Dep.setLatency(1);
692 SU.addPred(Dep);
693 continue;
694 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000695 }
696 // Second, the more expensive check that uses alias analysis on the
697 // base registers. If they alias, and the load offset is less than
698 // the store offset, the mark the dependence as loop carried.
699 if (!AA) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000700 SDep Dep(Load, SDep::Barrier);
701 Dep.setLatency(1);
702 SU.addPred(Dep);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000703 continue;
704 }
705 MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
706 MachineMemOperand *MMO2 = *MI.memoperands_begin();
707 if (!MMO1->getValue() || !MMO2->getValue()) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000708 SDep Dep(Load, SDep::Barrier);
709 Dep.setLatency(1);
710 SU.addPred(Dep);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000711 continue;
712 }
713 if (MMO1->getValue() == MMO2->getValue() &&
714 MMO1->getOffset() <= MMO2->getOffset()) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000715 SDep Dep(Load, SDep::Barrier);
716 Dep.setLatency(1);
717 SU.addPred(Dep);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000718 continue;
719 }
720 AliasResult AAResult = AA->alias(
George Burgess IV6ef80022018-10-10 21:28:44 +0000721 MemoryLocation(MMO1->getValue(), LocationSize::unknown(),
Brendon Cahoon254f8892016-07-29 16:44:44 +0000722 MMO1->getAAInfo()),
George Burgess IV6ef80022018-10-10 21:28:44 +0000723 MemoryLocation(MMO2->getValue(), LocationSize::unknown(),
Brendon Cahoon254f8892016-07-29 16:44:44 +0000724 MMO2->getAAInfo()));
725
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000726 if (AAResult != NoAlias) {
727 SDep Dep(Load, SDep::Barrier);
728 Dep.setLatency(1);
729 SU.addPred(Dep);
730 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000731 }
732 }
733 }
734 }
735}
736
737/// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
738/// processes dependences for PHIs. This function adds true dependences
739/// from a PHI to a use, and a loop carried dependence from the use to the
740/// PHI. The loop carried dependence is represented as an anti dependence
741/// edge. This function also removes chain dependences between unrelated
742/// PHIs.
743void SwingSchedulerDAG::updatePhiDependences() {
744 SmallVector<SDep, 4> RemoveDeps;
745 const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
746
747 // Iterate over each DAG node.
748 for (SUnit &I : SUnits) {
749 RemoveDeps.clear();
750 // Set to true if the instruction has an operand defined by a Phi.
751 unsigned HasPhiUse = 0;
752 unsigned HasPhiDef = 0;
753 MachineInstr *MI = I.getInstr();
754 // Iterate over each operand, and we process the definitions.
755 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
756 MOE = MI->operands_end();
757 MOI != MOE; ++MOI) {
758 if (!MOI->isReg())
759 continue;
Daniel Sanders0c476112019-08-15 19:22:08 +0000760 Register Reg = MOI->getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +0000761 if (MOI->isDef()) {
762 // If the register is used by a Phi, then create an anti dependence.
763 for (MachineRegisterInfo::use_instr_iterator
764 UI = MRI.use_instr_begin(Reg),
765 UE = MRI.use_instr_end();
766 UI != UE; ++UI) {
767 MachineInstr *UseMI = &*UI;
768 SUnit *SU = getSUnit(UseMI);
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000769 if (SU != nullptr && UseMI->isPHI()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +0000770 if (!MI->isPHI()) {
771 SDep Dep(SU, SDep::Anti, Reg);
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +0000772 Dep.setLatency(1);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000773 I.addPred(Dep);
774 } else {
775 HasPhiDef = Reg;
776 // Add a chain edge to a dependent Phi that isn't an existing
777 // predecessor.
778 if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
779 I.addPred(SDep(SU, SDep::Barrier));
780 }
781 }
782 }
783 } else if (MOI->isUse()) {
784 // If the register is defined by a Phi, then create a true dependence.
785 MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000786 if (DefMI == nullptr)
Brendon Cahoon254f8892016-07-29 16:44:44 +0000787 continue;
788 SUnit *SU = getSUnit(DefMI);
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000789 if (SU != nullptr && DefMI->isPHI()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +0000790 if (!MI->isPHI()) {
791 SDep Dep(SU, SDep::Data, Reg);
792 Dep.setLatency(0);
793 ST.adjustSchedDependency(SU, &I, Dep);
794 I.addPred(Dep);
795 } else {
796 HasPhiUse = Reg;
797 // Add a chain edge to a dependent Phi that isn't an existing
798 // predecessor.
799 if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
800 I.addPred(SDep(SU, SDep::Barrier));
801 }
802 }
803 }
804 }
805 // Remove order dependences from an unrelated Phi.
806 if (!SwpPruneDeps)
807 continue;
808 for (auto &PI : I.Preds) {
809 MachineInstr *PMI = PI.getSUnit()->getInstr();
810 if (PMI->isPHI() && PI.getKind() == SDep::Order) {
811 if (I.getInstr()->isPHI()) {
812 if (PMI->getOperand(0).getReg() == HasPhiUse)
813 continue;
814 if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
815 continue;
816 }
817 RemoveDeps.push_back(PI);
818 }
819 }
820 for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
821 I.removePred(RemoveDeps[i]);
822 }
823}
824
825/// Iterate over each DAG node and see if we can change any dependences
826/// in order to reduce the recurrence MII.
827void SwingSchedulerDAG::changeDependences() {
828 // See if an instruction can use a value from the previous iteration.
829 // If so, we update the base and offset of the instruction and change
830 // the dependences.
831 for (SUnit &I : SUnits) {
832 unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
833 int64_t NewOffset = 0;
834 if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
835 NewOffset))
836 continue;
837
838 // Get the MI and SUnit for the instruction that defines the original base.
Daniel Sanders0c476112019-08-15 19:22:08 +0000839 Register OrigBase = I.getInstr()->getOperand(BasePos).getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +0000840 MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
841 if (!DefMI)
842 continue;
843 SUnit *DefSU = getSUnit(DefMI);
844 if (!DefSU)
845 continue;
846 // Get the MI and SUnit for the instruction that defins the new base.
847 MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
848 if (!LastMI)
849 continue;
850 SUnit *LastSU = getSUnit(LastMI);
851 if (!LastSU)
852 continue;
853
854 if (Topo.IsReachable(&I, LastSU))
855 continue;
856
857 // Remove the dependence. The value now depends on a prior iteration.
858 SmallVector<SDep, 4> Deps;
859 for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E;
860 ++P)
861 if (P->getSUnit() == DefSU)
862 Deps.push_back(*P);
863 for (int i = 0, e = Deps.size(); i != e; i++) {
864 Topo.RemovePred(&I, Deps[i].getSUnit());
865 I.removePred(Deps[i]);
866 }
867 // Remove the chain dependence between the instructions.
868 Deps.clear();
869 for (auto &P : LastSU->Preds)
870 if (P.getSUnit() == &I && P.getKind() == SDep::Order)
871 Deps.push_back(P);
872 for (int i = 0, e = Deps.size(); i != e; i++) {
873 Topo.RemovePred(LastSU, Deps[i].getSUnit());
874 LastSU->removePred(Deps[i]);
875 }
876
877 // Add a dependence between the new instruction and the instruction
878 // that defines the new base.
879 SDep Dep(&I, SDep::Anti, NewBase);
Sumanth Gundapaneni8916e432018-10-11 19:42:46 +0000880 Topo.AddPred(LastSU, &I);
Brendon Cahoon254f8892016-07-29 16:44:44 +0000881 LastSU->addPred(Dep);
882
883 // Remember the base and offset information so that we can update the
884 // instruction during code generation.
885 InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
886 }
887}
888
889namespace {
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000890
Brendon Cahoon254f8892016-07-29 16:44:44 +0000891// FuncUnitSorter - Comparison operator used to sort instructions by
892// the number of functional unit choices.
893struct FuncUnitSorter {
894 const InstrItineraryData *InstrItins;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000895 const MCSubtargetInfo *STI;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000896 DenseMap<unsigned, unsigned> Resources;
897
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000898 FuncUnitSorter(const TargetSubtargetInfo &TSI)
899 : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
Eugene Zelenko32a40562017-09-11 23:00:48 +0000900
Brendon Cahoon254f8892016-07-29 16:44:44 +0000901 // Compute the number of functional unit alternatives needed
902 // at each stage, and take the minimum value. We prioritize the
903 // instructions by the least number of choices first.
904 unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const {
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000905 unsigned SchedClass = Inst->getDesc().getSchedClass();
Brendon Cahoon254f8892016-07-29 16:44:44 +0000906 unsigned min = UINT_MAX;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000907 if (InstrItins && !InstrItins->isEmpty()) {
908 for (const InstrStage &IS :
909 make_range(InstrItins->beginStage(SchedClass),
910 InstrItins->endStage(SchedClass))) {
911 unsigned funcUnits = IS.getUnits();
912 unsigned numAlternatives = countPopulation(funcUnits);
913 if (numAlternatives < min) {
914 min = numAlternatives;
915 F = funcUnits;
916 }
Brendon Cahoon254f8892016-07-29 16:44:44 +0000917 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000918 return min;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000919 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000920 if (STI && STI->getSchedModel().hasInstrSchedModel()) {
921 const MCSchedClassDesc *SCDesc =
922 STI->getSchedModel().getSchedClassDesc(SchedClass);
923 if (!SCDesc->isValid())
924 // No valid Schedule Class Desc for schedClass, should be
925 // Pseudo/PostRAPseudo
926 return min;
927
928 for (const MCWriteProcResEntry &PRE :
929 make_range(STI->getWriteProcResBegin(SCDesc),
930 STI->getWriteProcResEnd(SCDesc))) {
931 if (!PRE.Cycles)
932 continue;
933 const MCProcResourceDesc *ProcResource =
934 STI->getSchedModel().getProcResource(PRE.ProcResourceIdx);
935 unsigned NumUnits = ProcResource->NumUnits;
936 if (NumUnits < min) {
937 min = NumUnits;
938 F = PRE.ProcResourceIdx;
939 }
940 }
941 return min;
942 }
943 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000944 }
945
946 // Compute the critical resources needed by the instruction. This
947 // function records the functional units needed by instructions that
948 // must use only one functional unit. We use this as a tie breaker
949 // for computing the resource MII. The instrutions that require
950 // the same, highly used, functional unit have high priority.
951 void calcCriticalResources(MachineInstr &MI) {
952 unsigned SchedClass = MI.getDesc().getSchedClass();
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000953 if (InstrItins && !InstrItins->isEmpty()) {
954 for (const InstrStage &IS :
955 make_range(InstrItins->beginStage(SchedClass),
956 InstrItins->endStage(SchedClass))) {
957 unsigned FuncUnits = IS.getUnits();
958 if (countPopulation(FuncUnits) == 1)
959 Resources[FuncUnits]++;
960 }
961 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +0000962 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +0000963 if (STI && STI->getSchedModel().hasInstrSchedModel()) {
964 const MCSchedClassDesc *SCDesc =
965 STI->getSchedModel().getSchedClassDesc(SchedClass);
966 if (!SCDesc->isValid())
967 // No valid Schedule Class Desc for schedClass, should be
968 // Pseudo/PostRAPseudo
969 return;
970
971 for (const MCWriteProcResEntry &PRE :
972 make_range(STI->getWriteProcResBegin(SCDesc),
973 STI->getWriteProcResEnd(SCDesc))) {
974 if (!PRE.Cycles)
975 continue;
976 Resources[PRE.ProcResourceIdx]++;
977 }
978 return;
979 }
980 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
Brendon Cahoon254f8892016-07-29 16:44:44 +0000981 }
982
Brendon Cahoon254f8892016-07-29 16:44:44 +0000983 /// Return true if IS1 has less priority than IS2.
984 bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
985 unsigned F1 = 0, F2 = 0;
986 unsigned MFUs1 = minFuncUnits(IS1, F1);
987 unsigned MFUs2 = minFuncUnits(IS2, F2);
Jinsong Ji6349ce52019-08-09 14:10:57 +0000988 if (MFUs1 == MFUs2)
Brendon Cahoon254f8892016-07-29 16:44:44 +0000989 return Resources.lookup(F1) < Resources.lookup(F2);
990 return MFUs1 > MFUs2;
991 }
992};
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000993
994} // end anonymous namespace
Brendon Cahoon254f8892016-07-29 16:44:44 +0000995
996/// Calculate the resource constrained minimum initiation interval for the
997/// specified loop. We use the DFA to model the resources needed for
998/// each instruction, and we ignore dependences. A different DFA is created
999/// for each cycle that is required. When adding a new instruction, we attempt
1000/// to add it to each existing DFA, until a legal space is found. If the
1001/// instruction cannot be reserved in an existing DFA, we create a new one.
1002unsigned SwingSchedulerDAG::calculateResMII() {
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00001003
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001004 LLVM_DEBUG(dbgs() << "calculateResMII:\n");
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00001005 SmallVector<ResourceManager*, 8> Resources;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001006 MachineBasicBlock *MBB = Loop.getHeader();
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00001007 Resources.push_back(new ResourceManager(&MF.getSubtarget()));
Brendon Cahoon254f8892016-07-29 16:44:44 +00001008
1009 // Sort the instructions by the number of available choices for scheduling,
1010 // least to most. Use the number of critical resources as the tie breaker.
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00001011 FuncUnitSorter FUS = FuncUnitSorter(MF.getSubtarget());
Brendon Cahoon254f8892016-07-29 16:44:44 +00001012 for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
1013 E = MBB->getFirstTerminator();
1014 I != E; ++I)
1015 FUS.calcCriticalResources(*I);
1016 PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
1017 FuncUnitOrder(FUS);
1018
1019 for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
1020 E = MBB->getFirstTerminator();
1021 I != E; ++I)
1022 FuncUnitOrder.push(&*I);
1023
1024 while (!FuncUnitOrder.empty()) {
1025 MachineInstr *MI = FuncUnitOrder.top();
1026 FuncUnitOrder.pop();
1027 if (TII->isZeroCost(MI->getOpcode()))
1028 continue;
1029 // Attempt to reserve the instruction in an existing DFA. At least one
1030 // DFA is needed for each cycle.
1031 unsigned NumCycles = getSUnit(MI)->Latency;
1032 unsigned ReservedCycles = 0;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00001033 SmallVectorImpl<ResourceManager *>::iterator RI = Resources.begin();
1034 SmallVectorImpl<ResourceManager *>::iterator RE = Resources.end();
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001035 LLVM_DEBUG({
1036 dbgs() << "Trying to reserve resource for " << NumCycles
1037 << " cycles for \n";
1038 MI->dump();
1039 });
Brendon Cahoon254f8892016-07-29 16:44:44 +00001040 for (unsigned C = 0; C < NumCycles; ++C)
1041 while (RI != RE) {
Jinsong Jifee855b2019-06-25 21:50:56 +00001042 if ((*RI)->canReserveResources(*MI)) {
1043 (*RI)->reserveResources(*MI);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001044 ++ReservedCycles;
1045 break;
1046 }
Jinsong Jifee855b2019-06-25 21:50:56 +00001047 RI++;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001048 }
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001049 LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
1050 << ", NumCycles:" << NumCycles << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001051 // Add new DFAs, if needed, to reserve resources.
1052 for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
Jinsong Jiba438402019-06-18 20:24:49 +00001053 LLVM_DEBUG(if (SwpDebugResource) dbgs()
1054 << "NewResource created to reserve resources"
1055 << "\n");
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00001056 ResourceManager *NewResource = new ResourceManager(&MF.getSubtarget());
Brendon Cahoon254f8892016-07-29 16:44:44 +00001057 assert(NewResource->canReserveResources(*MI) && "Reserve error.");
1058 NewResource->reserveResources(*MI);
1059 Resources.push_back(NewResource);
1060 }
1061 }
1062 int Resmii = Resources.size();
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001063 LLVM_DEBUG(dbgs() << "Retrun Res MII:" << Resmii << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001064 // Delete the memory for each of the DFAs that were created earlier.
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00001065 for (ResourceManager *RI : Resources) {
1066 ResourceManager *D = RI;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001067 delete D;
1068 }
1069 Resources.clear();
1070 return Resmii;
1071}
1072
1073/// Calculate the recurrence-constrainted minimum initiation interval.
1074/// Iterate over each circuit. Compute the delay(c) and distance(c)
1075/// for each circuit. The II needs to satisfy the inequality
1076/// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001077/// II that satisfies the inequality, and the RecMII is the maximum
Brendon Cahoon254f8892016-07-29 16:44:44 +00001078/// of those values.
1079unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1080 unsigned RecMII = 0;
1081
1082 for (NodeSet &Nodes : NodeSets) {
Eugene Zelenko32a40562017-09-11 23:00:48 +00001083 if (Nodes.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001084 continue;
1085
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00001086 unsigned Delay = Nodes.getLatency();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001087 unsigned Distance = 1;
1088
1089 // ii = ceil(delay / distance)
1090 unsigned CurMII = (Delay + Distance - 1) / Distance;
1091 Nodes.setRecMII(CurMII);
1092 if (CurMII > RecMII)
1093 RecMII = CurMII;
1094 }
1095
1096 return RecMII;
1097}
1098
1099/// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1100/// but we do this to find the circuits, and then change them back.
1101static void swapAntiDependences(std::vector<SUnit> &SUnits) {
1102 SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
1103 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1104 SUnit *SU = &SUnits[i];
1105 for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end();
1106 IP != EP; ++IP) {
1107 if (IP->getKind() != SDep::Anti)
1108 continue;
1109 DepsAdded.push_back(std::make_pair(SU, *IP));
1110 }
1111 }
1112 for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(),
1113 E = DepsAdded.end();
1114 I != E; ++I) {
1115 // Remove this anti dependency and add one in the reverse direction.
1116 SUnit *SU = I->first;
1117 SDep &D = I->second;
1118 SUnit *TargetSU = D.getSUnit();
1119 unsigned Reg = D.getReg();
1120 unsigned Lat = D.getLatency();
1121 SU->removePred(D);
1122 SDep Dep(SU, SDep::Anti, Reg);
1123 Dep.setLatency(Lat);
1124 TargetSU->addPred(Dep);
1125 }
1126}
1127
1128/// Create the adjacency structure of the nodes in the graph.
1129void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1130 SwingSchedulerDAG *DAG) {
1131 BitVector Added(SUnits.size());
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001132 DenseMap<int, int> OutputDeps;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001133 for (int i = 0, e = SUnits.size(); i != e; ++i) {
1134 Added.reset();
1135 // Add any successor to the adjacency matrix and exclude duplicates.
1136 for (auto &SI : SUnits[i].Succs) {
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001137 // Only create a back-edge on the first and last nodes of a dependence
1138 // chain. This records any chains and adds them later.
1139 if (SI.getKind() == SDep::Output) {
1140 int N = SI.getSUnit()->NodeNum;
1141 int BackEdge = i;
1142 auto Dep = OutputDeps.find(BackEdge);
1143 if (Dep != OutputDeps.end()) {
1144 BackEdge = Dep->second;
1145 OutputDeps.erase(Dep);
1146 }
1147 OutputDeps[N] = BackEdge;
1148 }
Sumanth Gundapaneniada0f512018-10-25 21:27:08 +00001149 // Do not process a boundary node, an artificial node.
1150 // A back-edge is processed only if it goes to a Phi.
1151 if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() ||
Brendon Cahoon254f8892016-07-29 16:44:44 +00001152 (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
1153 continue;
1154 int N = SI.getSUnit()->NodeNum;
1155 if (!Added.test(N)) {
1156 AdjK[i].push_back(N);
1157 Added.set(N);
1158 }
1159 }
1160 // A chain edge between a store and a load is treated as a back-edge in the
1161 // adjacency matrix.
1162 for (auto &PI : SUnits[i].Preds) {
1163 if (!SUnits[i].getInstr()->mayStore() ||
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001164 !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001165 continue;
1166 if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1167 int N = PI.getSUnit()->NodeNum;
1168 if (!Added.test(N)) {
1169 AdjK[i].push_back(N);
1170 Added.set(N);
1171 }
1172 }
1173 }
1174 }
Hiroshi Inouedad8c6a2019-01-09 05:11:10 +00001175 // Add back-edges in the adjacency matrix for the output dependences.
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00001176 for (auto &OD : OutputDeps)
1177 if (!Added.test(OD.second)) {
1178 AdjK[OD.first].push_back(OD.second);
1179 Added.set(OD.second);
1180 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00001181}
1182
1183/// Identify an elementary circuit in the dependence graph starting at the
1184/// specified node.
1185bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
1186 bool HasBackedge) {
1187 SUnit *SV = &SUnits[V];
1188 bool F = false;
1189 Stack.insert(SV);
1190 Blocked.set(V);
1191
1192 for (auto W : AdjK[V]) {
1193 if (NumPaths > MaxPaths)
1194 break;
1195 if (W < S)
1196 continue;
1197 if (W == S) {
1198 if (!HasBackedge)
1199 NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
1200 F = true;
1201 ++NumPaths;
1202 break;
1203 } else if (!Blocked.test(W)) {
Sumanth Gundapaneni77418a32018-10-11 19:45:07 +00001204 if (circuit(W, S, NodeSets,
1205 Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001206 F = true;
1207 }
1208 }
1209
1210 if (F)
1211 unblock(V);
1212 else {
1213 for (auto W : AdjK[V]) {
1214 if (W < S)
1215 continue;
1216 if (B[W].count(SV) == 0)
1217 B[W].insert(SV);
1218 }
1219 }
1220 Stack.pop_back();
1221 return F;
1222}
1223
1224/// Unblock a node in the circuit finding algorithm.
1225void SwingSchedulerDAG::Circuits::unblock(int U) {
1226 Blocked.reset(U);
1227 SmallPtrSet<SUnit *, 4> &BU = B[U];
1228 while (!BU.empty()) {
1229 SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
1230 assert(SI != BU.end() && "Invalid B set.");
1231 SUnit *W = *SI;
1232 BU.erase(W);
1233 if (Blocked.test(W->NodeNum))
1234 unblock(W->NodeNum);
1235 }
1236}
1237
1238/// Identify all the elementary circuits in the dependence graph using
1239/// Johnson's circuit algorithm.
1240void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1241 // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1242 // but we do this to find the circuits, and then change them back.
1243 swapAntiDependences(SUnits);
1244
Sumanth Gundapaneni77418a32018-10-11 19:45:07 +00001245 Circuits Cir(SUnits, Topo);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001246 // Create the adjacency structure.
1247 Cir.createAdjacencyStructure(this);
1248 for (int i = 0, e = SUnits.size(); i != e; ++i) {
1249 Cir.reset();
1250 Cir.circuit(i, i, NodeSets);
1251 }
1252
1253 // Change the dependences back so that we've created a DAG again.
1254 swapAntiDependences(SUnits);
1255}
1256
Sumanth Gundapaneni62ac69d2018-10-18 15:51:16 +00001257// Create artificial dependencies between the source of COPY/REG_SEQUENCE that
1258// is loop-carried to the USE in next iteration. This will help pipeliner avoid
1259// additional copies that are needed across iterations. An artificial dependence
1260// edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
1261
1262// PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
1263// SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
1264// PHI-------True-Dep------> USEOfPhi
1265
1266// The mutation creates
1267// USEOfPHI -------Artificial-Dep---> SRCOfCopy
1268
1269// This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
1270// (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
1271// late to avoid additional copies across iterations. The possible scheduling
1272// order would be
1273// USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE.
1274
1275void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
1276 for (SUnit &SU : DAG->SUnits) {
1277 // Find the COPY/REG_SEQUENCE instruction.
1278 if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
1279 continue;
1280
1281 // Record the loop carried PHIs.
1282 SmallVector<SUnit *, 4> PHISUs;
1283 // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
1284 SmallVector<SUnit *, 4> SrcSUs;
1285
1286 for (auto &Dep : SU.Preds) {
1287 SUnit *TmpSU = Dep.getSUnit();
1288 MachineInstr *TmpMI = TmpSU->getInstr();
1289 SDep::Kind DepKind = Dep.getKind();
1290 // Save the loop carried PHI.
1291 if (DepKind == SDep::Anti && TmpMI->isPHI())
1292 PHISUs.push_back(TmpSU);
1293 // Save the source of COPY/REG_SEQUENCE.
1294 // If the source has no pre-decessors, we will end up creating cycles.
1295 else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
1296 SrcSUs.push_back(TmpSU);
1297 }
1298
1299 if (PHISUs.size() == 0 || SrcSUs.size() == 0)
1300 continue;
1301
1302 // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
1303 // SUnit to the container.
1304 SmallVector<SUnit *, 8> UseSUs;
1305 for (auto I = PHISUs.begin(); I != PHISUs.end(); ++I) {
1306 for (auto &Dep : (*I)->Succs) {
1307 if (Dep.getKind() != SDep::Data)
1308 continue;
1309
1310 SUnit *TmpSU = Dep.getSUnit();
1311 MachineInstr *TmpMI = TmpSU->getInstr();
1312 if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
1313 PHISUs.push_back(TmpSU);
1314 continue;
1315 }
1316 UseSUs.push_back(TmpSU);
1317 }
1318 }
1319
1320 if (UseSUs.size() == 0)
1321 continue;
1322
1323 SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
1324 // Add the artificial dependencies if it does not form a cycle.
1325 for (auto I : UseSUs) {
1326 for (auto Src : SrcSUs) {
1327 if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
1328 Src->addPred(SDep(I, SDep::Artificial));
1329 SDAG->Topo.AddPred(Src, I);
1330 }
1331 }
1332 }
1333 }
1334}
1335
Brendon Cahoon254f8892016-07-29 16:44:44 +00001336/// Return true for DAG nodes that we ignore when computing the cost functions.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001337/// We ignore the back-edge recurrence in order to avoid unbounded recursion
Brendon Cahoon254f8892016-07-29 16:44:44 +00001338/// in the calculation of the ASAP, ALAP, etc functions.
1339static bool ignoreDependence(const SDep &D, bool isPred) {
1340 if (D.isArtificial())
1341 return true;
1342 return D.getKind() == SDep::Anti && isPred;
1343}
1344
1345/// Compute several functions need to order the nodes for scheduling.
1346/// ASAP - Earliest time to schedule a node.
1347/// ALAP - Latest time to schedule a node.
1348/// MOV - Mobility function, difference between ALAP and ASAP.
1349/// D - Depth of each node.
1350/// H - Height of each node.
1351void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001352 ScheduleInfo.resize(SUnits.size());
1353
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001354 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001355 for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1356 E = Topo.end();
1357 I != E; ++I) {
Matthias Braun726e12c2018-09-19 00:23:35 +00001358 const SUnit &SU = SUnits[*I];
1359 dumpNode(SU);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001360 }
1361 });
1362
1363 int maxASAP = 0;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001364 // Compute ASAP and ZeroLatencyDepth.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001365 for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1366 E = Topo.end();
1367 I != E; ++I) {
1368 int asap = 0;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001369 int zeroLatencyDepth = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001370 SUnit *SU = &SUnits[*I];
1371 for (SUnit::const_pred_iterator IP = SU->Preds.begin(),
1372 EP = SU->Preds.end();
1373 IP != EP; ++IP) {
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001374 SUnit *pred = IP->getSUnit();
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001375 if (IP->getLatency() == 0)
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001376 zeroLatencyDepth =
1377 std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001378 if (ignoreDependence(*IP, true))
1379 continue;
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001380 asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() -
Brendon Cahoon254f8892016-07-29 16:44:44 +00001381 getDistance(pred, SU, *IP) * MII));
1382 }
1383 maxASAP = std::max(maxASAP, asap);
1384 ScheduleInfo[*I].ASAP = asap;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001385 ScheduleInfo[*I].ZeroLatencyDepth = zeroLatencyDepth;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001386 }
1387
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001388 // Compute ALAP, ZeroLatencyHeight, and MOV.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001389 for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(),
1390 E = Topo.rend();
1391 I != E; ++I) {
1392 int alap = maxASAP;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001393 int zeroLatencyHeight = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001394 SUnit *SU = &SUnits[*I];
1395 for (SUnit::const_succ_iterator IS = SU->Succs.begin(),
1396 ES = SU->Succs.end();
1397 IS != ES; ++IS) {
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001398 SUnit *succ = IS->getSUnit();
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001399 if (IS->getLatency() == 0)
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001400 zeroLatencyHeight =
1401 std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001402 if (ignoreDependence(*IS, true))
1403 continue;
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00001404 alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() +
Brendon Cahoon254f8892016-07-29 16:44:44 +00001405 getDistance(SU, succ, *IS) * MII));
1406 }
1407
1408 ScheduleInfo[*I].ALAP = alap;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001409 ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001410 }
1411
1412 // After computing the node functions, compute the summary for each node set.
1413 for (NodeSet &I : NodeSets)
1414 I.computeNodeSetInfo(this);
1415
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001416 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001417 for (unsigned i = 0; i < SUnits.size(); i++) {
1418 dbgs() << "\tNode " << i << ":\n";
1419 dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n";
1420 dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n";
1421 dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n";
1422 dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n";
1423 dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n";
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001424 dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
1425 dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
Brendon Cahoon254f8892016-07-29 16:44:44 +00001426 }
1427 });
1428}
1429
1430/// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1431/// as the predecessors of the elements of NodeOrder that are not also in
1432/// NodeOrder.
1433static bool pred_L(SetVector<SUnit *> &NodeOrder,
1434 SmallSetVector<SUnit *, 8> &Preds,
1435 const NodeSet *S = nullptr) {
1436 Preds.clear();
1437 for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1438 I != E; ++I) {
1439 for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end();
1440 PI != PE; ++PI) {
1441 if (S && S->count(PI->getSUnit()) == 0)
1442 continue;
1443 if (ignoreDependence(*PI, true))
1444 continue;
1445 if (NodeOrder.count(PI->getSUnit()) == 0)
1446 Preds.insert(PI->getSUnit());
1447 }
1448 // Back-edges are predecessors with an anti-dependence.
1449 for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(),
1450 ES = (*I)->Succs.end();
1451 IS != ES; ++IS) {
1452 if (IS->getKind() != SDep::Anti)
1453 continue;
1454 if (S && S->count(IS->getSUnit()) == 0)
1455 continue;
1456 if (NodeOrder.count(IS->getSUnit()) == 0)
1457 Preds.insert(IS->getSUnit());
1458 }
1459 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001460 return !Preds.empty();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001461}
1462
1463/// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1464/// as the successors of the elements of NodeOrder that are not also in
1465/// NodeOrder.
1466static bool succ_L(SetVector<SUnit *> &NodeOrder,
1467 SmallSetVector<SUnit *, 8> &Succs,
1468 const NodeSet *S = nullptr) {
1469 Succs.clear();
1470 for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1471 I != E; ++I) {
1472 for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end();
1473 SI != SE; ++SI) {
1474 if (S && S->count(SI->getSUnit()) == 0)
1475 continue;
1476 if (ignoreDependence(*SI, false))
1477 continue;
1478 if (NodeOrder.count(SI->getSUnit()) == 0)
1479 Succs.insert(SI->getSUnit());
1480 }
1481 for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(),
1482 PE = (*I)->Preds.end();
1483 PI != PE; ++PI) {
1484 if (PI->getKind() != SDep::Anti)
1485 continue;
1486 if (S && S->count(PI->getSUnit()) == 0)
1487 continue;
1488 if (NodeOrder.count(PI->getSUnit()) == 0)
1489 Succs.insert(PI->getSUnit());
1490 }
1491 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001492 return !Succs.empty();
Brendon Cahoon254f8892016-07-29 16:44:44 +00001493}
1494
1495/// Return true if there is a path from the specified node to any of the nodes
1496/// in DestNodes. Keep track and return the nodes in any path.
1497static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
1498 SetVector<SUnit *> &DestNodes,
1499 SetVector<SUnit *> &Exclude,
1500 SmallPtrSet<SUnit *, 8> &Visited) {
1501 if (Cur->isBoundaryNode())
1502 return false;
1503 if (Exclude.count(Cur) != 0)
1504 return false;
1505 if (DestNodes.count(Cur) != 0)
1506 return true;
1507 if (!Visited.insert(Cur).second)
1508 return Path.count(Cur) != 0;
1509 bool FoundPath = false;
1510 for (auto &SI : Cur->Succs)
1511 FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
1512 for (auto &PI : Cur->Preds)
1513 if (PI.getKind() == SDep::Anti)
1514 FoundPath |=
1515 computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
1516 if (FoundPath)
1517 Path.insert(Cur);
1518 return FoundPath;
1519}
1520
1521/// Return true if Set1 is a subset of Set2.
1522template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
1523 for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I)
1524 if (Set2.count(*I) == 0)
1525 return false;
1526 return true;
1527}
1528
1529/// Compute the live-out registers for the instructions in a node-set.
1530/// The live-out registers are those that are defined in the node-set,
1531/// but not used. Except for use operands of Phis.
1532static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
1533 NodeSet &NS) {
1534 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1535 MachineRegisterInfo &MRI = MF.getRegInfo();
1536 SmallVector<RegisterMaskPair, 8> LiveOutRegs;
1537 SmallSet<unsigned, 4> Uses;
1538 for (SUnit *SU : NS) {
1539 const MachineInstr *MI = SU->getInstr();
1540 if (MI->isPHI())
1541 continue;
Matthias Braunfc371552016-10-24 21:36:43 +00001542 for (const MachineOperand &MO : MI->operands())
1543 if (MO.isReg() && MO.isUse()) {
Daniel Sanders0c476112019-08-15 19:22:08 +00001544 Register Reg = MO.getReg();
Daniel Sanders2bea69b2019-08-01 23:27:28 +00001545 if (Register::isVirtualRegister(Reg))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001546 Uses.insert(Reg);
1547 else if (MRI.isAllocatable(Reg))
1548 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1549 Uses.insert(*Units);
1550 }
1551 }
1552 for (SUnit *SU : NS)
Matthias Braunfc371552016-10-24 21:36:43 +00001553 for (const MachineOperand &MO : SU->getInstr()->operands())
1554 if (MO.isReg() && MO.isDef() && !MO.isDead()) {
Daniel Sanders0c476112019-08-15 19:22:08 +00001555 Register Reg = MO.getReg();
Daniel Sanders2bea69b2019-08-01 23:27:28 +00001556 if (Register::isVirtualRegister(Reg)) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001557 if (!Uses.count(Reg))
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001558 LiveOutRegs.push_back(RegisterMaskPair(Reg,
1559 LaneBitmask::getNone()));
Brendon Cahoon254f8892016-07-29 16:44:44 +00001560 } else if (MRI.isAllocatable(Reg)) {
1561 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1562 if (!Uses.count(*Units))
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001563 LiveOutRegs.push_back(RegisterMaskPair(*Units,
1564 LaneBitmask::getNone()));
Brendon Cahoon254f8892016-07-29 16:44:44 +00001565 }
1566 }
1567 RPTracker.addLiveRegs(LiveOutRegs);
1568}
1569
1570/// A heuristic to filter nodes in recurrent node-sets if the register
1571/// pressure of a set is too high.
1572void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
1573 for (auto &NS : NodeSets) {
1574 // Skip small node-sets since they won't cause register pressure problems.
1575 if (NS.size() <= 2)
1576 continue;
1577 IntervalPressure RecRegPressure;
1578 RegPressureTracker RecRPTracker(RecRegPressure);
1579 RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
1580 computeLiveOuts(MF, RecRPTracker, NS);
1581 RecRPTracker.closeBottom();
1582
1583 std::vector<SUnit *> SUnits(NS.begin(), NS.end());
Fangrui Song0cac7262018-09-27 02:13:45 +00001584 llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001585 return A->NodeNum > B->NodeNum;
1586 });
1587
1588 for (auto &SU : SUnits) {
1589 // Since we're computing the register pressure for a subset of the
1590 // instructions in a block, we need to set the tracker for each
1591 // instruction in the node-set. The tracker is set to the instruction
1592 // just after the one we're interested in.
1593 MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
1594 RecRPTracker.setPos(std::next(CurInstI));
1595
1596 RegPressureDelta RPDelta;
1597 ArrayRef<PressureChange> CriticalPSets;
1598 RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
1599 CriticalPSets,
1600 RecRegPressure.MaxSetPressure);
1601 if (RPDelta.Excess.isValid()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001602 LLVM_DEBUG(
1603 dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
1604 << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
1605 << ":" << RPDelta.Excess.getUnitInc());
Brendon Cahoon254f8892016-07-29 16:44:44 +00001606 NS.setExceedPressure(SU);
1607 break;
1608 }
1609 RecRPTracker.recede();
1610 }
1611 }
1612}
1613
1614/// A heuristic to colocate node sets that have the same set of
1615/// successors.
1616void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
1617 unsigned Colocate = 0;
1618 for (int i = 0, e = NodeSets.size(); i < e; ++i) {
1619 NodeSet &N1 = NodeSets[i];
1620 SmallSetVector<SUnit *, 8> S1;
1621 if (N1.empty() || !succ_L(N1, S1))
1622 continue;
1623 for (int j = i + 1; j < e; ++j) {
1624 NodeSet &N2 = NodeSets[j];
1625 if (N1.compareRecMII(N2) != 0)
1626 continue;
1627 SmallSetVector<SUnit *, 8> S2;
1628 if (N2.empty() || !succ_L(N2, S2))
1629 continue;
1630 if (isSubset(S1, S2) && S1.size() == S2.size()) {
1631 N1.setColocate(++Colocate);
1632 N2.setColocate(Colocate);
1633 break;
1634 }
1635 }
1636 }
1637}
1638
1639/// Check if the existing node-sets are profitable. If not, then ignore the
1640/// recurrent node-sets, and attempt to schedule all nodes together. This is
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001641/// a heuristic. If the MII is large and all the recurrent node-sets are small,
1642/// then it's best to try to schedule all instructions together instead of
1643/// starting with the recurrent node-sets.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001644void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
1645 // Look for loops with a large MII.
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001646 if (MII < 17)
Brendon Cahoon254f8892016-07-29 16:44:44 +00001647 return;
1648 // Check if the node-set contains only a simple add recurrence.
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001649 for (auto &NS : NodeSets) {
1650 if (NS.getRecMII() > 2)
Brendon Cahoon254f8892016-07-29 16:44:44 +00001651 return;
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001652 if (NS.getMaxDepth() > MII)
Brendon Cahoon254f8892016-07-29 16:44:44 +00001653 return;
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001654 }
1655 NodeSets.clear();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001656 LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
Krzysztof Parzyszek3ca23342018-03-26 17:07:41 +00001657 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001658}
1659
1660/// Add the nodes that do not belong to a recurrence set into groups
1661/// based upon connected componenets.
1662void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
1663 SetVector<SUnit *> NodesAdded;
1664 SmallPtrSet<SUnit *, 8> Visited;
1665 // Add the nodes that are on a path between the previous node sets and
1666 // the current node set.
1667 for (NodeSet &I : NodeSets) {
1668 SmallSetVector<SUnit *, 8> N;
1669 // Add the nodes from the current node set to the previous node set.
1670 if (succ_L(I, N)) {
1671 SetVector<SUnit *> Path;
1672 for (SUnit *NI : N) {
1673 Visited.clear();
1674 computePath(NI, Path, NodesAdded, I, Visited);
1675 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001676 if (!Path.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001677 I.insert(Path.begin(), Path.end());
1678 }
1679 // Add the nodes from the previous node set to the current node set.
1680 N.clear();
1681 if (succ_L(NodesAdded, N)) {
1682 SetVector<SUnit *> Path;
1683 for (SUnit *NI : N) {
1684 Visited.clear();
1685 computePath(NI, Path, I, NodesAdded, Visited);
1686 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00001687 if (!Path.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001688 I.insert(Path.begin(), Path.end());
1689 }
1690 NodesAdded.insert(I.begin(), I.end());
1691 }
1692
1693 // Create a new node set with the connected nodes of any successor of a node
1694 // in a recurrent set.
1695 NodeSet NewSet;
1696 SmallSetVector<SUnit *, 8> N;
1697 if (succ_L(NodesAdded, N))
1698 for (SUnit *I : N)
1699 addConnectedNodes(I, NewSet, NodesAdded);
Eugene Zelenko32a40562017-09-11 23:00:48 +00001700 if (!NewSet.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001701 NodeSets.push_back(NewSet);
1702
1703 // Create a new node set with the connected nodes of any predecessor of a node
1704 // in a recurrent set.
1705 NewSet.clear();
1706 if (pred_L(NodesAdded, N))
1707 for (SUnit *I : N)
1708 addConnectedNodes(I, NewSet, NodesAdded);
Eugene Zelenko32a40562017-09-11 23:00:48 +00001709 if (!NewSet.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001710 NodeSets.push_back(NewSet);
1711
Hiroshi Inoue372ffa12018-04-13 11:37:06 +00001712 // Create new nodes sets with the connected nodes any remaining node that
Brendon Cahoon254f8892016-07-29 16:44:44 +00001713 // has no predecessor.
1714 for (unsigned i = 0; i < SUnits.size(); ++i) {
1715 SUnit *SU = &SUnits[i];
1716 if (NodesAdded.count(SU) == 0) {
1717 NewSet.clear();
1718 addConnectedNodes(SU, NewSet, NodesAdded);
Eugene Zelenko32a40562017-09-11 23:00:48 +00001719 if (!NewSet.empty())
Brendon Cahoon254f8892016-07-29 16:44:44 +00001720 NodeSets.push_back(NewSet);
1721 }
1722 }
1723}
1724
Alexey Lapshin31f47b82019-01-25 21:59:53 +00001725/// Add the node to the set, and add all of its connected nodes to the set.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001726void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
1727 SetVector<SUnit *> &NodesAdded) {
1728 NewSet.insert(SU);
1729 NodesAdded.insert(SU);
1730 for (auto &SI : SU->Succs) {
1731 SUnit *Successor = SI.getSUnit();
1732 if (!SI.isArtificial() && NodesAdded.count(Successor) == 0)
1733 addConnectedNodes(Successor, NewSet, NodesAdded);
1734 }
1735 for (auto &PI : SU->Preds) {
1736 SUnit *Predecessor = PI.getSUnit();
1737 if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
1738 addConnectedNodes(Predecessor, NewSet, NodesAdded);
1739 }
1740}
1741
1742/// Return true if Set1 contains elements in Set2. The elements in common
1743/// are returned in a different container.
1744static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
1745 SmallSetVector<SUnit *, 8> &Result) {
1746 Result.clear();
1747 for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
1748 SUnit *SU = Set1[i];
1749 if (Set2.count(SU) != 0)
1750 Result.insert(SU);
1751 }
1752 return !Result.empty();
1753}
1754
1755/// Merge the recurrence node sets that have the same initial node.
1756void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
1757 for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1758 ++I) {
1759 NodeSet &NI = *I;
1760 for (NodeSetType::iterator J = I + 1; J != E;) {
1761 NodeSet &NJ = *J;
1762 if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
1763 if (NJ.compareRecMII(NI) > 0)
1764 NI.setRecMII(NJ.getRecMII());
1765 for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI;
1766 ++NII)
1767 I->insert(*NII);
1768 NodeSets.erase(J);
1769 E = NodeSets.end();
1770 } else {
1771 ++J;
1772 }
1773 }
1774 }
1775}
1776
1777/// Remove nodes that have been scheduled in previous NodeSets.
1778void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
1779 for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1780 ++I)
1781 for (NodeSetType::iterator J = I + 1; J != E;) {
1782 J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
1783
Eugene Zelenko32a40562017-09-11 23:00:48 +00001784 if (J->empty()) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001785 NodeSets.erase(J);
1786 E = NodeSets.end();
1787 } else {
1788 ++J;
1789 }
1790 }
1791}
1792
Brendon Cahoon254f8892016-07-29 16:44:44 +00001793/// Compute an ordered list of the dependence graph nodes, which
1794/// indicates the order that the nodes will be scheduled. This is a
1795/// two-level algorithm. First, a partial order is created, which
1796/// consists of a list of sets ordered from highest to lowest priority.
1797void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
1798 SmallSetVector<SUnit *, 8> R;
1799 NodeOrder.clear();
1800
1801 for (auto &Nodes : NodeSets) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001802 LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001803 OrderKind Order;
1804 SmallSetVector<SUnit *, 8> N;
1805 if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) {
1806 R.insert(N.begin(), N.end());
1807 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001808 LLVM_DEBUG(dbgs() << " Bottom up (preds) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001809 } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) {
1810 R.insert(N.begin(), N.end());
1811 Order = TopDown;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001812 LLVM_DEBUG(dbgs() << " Top down (succs) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001813 } else if (isIntersect(N, Nodes, R)) {
1814 // If some of the successors are in the existing node-set, then use the
1815 // top-down ordering.
1816 Order = TopDown;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001817 LLVM_DEBUG(dbgs() << " Top down (intersect) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001818 } else if (NodeSets.size() == 1) {
1819 for (auto &N : Nodes)
1820 if (N->Succs.size() == 0)
1821 R.insert(N);
1822 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001823 LLVM_DEBUG(dbgs() << " Bottom up (all) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001824 } else {
1825 // Find the node with the highest ASAP.
1826 SUnit *maxASAP = nullptr;
1827 for (SUnit *SU : Nodes) {
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00001828 if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
1829 (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001830 maxASAP = SU;
1831 }
1832 R.insert(maxASAP);
1833 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001834 LLVM_DEBUG(dbgs() << " Bottom up (default) ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001835 }
1836
1837 while (!R.empty()) {
1838 if (Order == TopDown) {
1839 // Choose the node with the maximum height. If more than one, choose
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00001840 // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001841 // choose the node with the lowest MOV.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001842 while (!R.empty()) {
1843 SUnit *maxHeight = nullptr;
1844 for (SUnit *I : R) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001845 if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001846 maxHeight = I;
1847 else if (getHeight(I) == getHeight(maxHeight) &&
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001848 getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001849 maxHeight = I;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001850 else if (getHeight(I) == getHeight(maxHeight) &&
1851 getZeroLatencyHeight(I) ==
1852 getZeroLatencyHeight(maxHeight) &&
1853 getMOV(I) < getMOV(maxHeight))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001854 maxHeight = I;
1855 }
1856 NodeOrder.insert(maxHeight);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001857 LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001858 R.remove(maxHeight);
1859 for (const auto &I : maxHeight->Succs) {
1860 if (Nodes.count(I.getSUnit()) == 0)
1861 continue;
1862 if (NodeOrder.count(I.getSUnit()) != 0)
1863 continue;
1864 if (ignoreDependence(I, false))
1865 continue;
1866 R.insert(I.getSUnit());
1867 }
1868 // Back-edges are predecessors with an anti-dependence.
1869 for (const auto &I : maxHeight->Preds) {
1870 if (I.getKind() != SDep::Anti)
1871 continue;
1872 if (Nodes.count(I.getSUnit()) == 0)
1873 continue;
1874 if (NodeOrder.count(I.getSUnit()) != 0)
1875 continue;
1876 R.insert(I.getSUnit());
1877 }
1878 }
1879 Order = BottomUp;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001880 LLVM_DEBUG(dbgs() << "\n Switching order to bottom up ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001881 SmallSetVector<SUnit *, 8> N;
1882 if (pred_L(NodeOrder, N, &Nodes))
1883 R.insert(N.begin(), N.end());
1884 } else {
1885 // Choose the node with the maximum depth. If more than one, choose
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001886 // the node with the maximum ZeroLatencyDepth. If still more than one,
1887 // choose the node with the lowest MOV.
Brendon Cahoon254f8892016-07-29 16:44:44 +00001888 while (!R.empty()) {
1889 SUnit *maxDepth = nullptr;
1890 for (SUnit *I : R) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001891 if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001892 maxDepth = I;
1893 else if (getDepth(I) == getDepth(maxDepth) &&
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001894 getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001895 maxDepth = I;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00001896 else if (getDepth(I) == getDepth(maxDepth) &&
1897 getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
1898 getMOV(I) < getMOV(maxDepth))
Brendon Cahoon254f8892016-07-29 16:44:44 +00001899 maxDepth = I;
1900 }
1901 NodeOrder.insert(maxDepth);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001902 LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001903 R.remove(maxDepth);
1904 if (Nodes.isExceedSU(maxDepth)) {
1905 Order = TopDown;
1906 R.clear();
1907 R.insert(Nodes.getNode(0));
1908 break;
1909 }
1910 for (const auto &I : maxDepth->Preds) {
1911 if (Nodes.count(I.getSUnit()) == 0)
1912 continue;
1913 if (NodeOrder.count(I.getSUnit()) != 0)
1914 continue;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001915 R.insert(I.getSUnit());
1916 }
1917 // Back-edges are predecessors with an anti-dependence.
1918 for (const auto &I : maxDepth->Succs) {
1919 if (I.getKind() != SDep::Anti)
1920 continue;
1921 if (Nodes.count(I.getSUnit()) == 0)
1922 continue;
1923 if (NodeOrder.count(I.getSUnit()) != 0)
1924 continue;
1925 R.insert(I.getSUnit());
1926 }
1927 }
1928 Order = TopDown;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001929 LLVM_DEBUG(dbgs() << "\n Switching order to top down ");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001930 SmallSetVector<SUnit *, 8> N;
1931 if (succ_L(NodeOrder, N, &Nodes))
1932 R.insert(N.begin(), N.end());
1933 }
1934 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001935 LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001936 }
1937
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001938 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00001939 dbgs() << "Node order: ";
1940 for (SUnit *I : NodeOrder)
1941 dbgs() << " " << I->NodeNum << " ";
1942 dbgs() << "\n";
1943 });
1944}
1945
1946/// Process the nodes in the computed order and create the pipelined schedule
1947/// of the instructions, if possible. Return true if a schedule is found.
1948bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001949
1950 if (NodeOrder.empty()){
1951 LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
Brendon Cahoon254f8892016-07-29 16:44:44 +00001952 return false;
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001953 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00001954
1955 bool scheduleFound = false;
Brendon Cahoon59d99732019-01-23 03:26:10 +00001956 unsigned II = 0;
Brendon Cahoon254f8892016-07-29 16:44:44 +00001957 // Keep increasing II until a valid schedule is found.
Brendon Cahoon59d99732019-01-23 03:26:10 +00001958 for (II = MII; II <= MAX_II && !scheduleFound; ++II) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00001959 Schedule.reset();
1960 Schedule.setInitiationInterval(II);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001961 LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00001962
1963 SetVector<SUnit *>::iterator NI = NodeOrder.begin();
1964 SetVector<SUnit *>::iterator NE = NodeOrder.end();
1965 do {
1966 SUnit *SU = *NI;
1967
1968 // Compute the schedule time for the instruction, which is based
1969 // upon the scheduled time for any predecessors/successors.
1970 int EarlyStart = INT_MIN;
1971 int LateStart = INT_MAX;
1972 // These values are set when the size of the schedule window is limited
1973 // due to chain dependences.
1974 int SchedEnd = INT_MAX;
1975 int SchedStart = INT_MIN;
1976 Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
1977 II, this);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001978 LLVM_DEBUG({
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001979 dbgs() << "\n";
Brendon Cahoon254f8892016-07-29 16:44:44 +00001980 dbgs() << "Inst (" << SU->NodeNum << ") ";
1981 SU->getInstr()->dump();
1982 dbgs() << "\n";
1983 });
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001984 LLVM_DEBUG({
Jinsong Ji18e7bf52019-05-31 15:35:19 +00001985 dbgs() << format("\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart,
1986 LateStart, SchedEnd, SchedStart);
Brendon Cahoon254f8892016-07-29 16:44:44 +00001987 });
1988
1989 if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
1990 SchedStart > LateStart)
1991 scheduleFound = false;
1992 else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
1993 SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
1994 scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
1995 } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
1996 SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
1997 scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
1998 } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
1999 SchedEnd =
2000 std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
2001 // When scheduling a Phi it is better to start at the late cycle and go
2002 // backwards. The default order may insert the Phi too far away from
2003 // its first dependence.
2004 if (SU->getInstr()->isPHI())
2005 scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
2006 else
2007 scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
2008 } else {
2009 int FirstCycle = Schedule.getFirstCycle();
2010 scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
2011 FirstCycle + getASAP(SU) + II - 1, II);
2012 }
2013 // Even if we find a schedule, make sure the schedule doesn't exceed the
2014 // allowable number of stages. We keep trying if this happens.
2015 if (scheduleFound)
2016 if (SwpMaxStages > -1 &&
2017 Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
2018 scheduleFound = false;
2019
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002020 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00002021 if (!scheduleFound)
2022 dbgs() << "\tCan't schedule\n";
2023 });
2024 } while (++NI != NE && scheduleFound);
2025
2026 // If a schedule is found, check if it is a valid schedule too.
2027 if (scheduleFound)
2028 scheduleFound = Schedule.isValidSchedule(this);
2029 }
2030
Brendon Cahoon59d99732019-01-23 03:26:10 +00002031 LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound << " (II=" << II
2032 << ")\n");
Brendon Cahoon254f8892016-07-29 16:44:44 +00002033
2034 if (scheduleFound)
2035 Schedule.finalizeSchedule(this);
2036 else
2037 Schedule.reset();
2038
2039 return scheduleFound && Schedule.getMaxStageCount() > 0;
2040}
2041
Brendon Cahoon254f8892016-07-29 16:44:44 +00002042/// Return true if we can compute the amount the instruction changes
2043/// during each iteration. Set Delta to the amount of the change.
2044bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
2045 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +00002046 const MachineOperand *BaseOp;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002047 int64_t Offset;
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00002048 if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002049 return false;
2050
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00002051 if (!BaseOp->isReg())
2052 return false;
2053
Daniel Sanders0c476112019-08-15 19:22:08 +00002054 Register BaseReg = BaseOp->getReg();
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00002055
Brendon Cahoon254f8892016-07-29 16:44:44 +00002056 MachineRegisterInfo &MRI = MF.getRegInfo();
2057 // Check if there is a Phi. If so, get the definition in the loop.
2058 MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
2059 if (BaseDef && BaseDef->isPHI()) {
2060 BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
2061 BaseDef = MRI.getVRegDef(BaseReg);
2062 }
2063 if (!BaseDef)
2064 return false;
2065
2066 int D = 0;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002067 if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
Brendon Cahoon254f8892016-07-29 16:44:44 +00002068 return false;
2069
2070 Delta = D;
2071 return true;
2072}
2073
Brendon Cahoon254f8892016-07-29 16:44:44 +00002074/// Check if we can change the instruction to use an offset value from the
2075/// previous iteration. If so, return true and set the base and offset values
2076/// so that we can rewrite the load, if necessary.
2077/// v1 = Phi(v0, v3)
2078/// v2 = load v1, 0
2079/// v3 = post_store v1, 4, x
2080/// This function enables the load to be rewritten as v2 = load v3, 4.
2081bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
2082 unsigned &BasePos,
2083 unsigned &OffsetPos,
2084 unsigned &NewBase,
2085 int64_t &Offset) {
2086 // Get the load instruction.
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002087 if (TII->isPostIncrement(*MI))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002088 return false;
2089 unsigned BasePosLd, OffsetPosLd;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002090 if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002091 return false;
Daniel Sanders0c476112019-08-15 19:22:08 +00002092 Register BaseReg = MI->getOperand(BasePosLd).getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00002093
2094 // Look for the Phi instruction.
Justin Bognerfdf9bf42017-10-10 23:50:49 +00002095 MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
Brendon Cahoon254f8892016-07-29 16:44:44 +00002096 MachineInstr *Phi = MRI.getVRegDef(BaseReg);
2097 if (!Phi || !Phi->isPHI())
2098 return false;
2099 // Get the register defined in the loop block.
2100 unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
2101 if (!PrevReg)
2102 return false;
2103
2104 // Check for the post-increment load/store instruction.
2105 MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
2106 if (!PrevDef || PrevDef == MI)
2107 return false;
2108
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002109 if (!TII->isPostIncrement(*PrevDef))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002110 return false;
2111
2112 unsigned BasePos1 = 0, OffsetPos1 = 0;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002113 if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002114 return false;
2115
Krzysztof Parzyszek40df8a22018-03-26 16:17:06 +00002116 // Make sure that the instructions do not access the same memory location in
2117 // the next iteration.
Brendon Cahoon254f8892016-07-29 16:44:44 +00002118 int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
2119 int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
Krzysztof Parzyszek40df8a22018-03-26 16:17:06 +00002120 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2121 NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
2122 bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
2123 MF.DeleteMachineInstr(NewMI);
2124 if (!Disjoint)
Brendon Cahoon254f8892016-07-29 16:44:44 +00002125 return false;
2126
2127 // Set the return value once we determine that we return true.
2128 BasePos = BasePosLd;
2129 OffsetPos = OffsetPosLd;
2130 NewBase = PrevReg;
2131 Offset = StoreOffset;
2132 return true;
2133}
2134
2135/// Apply changes to the instruction if needed. The changes are need
2136/// to improve the scheduling and depend up on the final schedule.
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00002137void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
2138 SMSchedule &Schedule) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00002139 SUnit *SU = getSUnit(MI);
2140 DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
2141 InstrChanges.find(SU);
2142 if (It != InstrChanges.end()) {
2143 std::pair<unsigned, int64_t> RegAndOffset = It->second;
2144 unsigned BasePos, OffsetPos;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002145 if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00002146 return;
Daniel Sanders0c476112019-08-15 19:22:08 +00002147 Register BaseReg = MI->getOperand(BasePos).getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00002148 MachineInstr *LoopDef = findDefInLoop(BaseReg);
2149 int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
2150 int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
2151 int BaseStageNum = Schedule.stageScheduled(SU);
2152 int BaseCycleNum = Schedule.cycleScheduled(SU);
2153 if (BaseStageNum < DefStageNum) {
2154 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2155 int OffsetDiff = DefStageNum - BaseStageNum;
2156 if (DefCycleNum < BaseCycleNum) {
2157 NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
2158 if (OffsetDiff > 0)
2159 --OffsetDiff;
2160 }
2161 int64_t NewOffset =
2162 MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
2163 NewMI->getOperand(OffsetPos).setImm(NewOffset);
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00002164 SU->setInstr(NewMI);
2165 MISUnitMap[NewMI] = SU;
James Molloy790a7792019-08-30 18:49:50 +00002166 NewMIs[MI] = NewMI;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002167 }
2168 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002169}
2170
James Molloy790a7792019-08-30 18:49:50 +00002171/// Return the instruction in the loop that defines the register.
2172/// If the definition is a Phi, then follow the Phi operand to
2173/// the instruction in the loop.
2174MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) {
2175 SmallPtrSet<MachineInstr *, 8> Visited;
2176 MachineInstr *Def = MRI.getVRegDef(Reg);
2177 while (Def->isPHI()) {
2178 if (!Visited.insert(Def).second)
2179 break;
2180 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
2181 if (Def->getOperand(i + 1).getMBB() == BB) {
2182 Def = MRI.getVRegDef(Def->getOperand(i).getReg());
2183 break;
2184 }
2185 }
2186 return Def;
2187}
2188
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00002189/// Return true for an order or output dependence that is loop carried
2190/// potentially. A dependence is loop carried if the destination defines a valu
2191/// that may be used or defined by the source in a subsequent iteration.
2192bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
2193 bool isSucc) {
2194 if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
2195 Dep.isArtificial())
Brendon Cahoon254f8892016-07-29 16:44:44 +00002196 return false;
2197
2198 if (!SwpPruneLoopCarried)
2199 return true;
2200
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00002201 if (Dep.getKind() == SDep::Output)
2202 return true;
2203
Brendon Cahoon254f8892016-07-29 16:44:44 +00002204 MachineInstr *SI = Source->getInstr();
2205 MachineInstr *DI = Dep.getSUnit()->getInstr();
2206 if (!isSucc)
2207 std::swap(SI, DI);
2208 assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
2209
2210 // Assume ordered loads and stores may have a loop carried dependence.
2211 if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
Ulrich Weigand6c5d5ce2019-06-05 22:33:10 +00002212 SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
Brendon Cahoon254f8892016-07-29 16:44:44 +00002213 SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
2214 return true;
2215
2216 // Only chain dependences between a load and store can be loop carried.
2217 if (!DI->mayStore() || !SI->mayLoad())
2218 return false;
2219
2220 unsigned DeltaS, DeltaD;
2221 if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
2222 return true;
2223
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +00002224 const MachineOperand *BaseOpS, *BaseOpD;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002225 int64_t OffsetS, OffsetD;
2226 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00002227 if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, TRI) ||
2228 !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, TRI))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002229 return true;
2230
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00002231 if (!BaseOpS->isIdenticalTo(*BaseOpD))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002232 return true;
2233
Krzysztof Parzyszek8c07d0c2018-03-26 16:58:40 +00002234 // Check that the base register is incremented by a constant value for each
2235 // iteration.
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00002236 MachineInstr *Def = MRI.getVRegDef(BaseOpS->getReg());
Krzysztof Parzyszek8c07d0c2018-03-26 16:58:40 +00002237 if (!Def || !Def->isPHI())
2238 return true;
2239 unsigned InitVal = 0;
2240 unsigned LoopVal = 0;
2241 getPhiRegs(*Def, BB, InitVal, LoopVal);
2242 MachineInstr *LoopDef = MRI.getVRegDef(LoopVal);
2243 int D = 0;
2244 if (!LoopDef || !TII->getIncrementValue(*LoopDef, D))
2245 return true;
2246
Brendon Cahoon254f8892016-07-29 16:44:44 +00002247 uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
2248 uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
2249
2250 // This is the main test, which checks the offset values and the loop
2251 // increment value to determine if the accesses may be loop carried.
Brendon Cahoon57c3d4b2019-04-11 21:57:51 +00002252 if (AccessSizeS == MemoryLocation::UnknownSize ||
2253 AccessSizeD == MemoryLocation::UnknownSize)
2254 return true;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002255
Brendon Cahoon57c3d4b2019-04-11 21:57:51 +00002256 if (DeltaS != DeltaD || DeltaS < AccessSizeS || DeltaD < AccessSizeD)
2257 return true;
2258
2259 return (OffsetS + (int64_t)AccessSizeS < OffsetD + (int64_t)AccessSizeD);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002260}
2261
Krzysztof Parzyszek88391242016-12-22 19:21:20 +00002262void SwingSchedulerDAG::postprocessDAG() {
2263 for (auto &M : Mutations)
2264 M->apply(this);
2265}
2266
Brendon Cahoon254f8892016-07-29 16:44:44 +00002267/// Try to schedule the node at the specified StartCycle and continue
2268/// until the node is schedule or the EndCycle is reached. This function
2269/// returns true if the node is scheduled. This routine may search either
2270/// forward or backward for a place to insert the instruction based upon
2271/// the relative values of StartCycle and EndCycle.
2272bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
2273 bool forward = true;
Jinsong Ji18e7bf52019-05-31 15:35:19 +00002274 LLVM_DEBUG({
2275 dbgs() << "Trying to insert node between " << StartCycle << " and "
2276 << EndCycle << " II: " << II << "\n";
2277 });
Brendon Cahoon254f8892016-07-29 16:44:44 +00002278 if (StartCycle > EndCycle)
2279 forward = false;
2280
2281 // The terminating condition depends on the direction.
2282 int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
2283 for (int curCycle = StartCycle; curCycle != termCycle;
2284 forward ? ++curCycle : --curCycle) {
2285
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00002286 // Add the already scheduled instructions at the specified cycle to the
2287 // DFA.
2288 ProcItinResources.clearResources();
Brendon Cahoon254f8892016-07-29 16:44:44 +00002289 for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
2290 checkCycle <= LastCycle; checkCycle += II) {
2291 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
2292
2293 for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(),
2294 E = cycleInstrs.end();
2295 I != E; ++I) {
2296 if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
2297 continue;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00002298 assert(ProcItinResources.canReserveResources(*(*I)->getInstr()) &&
Brendon Cahoon254f8892016-07-29 16:44:44 +00002299 "These instructions have already been scheduled.");
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00002300 ProcItinResources.reserveResources(*(*I)->getInstr());
Brendon Cahoon254f8892016-07-29 16:44:44 +00002301 }
2302 }
2303 if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00002304 ProcItinResources.canReserveResources(*SU->getInstr())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002305 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00002306 dbgs() << "\tinsert at cycle " << curCycle << " ";
2307 SU->getInstr()->dump();
2308 });
2309
2310 ScheduledInstrs[curCycle].push_back(SU);
2311 InstrToCycle.insert(std::make_pair(SU, curCycle));
2312 if (curCycle > LastCycle)
2313 LastCycle = curCycle;
2314 if (curCycle < FirstCycle)
2315 FirstCycle = curCycle;
2316 return true;
2317 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002318 LLVM_DEBUG({
Brendon Cahoon254f8892016-07-29 16:44:44 +00002319 dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
2320 SU->getInstr()->dump();
2321 });
2322 }
2323 return false;
2324}
2325
2326// Return the cycle of the earliest scheduled instruction in the chain.
2327int SMSchedule::earliestCycleInChain(const SDep &Dep) {
2328 SmallPtrSet<SUnit *, 8> Visited;
2329 SmallVector<SDep, 8> Worklist;
2330 Worklist.push_back(Dep);
2331 int EarlyCycle = INT_MAX;
2332 while (!Worklist.empty()) {
2333 const SDep &Cur = Worklist.pop_back_val();
2334 SUnit *PrevSU = Cur.getSUnit();
2335 if (Visited.count(PrevSU))
2336 continue;
2337 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
2338 if (it == InstrToCycle.end())
2339 continue;
2340 EarlyCycle = std::min(EarlyCycle, it->second);
2341 for (const auto &PI : PrevSU->Preds)
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00002342 if (PI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
Brendon Cahoon254f8892016-07-29 16:44:44 +00002343 Worklist.push_back(PI);
2344 Visited.insert(PrevSU);
2345 }
2346 return EarlyCycle;
2347}
2348
2349// Return the cycle of the latest scheduled instruction in the chain.
2350int SMSchedule::latestCycleInChain(const SDep &Dep) {
2351 SmallPtrSet<SUnit *, 8> Visited;
2352 SmallVector<SDep, 8> Worklist;
2353 Worklist.push_back(Dep);
2354 int LateCycle = INT_MIN;
2355 while (!Worklist.empty()) {
2356 const SDep &Cur = Worklist.pop_back_val();
2357 SUnit *SuccSU = Cur.getSUnit();
2358 if (Visited.count(SuccSU))
2359 continue;
2360 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
2361 if (it == InstrToCycle.end())
2362 continue;
2363 LateCycle = std::max(LateCycle, it->second);
2364 for (const auto &SI : SuccSU->Succs)
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00002365 if (SI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
Brendon Cahoon254f8892016-07-29 16:44:44 +00002366 Worklist.push_back(SI);
2367 Visited.insert(SuccSU);
2368 }
2369 return LateCycle;
2370}
2371
2372/// If an instruction has a use that spans multiple iterations, then
2373/// return true. These instructions are characterized by having a back-ege
2374/// to a Phi, which contains a reference to another Phi.
2375static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
2376 for (auto &P : SU->Preds)
2377 if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
2378 for (auto &S : P.getSUnit()->Succs)
Krzysztof Parzyszekb9b75b82018-03-26 15:53:23 +00002379 if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
Brendon Cahoon254f8892016-07-29 16:44:44 +00002380 return P.getSUnit();
2381 return nullptr;
2382}
2383
2384/// Compute the scheduling start slot for the instruction. The start slot
2385/// depends on any predecessor or successor nodes scheduled already.
2386void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
2387 int *MinEnd, int *MaxStart, int II,
2388 SwingSchedulerDAG *DAG) {
2389 // Iterate over each instruction that has been scheduled already. The start
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002390 // slot computation depends on whether the previously scheduled instruction
Brendon Cahoon254f8892016-07-29 16:44:44 +00002391 // is a predecessor or successor of the specified instruction.
2392 for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
2393
2394 // Iterate over each instruction in the current cycle.
2395 for (SUnit *I : getInstructions(cycle)) {
2396 // Because we're processing a DAG for the dependences, we recognize
2397 // the back-edge in recurrences by anti dependences.
2398 for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
2399 const SDep &Dep = SU->Preds[i];
2400 if (Dep.getSUnit() == I) {
2401 if (!DAG->isBackedge(SU, Dep)) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00002402 int EarlyStart = cycle + Dep.getLatency() -
Brendon Cahoon254f8892016-07-29 16:44:44 +00002403 DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
2404 *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00002405 if (DAG->isLoopCarriedDep(SU, Dep, false)) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00002406 int End = earliestCycleInChain(Dep) + (II - 1);
2407 *MinEnd = std::min(*MinEnd, End);
2408 }
2409 } else {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00002410 int LateStart = cycle - Dep.getLatency() +
Brendon Cahoon254f8892016-07-29 16:44:44 +00002411 DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
2412 *MinLateStart = std::min(*MinLateStart, LateStart);
2413 }
2414 }
2415 // For instruction that requires multiple iterations, make sure that
2416 // the dependent instruction is not scheduled past the definition.
2417 SUnit *BE = multipleIterations(I, DAG);
2418 if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
2419 !SU->isPred(I))
2420 *MinLateStart = std::min(*MinLateStart, cycle);
2421 }
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00002422 for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00002423 if (SU->Succs[i].getSUnit() == I) {
2424 const SDep &Dep = SU->Succs[i];
2425 if (!DAG->isBackedge(SU, Dep)) {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00002426 int LateStart = cycle - Dep.getLatency() +
Brendon Cahoon254f8892016-07-29 16:44:44 +00002427 DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
2428 *MinLateStart = std::min(*MinLateStart, LateStart);
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00002429 if (DAG->isLoopCarriedDep(SU, Dep)) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00002430 int Start = latestCycleInChain(Dep) + 1 - II;
2431 *MaxStart = std::max(*MaxStart, Start);
2432 }
2433 } else {
Krzysztof Parzyszekc715a5d2018-03-21 16:39:11 +00002434 int EarlyStart = cycle + Dep.getLatency() -
Brendon Cahoon254f8892016-07-29 16:44:44 +00002435 DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
2436 *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
2437 }
2438 }
Krzysztof Parzyszeka2122042018-03-26 16:33:16 +00002439 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002440 }
2441 }
2442}
2443
2444/// Order the instructions within a cycle so that the definitions occur
2445/// before the uses. Returns true if the instruction is added to the start
2446/// of the list, or false if added to the end.
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00002447void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
Brendon Cahoon254f8892016-07-29 16:44:44 +00002448 std::deque<SUnit *> &Insts) {
2449 MachineInstr *MI = SU->getInstr();
2450 bool OrderBeforeUse = false;
2451 bool OrderAfterDef = false;
2452 bool OrderBeforeDef = false;
2453 unsigned MoveDef = 0;
2454 unsigned MoveUse = 0;
2455 int StageInst1 = stageScheduled(SU);
2456
2457 unsigned Pos = 0;
2458 for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
2459 ++I, ++Pos) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00002460 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
2461 MachineOperand &MO = MI->getOperand(i);
Daniel Sanders2bea69b2019-08-01 23:27:28 +00002462 if (!MO.isReg() || !Register::isVirtualRegister(MO.getReg()))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002463 continue;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00002464
Daniel Sanders0c476112019-08-15 19:22:08 +00002465 Register Reg = MO.getReg();
Brendon Cahoon254f8892016-07-29 16:44:44 +00002466 unsigned BasePos, OffsetPos;
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +00002467 if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002468 if (MI->getOperand(BasePos).getReg() == Reg)
2469 if (unsigned NewReg = SSD->getInstrBaseReg(SU))
2470 Reg = NewReg;
2471 bool Reads, Writes;
2472 std::tie(Reads, Writes) =
2473 (*I)->getInstr()->readsWritesVirtualRegister(Reg);
2474 if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
2475 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00002476 if (MoveUse == 0)
2477 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002478 } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
2479 // Add the instruction after the scheduled instruction.
2480 OrderAfterDef = true;
2481 MoveDef = Pos;
2482 } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
2483 if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
2484 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00002485 if (MoveUse == 0)
2486 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002487 } else {
2488 OrderAfterDef = true;
2489 MoveDef = Pos;
2490 }
2491 } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
2492 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00002493 if (MoveUse == 0)
2494 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002495 if (MoveUse != 0) {
2496 OrderAfterDef = true;
2497 MoveDef = Pos - 1;
2498 }
2499 } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
2500 // Add the instruction before the scheduled instruction.
2501 OrderBeforeUse = true;
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00002502 if (MoveUse == 0)
2503 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002504 } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
2505 isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00002506 if (MoveUse == 0) {
2507 OrderBeforeDef = true;
2508 MoveUse = Pos;
2509 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002510 }
2511 }
2512 // Check for order dependences between instructions. Make sure the source
2513 // is ordered before the destination.
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00002514 for (auto &S : SU->Succs) {
2515 if (S.getSUnit() != *I)
2516 continue;
2517 if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
2518 OrderBeforeUse = true;
2519 if (Pos < MoveUse)
Brendon Cahoon254f8892016-07-29 16:44:44 +00002520 MoveUse = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002521 }
Jinsong Ji95770862019-07-12 01:59:42 +00002522 // We did not handle HW dependences in previous for loop,
2523 // and we normally set Latency = 0 for Anti deps,
2524 // so may have nodes in same cycle with Anti denpendent on HW regs.
2525 else if (S.getKind() == SDep::Anti && stageScheduled(*I) == StageInst1) {
2526 OrderBeforeUse = true;
2527 if ((MoveUse == 0) || (Pos < MoveUse))
2528 MoveUse = Pos;
2529 }
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00002530 }
2531 for (auto &P : SU->Preds) {
2532 if (P.getSUnit() != *I)
2533 continue;
2534 if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
2535 OrderAfterDef = true;
2536 MoveDef = Pos;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002537 }
Krzysztof Parzyszek8e1363d2018-03-26 16:05:55 +00002538 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002539 }
2540
2541 // A circular dependence.
2542 if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
2543 OrderBeforeUse = false;
2544
2545 // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
2546 // to a loop-carried dependence.
2547 if (OrderBeforeDef)
2548 OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
2549
2550 // The uncommon case when the instruction order needs to be updated because
2551 // there is both a use and def.
2552 if (OrderBeforeUse && OrderAfterDef) {
2553 SUnit *UseSU = Insts.at(MoveUse);
2554 SUnit *DefSU = Insts.at(MoveDef);
2555 if (MoveUse > MoveDef) {
2556 Insts.erase(Insts.begin() + MoveUse);
2557 Insts.erase(Insts.begin() + MoveDef);
2558 } else {
2559 Insts.erase(Insts.begin() + MoveDef);
2560 Insts.erase(Insts.begin() + MoveUse);
2561 }
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00002562 orderDependence(SSD, UseSU, Insts);
2563 orderDependence(SSD, SU, Insts);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002564 orderDependence(SSD, DefSU, Insts);
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00002565 return;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002566 }
2567 // Put the new instruction first if there is a use in the list. Otherwise,
2568 // put it at the end of the list.
2569 if (OrderBeforeUse)
2570 Insts.push_front(SU);
2571 else
2572 Insts.push_back(SU);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002573}
2574
2575/// Return true if the scheduled Phi has a loop carried operand.
2576bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
2577 if (!Phi.isPHI())
2578 return false;
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002579 assert(Phi.isPHI() && "Expecting a Phi.");
Brendon Cahoon254f8892016-07-29 16:44:44 +00002580 SUnit *DefSU = SSD->getSUnit(&Phi);
2581 unsigned DefCycle = cycleScheduled(DefSU);
2582 int DefStage = stageScheduled(DefSU);
2583
2584 unsigned InitVal = 0;
2585 unsigned LoopVal = 0;
2586 getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
2587 SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
2588 if (!UseSU)
2589 return true;
2590 if (UseSU->getInstr()->isPHI())
2591 return true;
2592 unsigned LoopCycle = cycleScheduled(UseSU);
2593 int LoopStage = stageScheduled(UseSU);
Simon Pilgrim3d8482a2016-11-14 10:40:23 +00002594 return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002595}
2596
2597/// Return true if the instruction is a definition that is loop carried
2598/// and defines the use on the next iteration.
2599/// v1 = phi(v2, v3)
2600/// (Def) v3 = op v1
2601/// (MO) = v1
2602/// If MO appears before Def, then then v1 and v3 may get assigned to the same
2603/// register.
2604bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
2605 MachineInstr *Def, MachineOperand &MO) {
2606 if (!MO.isReg())
2607 return false;
2608 if (Def->isPHI())
2609 return false;
2610 MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
2611 if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
2612 return false;
2613 if (!isLoopCarried(SSD, *Phi))
2614 return false;
2615 unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
2616 for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
2617 MachineOperand &DMO = Def->getOperand(i);
2618 if (!DMO.isReg() || !DMO.isDef())
2619 continue;
2620 if (DMO.getReg() == LoopReg)
2621 return true;
2622 }
2623 return false;
2624}
2625
2626// Check if the generated schedule is valid. This function checks if
2627// an instruction that uses a physical register is scheduled in a
2628// different stage than the definition. The pipeliner does not handle
2629// physical register values that may cross a basic block boundary.
2630bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
Brendon Cahoon254f8892016-07-29 16:44:44 +00002631 for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
2632 SUnit &SU = SSD->SUnits[i];
2633 if (!SU.hasPhysRegDefs)
2634 continue;
2635 int StageDef = stageScheduled(&SU);
2636 assert(StageDef != -1 && "Instruction should have been scheduled.");
2637 for (auto &SI : SU.Succs)
2638 if (SI.isAssignedRegDep())
Daniel Sanders2bea69b2019-08-01 23:27:28 +00002639 if (Register::isPhysicalRegister(SI.getReg()))
Brendon Cahoon254f8892016-07-29 16:44:44 +00002640 if (stageScheduled(SI.getSUnit()) != StageDef)
2641 return false;
2642 }
2643 return true;
2644}
2645
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00002646/// A property of the node order in swing-modulo-scheduling is
2647/// that for nodes outside circuits the following holds:
2648/// none of them is scheduled after both a successor and a
2649/// predecessor.
2650/// The method below checks whether the property is met.
2651/// If not, debug information is printed and statistics information updated.
2652/// Note that we do not use an assert statement.
2653/// The reason is that although an invalid node oder may prevent
2654/// the pipeliner from finding a pipelined schedule for arbitrary II,
2655/// it does not lead to the generation of incorrect code.
2656void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
2657
2658 // a sorted vector that maps each SUnit to its index in the NodeOrder
2659 typedef std::pair<SUnit *, unsigned> UnitIndex;
2660 std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
2661
2662 for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
2663 Indices.push_back(std::make_pair(NodeOrder[i], i));
2664
2665 auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
2666 return std::get<0>(i1) < std::get<0>(i2);
2667 };
2668
2669 // sort, so that we can perform a binary search
Fangrui Song0cac7262018-09-27 02:13:45 +00002670 llvm::sort(Indices, CompareKey);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00002671
2672 bool Valid = true;
David L Kreitzerfebf70a2018-03-16 21:21:23 +00002673 (void)Valid;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00002674 // for each SUnit in the NodeOrder, check whether
2675 // it appears after both a successor and a predecessor
2676 // of the SUnit. If this is the case, and the SUnit
2677 // is not part of circuit, then the NodeOrder is not
2678 // valid.
2679 for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
2680 SUnit *SU = NodeOrder[i];
2681 unsigned Index = i;
2682
2683 bool PredBefore = false;
2684 bool SuccBefore = false;
2685
2686 SUnit *Succ;
2687 SUnit *Pred;
David L Kreitzerfebf70a2018-03-16 21:21:23 +00002688 (void)Succ;
2689 (void)Pred;
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00002690
2691 for (SDep &PredEdge : SU->Preds) {
2692 SUnit *PredSU = PredEdge.getSUnit();
Fangrui Songdc8de602019-06-21 05:40:31 +00002693 unsigned PredIndex = std::get<1>(
2694 *llvm::lower_bound(Indices, std::make_pair(PredSU, 0), CompareKey));
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00002695 if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
2696 PredBefore = true;
2697 Pred = PredSU;
2698 break;
2699 }
2700 }
2701
2702 for (SDep &SuccEdge : SU->Succs) {
2703 SUnit *SuccSU = SuccEdge.getSUnit();
Jinsong Ji1c884452019-06-13 21:51:12 +00002704 // Do not process a boundary node, it was not included in NodeOrder,
2705 // hence not in Indices either, call to std::lower_bound() below will
2706 // return Indices.end().
2707 if (SuccSU->isBoundaryNode())
2708 continue;
Fangrui Songdc8de602019-06-21 05:40:31 +00002709 unsigned SuccIndex = std::get<1>(
2710 *llvm::lower_bound(Indices, std::make_pair(SuccSU, 0), CompareKey));
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00002711 if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
2712 SuccBefore = true;
2713 Succ = SuccSU;
2714 break;
2715 }
2716 }
2717
2718 if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
2719 // instructions in circuits are allowed to be scheduled
2720 // after both a successor and predecessor.
Fangrui Songdc8de602019-06-21 05:40:31 +00002721 bool InCircuit = llvm::any_of(
2722 Circuits, [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00002723 if (InCircuit)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002724 LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00002725 else {
2726 Valid = false;
2727 NumNodeOrderIssues++;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002728 LLVM_DEBUG(dbgs() << "Predecessor ";);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00002729 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002730 LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
2731 << " are scheduled before node " << SU->NodeNum
2732 << "\n";);
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00002733 }
2734 }
2735
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002736 LLVM_DEBUG({
Roorda, Jan-Willem4b8bcf02018-03-07 18:53:36 +00002737 if (!Valid)
2738 dbgs() << "Invalid node order found!\n";
2739 });
2740}
2741
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00002742/// Attempt to fix the degenerate cases when the instruction serialization
2743/// causes the register lifetimes to overlap. For example,
2744/// p' = store_pi(p, b)
2745/// = load p, offset
2746/// In this case p and p' overlap, which means that two registers are needed.
2747/// Instead, this function changes the load to use p' and updates the offset.
2748void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
2749 unsigned OverlapReg = 0;
2750 unsigned NewBaseReg = 0;
2751 for (SUnit *SU : Instrs) {
2752 MachineInstr *MI = SU->getInstr();
2753 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
2754 const MachineOperand &MO = MI->getOperand(i);
2755 // Look for an instruction that uses p. The instruction occurs in the
2756 // same cycle but occurs later in the serialized order.
2757 if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
2758 // Check that the instruction appears in the InstrChanges structure,
2759 // which contains instructions that can have the offset updated.
2760 DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
2761 InstrChanges.find(SU);
2762 if (It != InstrChanges.end()) {
2763 unsigned BasePos, OffsetPos;
2764 // Update the base register and adjust the offset.
2765 if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
Krzysztof Parzyszek12bdcab2017-10-11 15:59:51 +00002766 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2767 NewMI->getOperand(BasePos).setReg(NewBaseReg);
2768 int64_t NewOffset =
2769 MI->getOperand(OffsetPos).getImm() - It->second.second;
2770 NewMI->getOperand(OffsetPos).setImm(NewOffset);
2771 SU->setInstr(NewMI);
2772 MISUnitMap[NewMI] = SU;
James Molloy790a7792019-08-30 18:49:50 +00002773 NewMIs[MI] = NewMI;
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00002774 }
2775 }
2776 OverlapReg = 0;
2777 NewBaseReg = 0;
2778 break;
2779 }
2780 // Look for an instruction of the form p' = op(p), which uses and defines
2781 // two virtual registers that get allocated to the same physical register.
2782 unsigned TiedUseIdx = 0;
2783 if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
2784 // OverlapReg is p in the example above.
2785 OverlapReg = MI->getOperand(TiedUseIdx).getReg();
2786 // NewBaseReg is p' in the example above.
2787 NewBaseReg = MI->getOperand(i).getReg();
2788 break;
2789 }
2790 }
2791 }
2792}
2793
Brendon Cahoon254f8892016-07-29 16:44:44 +00002794/// After the schedule has been formed, call this function to combine
2795/// the instructions from the different stages/cycles. That is, this
2796/// function creates a schedule that represents a single iteration.
2797void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
2798 // Move all instructions to the first stage from later stages.
2799 for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
2800 for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
2801 ++stage) {
2802 std::deque<SUnit *> &cycleInstrs =
2803 ScheduledInstrs[cycle + (stage * InitiationInterval)];
2804 for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
2805 E = cycleInstrs.rend();
2806 I != E; ++I)
2807 ScheduledInstrs[cycle].push_front(*I);
2808 }
2809 }
Brendon Cahoon254f8892016-07-29 16:44:44 +00002810
2811 // Erase all the elements in the later stages. Only one iteration should
2812 // remain in the scheduled list, and it contains all the instructions.
2813 for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
2814 ScheduledInstrs.erase(cycle);
2815
2816 // Change the registers in instruction as specified in the InstrChanges
2817 // map. We need to use the new registers to create the correct order.
2818 for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
2819 SUnit *SU = &SSD->SUnits[i];
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00002820 SSD->applyInstrChange(SU->getInstr(), *this);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002821 }
2822
2823 // Reorder the instructions in each cycle to fix and improve the
2824 // generated code.
2825 for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
2826 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00002827 std::deque<SUnit *> newOrderPhi;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002828 for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
2829 SUnit *SU = cycleInstrs[i];
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00002830 if (SU->getInstr()->isPHI())
2831 newOrderPhi.push_back(SU);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002832 }
2833 std::deque<SUnit *> newOrderI;
Brendon Cahoon254f8892016-07-29 16:44:44 +00002834 for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
2835 SUnit *SU = cycleInstrs[i];
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00002836 if (!SU->getInstr()->isPHI())
Brendon Cahoon254f8892016-07-29 16:44:44 +00002837 orderDependence(SSD, SU, newOrderI);
2838 }
2839 // Replace the old order with the new order.
Krzysztof Parzyszekf13bbf12018-03-26 16:23:29 +00002840 cycleInstrs.swap(newOrderPhi);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002841 cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
Krzysztof Parzyszek8f174dd2017-10-11 15:51:44 +00002842 SSD->fixupRegisterOverlaps(cycleInstrs);
Brendon Cahoon254f8892016-07-29 16:44:44 +00002843 }
2844
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002845 LLVM_DEBUG(dump(););
Brendon Cahoon254f8892016-07-29 16:44:44 +00002846}
2847
Adrian Prantlfa2e3582019-01-14 17:24:11 +00002848void NodeSet::print(raw_ostream &os) const {
2849 os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
2850 << " depth " << MaxDepth << " col " << Colocate << "\n";
2851 for (const auto &I : Nodes)
2852 os << " SU(" << I->NodeNum << ") " << *(I->getInstr());
2853 os << "\n";
2854}
2855
Aaron Ballman615eb472017-10-15 14:32:27 +00002856#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Brendon Cahoon254f8892016-07-29 16:44:44 +00002857/// Print the schedule information to the given output.
2858void SMSchedule::print(raw_ostream &os) const {
2859 // Iterate over each cycle.
2860 for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
2861 // Iterate over each instruction in the cycle.
2862 const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
2863 for (SUnit *CI : cycleInstrs->second) {
2864 os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
2865 os << "(" << CI->NodeNum << ") ";
2866 CI->getInstr()->print(os);
2867 os << "\n";
2868 }
2869 }
2870}
2871
2872/// Utility function used for debugging to print the schedule.
Matthias Braun8c209aa2017-01-28 02:02:38 +00002873LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
Adrian Prantlfa2e3582019-01-14 17:24:11 +00002874LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
2875
Matthias Braun8c209aa2017-01-28 02:02:38 +00002876#endif
Adrian Prantlfa2e3582019-01-14 17:24:11 +00002877
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00002878void ResourceManager::initProcResourceVectors(
2879 const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
2880 unsigned ProcResourceID = 0;
Adrian Prantlfa2e3582019-01-14 17:24:11 +00002881
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00002882 // We currently limit the resource kinds to 64 and below so that we can use
2883 // uint64_t for Masks
2884 assert(SM.getNumProcResourceKinds() < 64 &&
2885 "Too many kinds of resources, unsupported");
2886 // Create a unique bitmask for every processor resource unit.
2887 // Skip resource at index 0, since it always references 'InvalidUnit'.
2888 Masks.resize(SM.getNumProcResourceKinds());
2889 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
2890 const MCProcResourceDesc &Desc = *SM.getProcResource(I);
2891 if (Desc.SubUnitsIdxBegin)
2892 continue;
2893 Masks[I] = 1ULL << ProcResourceID;
2894 ProcResourceID++;
2895 }
2896 // Create a unique bitmask for every processor resource group.
2897 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
2898 const MCProcResourceDesc &Desc = *SM.getProcResource(I);
2899 if (!Desc.SubUnitsIdxBegin)
2900 continue;
2901 Masks[I] = 1ULL << ProcResourceID;
2902 for (unsigned U = 0; U < Desc.NumUnits; ++U)
2903 Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
2904 ProcResourceID++;
2905 }
2906 LLVM_DEBUG({
Jinsong Jiba438402019-06-18 20:24:49 +00002907 if (SwpShowResMask) {
2908 dbgs() << "ProcResourceDesc:\n";
2909 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
2910 const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
2911 dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
2912 ProcResource->Name, I, Masks[I],
2913 ProcResource->NumUnits);
2914 }
2915 dbgs() << " -----------------\n";
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00002916 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00002917 });
2918}
2919
2920bool ResourceManager::canReserveResources(const MCInstrDesc *MID) const {
2921
Jinsong Jiba438402019-06-18 20:24:49 +00002922 LLVM_DEBUG({
2923 if (SwpDebugResource)
2924 dbgs() << "canReserveResources:\n";
2925 });
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00002926 if (UseDFA)
2927 return DFAResources->canReserveResources(MID);
2928
2929 unsigned InsnClass = MID->getSchedClass();
2930 const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
2931 if (!SCDesc->isValid()) {
2932 LLVM_DEBUG({
2933 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
2934 dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
2935 });
2936 return true;
2937 }
2938
2939 const MCWriteProcResEntry *I = STI->getWriteProcResBegin(SCDesc);
2940 const MCWriteProcResEntry *E = STI->getWriteProcResEnd(SCDesc);
2941 for (; I != E; ++I) {
2942 if (!I->Cycles)
2943 continue;
2944 const MCProcResourceDesc *ProcResource =
2945 SM.getProcResource(I->ProcResourceIdx);
2946 unsigned NumUnits = ProcResource->NumUnits;
2947 LLVM_DEBUG({
Jinsong Jiba438402019-06-18 20:24:49 +00002948 if (SwpDebugResource)
2949 dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
2950 ProcResource->Name, I->ProcResourceIdx,
2951 ProcResourceCount[I->ProcResourceIdx], NumUnits,
2952 I->Cycles);
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00002953 });
2954 if (ProcResourceCount[I->ProcResourceIdx] >= NumUnits)
2955 return false;
2956 }
Jinsong Jiba438402019-06-18 20:24:49 +00002957 LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return true\n\n";);
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00002958 return true;
2959}
2960
2961void ResourceManager::reserveResources(const MCInstrDesc *MID) {
Jinsong Jiba438402019-06-18 20:24:49 +00002962 LLVM_DEBUG({
2963 if (SwpDebugResource)
2964 dbgs() << "reserveResources:\n";
2965 });
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00002966 if (UseDFA)
2967 return DFAResources->reserveResources(MID);
2968
2969 unsigned InsnClass = MID->getSchedClass();
2970 const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
2971 if (!SCDesc->isValid()) {
2972 LLVM_DEBUG({
2973 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
2974 dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
2975 });
2976 return;
2977 }
2978 for (const MCWriteProcResEntry &PRE :
2979 make_range(STI->getWriteProcResBegin(SCDesc),
2980 STI->getWriteProcResEnd(SCDesc))) {
2981 if (!PRE.Cycles)
2982 continue;
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00002983 ++ProcResourceCount[PRE.ProcResourceIdx];
2984 LLVM_DEBUG({
Jinsong Jiba438402019-06-18 20:24:49 +00002985 if (SwpDebugResource) {
2986 const MCProcResourceDesc *ProcResource =
2987 SM.getProcResource(PRE.ProcResourceIdx);
2988 dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
2989 ProcResource->Name, PRE.ProcResourceIdx,
2990 ProcResourceCount[PRE.ProcResourceIdx],
2991 ProcResource->NumUnits, PRE.Cycles);
2992 }
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00002993 });
2994 }
Jinsong Jiba438402019-06-18 20:24:49 +00002995 LLVM_DEBUG({
2996 if (SwpDebugResource)
2997 dbgs() << "reserveResources: done!\n\n";
2998 });
Jinsong Jif6cb3bc2019-05-29 03:02:59 +00002999}
3000
3001bool ResourceManager::canReserveResources(const MachineInstr &MI) const {
3002 return canReserveResources(&MI.getDesc());
3003}
3004
3005void ResourceManager::reserveResources(const MachineInstr &MI) {
3006 return reserveResources(&MI.getDesc());
3007}
3008
3009void ResourceManager::clearResources() {
3010 if (UseDFA)
3011 return DFAResources->clearResources();
3012 std::fill(ProcResourceCount.begin(), ProcResourceCount.end(), 0);
3013}