1//===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
10//
11// 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
32#include "llvm/CodeGen/MachinePipeliner.h"
33#include "llvm/ADT/ArrayRef.h"
34#include "llvm/ADT/BitVector.h"
35#include "llvm/ADT/DenseMap.h"
36#include "llvm/ADT/PriorityQueue.h"
37#include "llvm/ADT/STLExtras.h"
38#include "llvm/ADT/SetOperations.h"
39#include "llvm/ADT/SetVector.h"
40#include "llvm/ADT/SmallPtrSet.h"
41#include "llvm/ADT/SmallSet.h"
42#include "llvm/ADT/SmallVector.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/ADT/iterator_range.h"
45#include "llvm/Analysis/AliasAnalysis.h"
46#include "llvm/Analysis/MemoryLocation.h"
47#include "llvm/Analysis/OptimizationRemarkEmitter.h"
48#include "llvm/Analysis/ValueTracking.h"
49#include "llvm/CodeGen/DFAPacketizer.h"
50#include "llvm/CodeGen/LiveIntervals.h"
51#include "llvm/CodeGen/MachineBasicBlock.h"
52#include "llvm/CodeGen/MachineDominators.h"
53#include "llvm/CodeGen/MachineFunction.h"
54#include "llvm/CodeGen/MachineFunctionPass.h"
55#include "llvm/CodeGen/MachineInstr.h"
56#include "llvm/CodeGen/MachineInstrBuilder.h"
57#include "llvm/CodeGen/MachineLoopInfo.h"
58#include "llvm/CodeGen/MachineMemOperand.h"
59#include "llvm/CodeGen/MachineOperand.h"
60#include "llvm/CodeGen/MachineRegisterInfo.h"
61#include "llvm/CodeGen/ModuloSchedule.h"
62#include "llvm/CodeGen/Register.h"
63#include "llvm/CodeGen/RegisterClassInfo.h"
64#include "llvm/CodeGen/RegisterPressure.h"
65#include "llvm/CodeGen/ScheduleDAG.h"
66#include "llvm/CodeGen/ScheduleDAGMutation.h"
67#include "llvm/CodeGen/TargetInstrInfo.h"
68#include "llvm/CodeGen/TargetOpcodes.h"
69#include "llvm/CodeGen/TargetPassConfig.h"
70#include "llvm/CodeGen/TargetRegisterInfo.h"
71#include "llvm/CodeGen/TargetSubtargetInfo.h"
72#include "llvm/Config/llvm-config.h"
73#include "llvm/IR/Attributes.h"
74#include "llvm/IR/Function.h"
75#include "llvm/InitializePasses.h"
76#include "llvm/MC/LaneBitmask.h"
77#include "llvm/MC/MCInstrDesc.h"
78#include "llvm/MC/MCInstrItineraries.h"
79#include "llvm/Pass.h"
80#include "llvm/Support/CommandLine.h"
81#include "llvm/Support/Compiler.h"
82#include "llvm/Support/Debug.h"
83#include "llvm/Support/raw_ostream.h"
84#include <algorithm>
85#include <cassert>
86#include <climits>
87#include <cstdint>
88#include <deque>
89#include <functional>
90#include <iomanip>
91#include <iterator>
92#include <map>
93#include <memory>
94#include <sstream>
95#include <tuple>
96#include <utility>
97#include <vector>
98
99using namespace llvm;
100
101#define DEBUG_TYPE "pipeliner"
102
103STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
104STATISTIC(NumPipelined, "Number of loops software pipelined");
105STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
106STATISTIC(NumFailBranch, "Pipeliner abort due to unknown branch");
107STATISTIC(NumFailLoop, "Pipeliner abort due to unsupported loop");
108STATISTIC(NumFailPreheader, "Pipeliner abort due to missing preheader");
109STATISTIC(NumFailLargeMaxMII, "Pipeliner abort due to MaxMII too large");
110STATISTIC(NumFailZeroMII, "Pipeliner abort due to zero MII");
111STATISTIC(NumFailNoSchedule, "Pipeliner abort due to no schedule found");
112STATISTIC(NumFailZeroStage, "Pipeliner abort due to zero stage");
113STATISTIC(NumFailLargeMaxStage, "Pipeliner abort due to too many stages");
114STATISTIC(NumFailTooManyStores, "Pipeliner abort due to too many stores");
115
116/// A command line option to turn software pipelining on or off.
117static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(Val: true),
118 cl::desc("Enable Software Pipelining"));
119
120/// A command line option to enable SWP at -Os.
121static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
122 cl::desc("Enable SWP at Os."), cl::Hidden,
123 cl::init(Val: false));
124
125/// A command line argument to limit minimum initial interval for pipelining.
126static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
127 cl::desc("Size limit for the MII."),
128 cl::Hidden, cl::init(Val: 27));
129
130/// A command line argument to force pipeliner to use specified initial
131/// interval.
132static cl::opt<int> SwpForceII("pipeliner-force-ii",
133 cl::desc("Force pipeliner to use specified II."),
134 cl::Hidden, cl::init(Val: -1));
135
136/// A command line argument to limit the number of stages in the pipeline.
137static cl::opt<int>
138 SwpMaxStages("pipeliner-max-stages",
139 cl::desc("Maximum stages allowed in the generated scheduled."),
140 cl::Hidden, cl::init(Val: 3));
141
142/// A command line option to disable the pruning of chain dependences due to
143/// an unrelated Phi.
144static cl::opt<bool>
145 SwpPruneDeps("pipeliner-prune-deps",
146 cl::desc("Prune dependences between unrelated Phi nodes."),
147 cl::Hidden, cl::init(Val: true));
148
149/// A command line option to disable the pruning of loop carried order
150/// dependences.
151static cl::opt<bool>
152 SwpPruneLoopCarried("pipeliner-prune-loop-carried",
153 cl::desc("Prune loop carried order dependences."),
154 cl::Hidden, cl::init(Val: true));
155
156#ifndef NDEBUG
157static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
158#endif
159
160static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
161 cl::ReallyHidden,
162 cl::desc("Ignore RecMII"));
163
164static cl::opt<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden,
165 cl::init(Val: false));
166static cl::opt<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden,
167 cl::init(Val: false));
168
169static cl::opt<bool> EmitTestAnnotations(
170 "pipeliner-annotate-for-testing", cl::Hidden, cl::init(Val: false),
171 cl::desc("Instead of emitting the pipelined code, annotate instructions "
172 "with the generated schedule for feeding into the "
173 "-modulo-schedule-test pass"));
174
175static cl::opt<bool> ExperimentalCodeGen(
176 "pipeliner-experimental-cg", cl::Hidden, cl::init(Val: false),
177 cl::desc(
178 "Use the experimental peeling code generator for software pipelining"));
179
180static cl::opt<int> SwpIISearchRange("pipeliner-ii-search-range",
181 cl::desc("Range to search for II"),
182 cl::Hidden, cl::init(Val: 10));
183
184static cl::opt<bool>
185 LimitRegPressure("pipeliner-register-pressure", cl::Hidden, cl::init(Val: false),
186 cl::desc("Limit register pressure of scheduled loop"));
187
188static cl::opt<int>
189 RegPressureMargin("pipeliner-register-pressure-margin", cl::Hidden,
190 cl::init(Val: 5),
191 cl::desc("Margin representing the unused percentage of "
192 "the register pressure limit"));
193
194static cl::opt<bool>
195 MVECodeGen("pipeliner-mve-cg", cl::Hidden, cl::init(Val: false),
196 cl::desc("Use the MVE code generator for software pipelining"));
197
198/// A command line argument to limit the number of store instructions in the
199/// target basic block.
200static cl::opt<unsigned> SwpMaxNumStores(
201 "pipeliner-max-num-stores",
202 cl::desc("Maximum number of stores allwed in the target loop."), cl::Hidden,
203 cl::init(Val: 200));
204
205// A command line option to enable the CopyToPhi DAG mutation.
206cl::opt<bool>
207 llvm::SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
208 cl::init(Val: true),
209 cl::desc("Enable CopyToPhi DAG Mutation"));
210
211/// A command line argument to force pipeliner to use specified issue
212/// width.
213cl::opt<int> llvm::SwpForceIssueWidth(
214 "pipeliner-force-issue-width",
215 cl::desc("Force pipeliner to use specified issue width."), cl::Hidden,
216 cl::init(Val: -1));
217
218/// A command line argument to set the window scheduling option.
219static cl::opt<WindowSchedulingFlag> WindowSchedulingOption(
220 "window-sched", cl::Hidden, cl::init(Val: WindowSchedulingFlag::WS_On),
221 cl::desc("Set how to use window scheduling algorithm."),
222 cl::values(clEnumValN(WindowSchedulingFlag::WS_Off, "off",
223 "Turn off window algorithm."),
224 clEnumValN(WindowSchedulingFlag::WS_On, "on",
225 "Use window algorithm after SMS algorithm fails."),
226 clEnumValN(WindowSchedulingFlag::WS_Force, "force",
227 "Use window algorithm instead of SMS algorithm.")));
228
229unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
230char MachinePipeliner::ID = 0;
231#ifndef NDEBUG
232int MachinePipeliner::NumTries = 0;
233#endif
234char &llvm::MachinePipelinerID = MachinePipeliner::ID;
235
236INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
237 "Modulo Software Pipelining", false, false)
238INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
239INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
240INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
241INITIALIZE_PASS_DEPENDENCY(LiveIntervalsWrapperPass)
242INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
243 "Modulo Software Pipelining", false, false)
244
245namespace {
246
247/// This class holds an SUnit corresponding to a memory operation and other
248/// information related to the instruction.
249struct SUnitWithMemInfo {
250 SUnit *SU;
251 SmallVector<const Value *, 2> UnderlyingObjs;
252
253 /// The value of a memory operand.
254 const Value *MemOpValue = nullptr;
255
256 /// The offset of a memory operand.
257 int64_t MemOpOffset = 0;
258
259 AAMDNodes AATags;
260
261 /// True if all the underlying objects are identified.
262 bool IsAllIdentified = false;
263
264 SUnitWithMemInfo(SUnit *SU);
265
266 bool isTriviallyDisjoint(const SUnitWithMemInfo &Other) const;
267
268 bool isUnknown() const { return MemOpValue == nullptr; }
269
270private:
271 bool getUnderlyingObjects();
272};
273
274/// Add loop-carried chain dependencies. This class handles the same type of
275/// dependencies added by `ScheduleDAGInstrs::buildSchedGraph`, but takes into
276/// account dependencies across iterations.
277class LoopCarriedOrderDepsTracker {
278 // Type of instruction that is relevant to order-dependencies
279 enum class InstrTag {
280 Barrier = 0, ///< A barrier event instruction.
281 LoadOrStore = 1, ///< An instruction that may load or store memory, but is
282 ///< not a barrier event.
283 FPExceptions = 2, ///< An instruction that does not match above, but may
284 ///< raise floatin-point exceptions.
285 };
286
287 struct TaggedSUnit : PointerIntPair<SUnit *, 2> {
288 TaggedSUnit(SUnit *SU, InstrTag Tag)
289 : PointerIntPair<SUnit *, 2>(SU, unsigned(Tag)) {}
290
291 InstrTag getTag() const { return InstrTag(getInt()); }
292 };
293
294 /// Holds instructions that may form loop-carried order-dependencies, but not
295 /// global barriers.
296 struct NoBarrierInstsChunk {
297 SmallVector<SUnitWithMemInfo, 4> Loads;
298 SmallVector<SUnitWithMemInfo, 4> Stores;
299 SmallVector<SUnitWithMemInfo, 1> FPExceptions;
300
301 void append(SUnit *SU);
302 };
303
304 SwingSchedulerDAG *DAG;
305 BatchAAResults *BAA;
306 std::vector<SUnit> &SUnits;
307
308 /// The size of SUnits, for convenience.
309 const unsigned N;
310
311 /// Loop-carried Edges.
312 std::vector<BitVector> LoopCarried;
313
314 /// Instructions related to chain dependencies. They are one of the
315 /// following:
316 ///
317 /// 1. Barrier event.
318 /// 2. Load, but neither a barrier event, invariant load, nor may load trap
319 /// value.
320 /// 3. Store, but not a barrier event.
321 /// 4. None of them, but may raise floating-point exceptions.
322 ///
323 /// This is used when analyzing loop-carried dependencies that access global
324 /// barrier instructions.
325 std::vector<TaggedSUnit> TaggedSUnits;
326
327 const TargetInstrInfo *TII = nullptr;
328 const TargetRegisterInfo *TRI = nullptr;
329
330public:
331 LoopCarriedOrderDepsTracker(SwingSchedulerDAG *SSD, BatchAAResults *BAA,
332 const TargetInstrInfo *TII,
333 const TargetRegisterInfo *TRI);
334
335 /// The main function to compute loop-carried order-dependencies.
336 void computeDependencies();
337
338 const BitVector &getLoopCarried(unsigned Idx) const {
339 return LoopCarried[Idx];
340 }
341
342private:
343 /// Tags to \p SU if the instruction may affect the order-dependencies.
344 std::optional<InstrTag> getInstrTag(SUnit *SU) const;
345
346 void addLoopCarriedDepenenciesForChunks(const NoBarrierInstsChunk &From,
347 const NoBarrierInstsChunk &To);
348
349 /// Add a loop-carried order dependency between \p Src and \p Dst if we
350 /// cannot prove they are independent.
351 void addDependenciesBetweenSUs(const SUnitWithMemInfo &Src,
352 const SUnitWithMemInfo &Dst);
353
354 void computeDependenciesAux();
355
356 void setLoopCarriedDep(const SUnit *Src, const SUnit *Dst) {
357 LoopCarried[Src->NodeNum].set(Dst->NodeNum);
358 }
359};
360
361} // end anonymous namespace
362
363/// The "main" function for implementing Swing Modulo Scheduling.
364bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
365 if (skipFunction(F: mf.getFunction()))
366 return false;
367
368 if (!EnableSWP)
369 return false;
370
371 if (mf.getFunction().getAttributes().hasFnAttr(Kind: Attribute::OptimizeForSize) &&
372 !EnableSWPOptSize.getPosition())
373 return false;
374
375 if (!mf.getSubtarget().enableMachinePipeliner())
376 return false;
377
378 // Cannot pipeline loops without instruction itineraries if we are using
379 // DFA for the pipeliner.
380 if (mf.getSubtarget().useDFAforSMS() &&
381 (!mf.getSubtarget().getInstrItineraryData() ||
382 mf.getSubtarget().getInstrItineraryData()->isEmpty()))
383 return false;
384
385 MF = &mf;
386 MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
387 MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
388 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
389 TII = MF->getSubtarget().getInstrInfo();
390 RegClassInfo.runOnMachineFunction(MF: *MF);
391
392 for (const auto &L : *MLI)
393 scheduleLoop(L&: *L);
394
395 return false;
396}
397
398/// Attempt to perform the SMS algorithm on the specified loop. This function is
399/// the main entry point for the algorithm. The function identifies candidate
400/// loops, calculates the minimum initiation interval, and attempts to schedule
401/// the loop.
402bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
403 bool Changed = false;
404 for (const auto &InnerLoop : L)
405 Changed |= scheduleLoop(L&: *InnerLoop);
406
407#ifndef NDEBUG
408 // Stop trying after reaching the limit (if any).
409 int Limit = SwpLoopLimit;
410 if (Limit >= 0) {
411 if (NumTries >= SwpLoopLimit)
412 return Changed;
413 NumTries++;
414 }
415#endif
416
417 setPragmaPipelineOptions(L);
418 if (!canPipelineLoop(L)) {
419 LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
420 ORE->emit(RemarkBuilder: [&]() {
421 return MachineOptimizationRemarkMissed(DEBUG_TYPE, "canPipelineLoop",
422 L.getStartLoc(), L.getHeader())
423 << "Failed to pipeline loop";
424 });
425
426 LI.LoopPipelinerInfo.reset();
427 return Changed;
428 }
429
430 ++NumTrytoPipeline;
431 if (useSwingModuloScheduler())
432 Changed = swingModuloScheduler(L);
433
434 if (useWindowScheduler(Changed))
435 Changed = runWindowScheduler(L);
436
437 LI.LoopPipelinerInfo.reset();
438 return Changed;
439}
440
441void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) {
442 // Reset the pragma for the next loop in iteration.
443 disabledByPragma = false;
444 II_setByPragma = 0;
445
446 MachineBasicBlock *LBLK = L.getTopBlock();
447
448 if (LBLK == nullptr)
449 return;
450
451 const BasicBlock *BBLK = LBLK->getBasicBlock();
452 if (BBLK == nullptr)
453 return;
454
455 const Instruction *TI = BBLK->getTerminator();
456 if (TI == nullptr)
457 return;
458
459 MDNode *LoopID = TI->getMetadata(KindID: LLVMContext::MD_loop);
460 if (LoopID == nullptr)
461 return;
462
463 assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
464 assert(LoopID->getOperand(0) == LoopID && "invalid loop");
465
466 for (const MDOperand &MDO : llvm::drop_begin(RangeOrContainer: LoopID->operands())) {
467 MDNode *MD = dyn_cast<MDNode>(Val: MDO);
468
469 if (MD == nullptr)
470 continue;
471
472 MDString *S = dyn_cast<MDString>(Val: MD->getOperand(I: 0));
473
474 if (S == nullptr)
475 continue;
476
477 if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
478 assert(MD->getNumOperands() == 2 &&
479 "Pipeline initiation interval hint metadata should have two operands.");
480 II_setByPragma =
481 mdconst::extract<ConstantInt>(MD: MD->getOperand(I: 1))->getZExtValue();
482 assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
483 } else if (S->getString() == "llvm.loop.pipeline.disable") {
484 disabledByPragma = true;
485 }
486 }
487}
488
489/// Depth-first search to detect cycles among PHI dependencies.
490/// Returns true if a cycle is detected within the PHI-only subgraph.
491static bool hasPHICycleDFS(
492 unsigned Reg, const DenseMap<unsigned, SmallVector<unsigned, 2>> &PhiDeps,
493 SmallSet<unsigned, 8> &Visited, SmallSet<unsigned, 8> &RecStack) {
494
495 // If Reg is not a PHI-def it cannot contribute to a PHI cycle.
496 auto It = PhiDeps.find(Val: Reg);
497 if (It == PhiDeps.end())
498 return false;
499
500 if (RecStack.count(V: Reg))
501 return true; // backedge.
502 if (Visited.count(V: Reg))
503 return false;
504
505 Visited.insert(V: Reg);
506 RecStack.insert(V: Reg);
507
508 for (unsigned Dep : It->second) {
509 if (hasPHICycleDFS(Reg: Dep, PhiDeps, Visited, RecStack))
510 return true;
511 }
512
513 RecStack.erase(V: Reg);
514 return false;
515}
516
517static bool hasPHICycle(const MachineBasicBlock *LoopHeader,
518 const MachineRegisterInfo &MRI) {
519 DenseMap<unsigned, SmallVector<unsigned, 2>> PhiDeps;
520
521 // Collect PHI nodes and their dependencies.
522 for (const MachineInstr &MI : LoopHeader->phis()) {
523 unsigned DefReg = MI.getOperand(i: 0).getReg();
524 auto Ins = PhiDeps.try_emplace(Key: DefReg).first;
525
526 // PHI operands are (Reg, MBB) pairs starting at index 1.
527 for (unsigned I = 1; I < MI.getNumOperands(); I += 2)
528 Ins->second.push_back(Elt: MI.getOperand(i: I).getReg());
529 }
530
531 // DFS to detect cycles among PHI nodes.
532 SmallSet<unsigned, 8> Visited, RecStack;
533
534 // Start DFS from each PHI-def.
535 for (const auto &KV : PhiDeps) {
536 unsigned Reg = KV.first;
537 if (hasPHICycleDFS(Reg, PhiDeps, Visited, RecStack))
538 return true;
539 }
540
541 return false;
542}
543
544/// Return true if the loop can be software pipelined. The algorithm is
545/// restricted to loops with a single basic block. Make sure that the
546/// branch in the loop can be analyzed.
547bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
548 if (L.getNumBlocks() != 1) {
549 ORE->emit(RemarkBuilder: [&]() {
550 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
551 L.getStartLoc(), L.getHeader())
552 << "Not a single basic block: "
553 << ore::NV("NumBlocks", L.getNumBlocks());
554 });
555 return false;
556 }
557
558 if (hasPHICycle(LoopHeader: L.getHeader(), MRI: MF->getRegInfo())) {
559 LLVM_DEBUG(dbgs() << "Cannot pipeline loop due to PHI cycle\n");
560 return false;
561 }
562
563 if (disabledByPragma) {
564 ORE->emit(RemarkBuilder: [&]() {
565 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
566 L.getStartLoc(), L.getHeader())
567 << "Disabled by Pragma.";
568 });
569 return false;
570 }
571
572 // Check if the branch can't be understood because we can't do pipelining
573 // if that's the case.
574 LI.TBB = nullptr;
575 LI.FBB = nullptr;
576 LI.BrCond.clear();
577 if (TII->analyzeBranch(MBB&: *L.getHeader(), TBB&: LI.TBB, FBB&: LI.FBB, Cond&: LI.BrCond)) {
578 LLVM_DEBUG(dbgs() << "Unable to analyzeBranch, can NOT pipeline Loop\n");
579 NumFailBranch++;
580 ORE->emit(RemarkBuilder: [&]() {
581 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
582 L.getStartLoc(), L.getHeader())
583 << "The branch can't be understood";
584 });
585 return false;
586 }
587
588 LI.LoopInductionVar = nullptr;
589 LI.LoopCompare = nullptr;
590 LI.LoopPipelinerInfo = TII->analyzeLoopForPipelining(LoopBB: L.getTopBlock());
591 if (!LI.LoopPipelinerInfo) {
592 LLVM_DEBUG(dbgs() << "Unable to analyzeLoop, can NOT pipeline Loop\n");
593 NumFailLoop++;
594 ORE->emit(RemarkBuilder: [&]() {
595 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
596 L.getStartLoc(), L.getHeader())
597 << "The loop structure is not supported";
598 });
599 return false;
600 }
601
602 if (!L.getLoopPreheader()) {
603 LLVM_DEBUG(dbgs() << "Preheader not found, can NOT pipeline Loop\n");
604 NumFailPreheader++;
605 ORE->emit(RemarkBuilder: [&]() {
606 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
607 L.getStartLoc(), L.getHeader())
608 << "No loop preheader found";
609 });
610 return false;
611 }
612
613 unsigned NumStores = 0;
614 for (MachineInstr &MI : *L.getHeader())
615 if (MI.mayStore())
616 ++NumStores;
617 if (NumStores > SwpMaxNumStores) {
618 LLVM_DEBUG(dbgs() << "Too many stores\n");
619 NumFailTooManyStores++;
620 ORE->emit(RemarkBuilder: [&]() {
621 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
622 L.getStartLoc(), L.getHeader())
623 << "Too many store instructions in the loop: "
624 << ore::NV("NumStores", NumStores) << " > "
625 << ore::NV("SwpMaxNumStores", SwpMaxNumStores) << ".";
626 });
627 return false;
628 }
629
630 // Remove any subregisters from inputs to phi nodes.
631 preprocessPhiNodes(B&: *L.getHeader());
632 return true;
633}
634
635void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
636 MachineRegisterInfo &MRI = MF->getRegInfo();
637 SlotIndexes &Slots =
638 *getAnalysis<LiveIntervalsWrapperPass>().getLIS().getSlotIndexes();
639
640 for (MachineInstr &PI : B.phis()) {
641 MachineOperand &DefOp = PI.getOperand(i: 0);
642 assert(DefOp.getSubReg() == 0);
643 auto *RC = MRI.getRegClass(Reg: DefOp.getReg());
644
645 for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
646 MachineOperand &RegOp = PI.getOperand(i);
647 if (RegOp.getSubReg() == 0)
648 continue;
649
650 // If the operand uses a subregister, replace it with a new register
651 // without subregisters, and generate a copy to the new register.
652 Register NewReg = MRI.createVirtualRegister(RegClass: RC);
653 MachineBasicBlock &PredB = *PI.getOperand(i: i+1).getMBB();
654 MachineBasicBlock::iterator At = PredB.getFirstTerminator();
655 const DebugLoc &DL = PredB.findDebugLoc(MBBI: At);
656 auto Copy = BuildMI(BB&: PredB, I: At, MIMD: DL, MCID: TII->get(Opcode: TargetOpcode::COPY), DestReg: NewReg)
657 .addReg(RegNo: RegOp.getReg(), Flags: getRegState(RegOp),
658 SubReg: RegOp.getSubReg());
659 Slots.insertMachineInstrInMaps(MI&: *Copy);
660 RegOp.setReg(NewReg);
661 RegOp.setSubReg(0);
662 }
663 }
664}
665
666/// The SMS algorithm consists of the following main steps:
667/// 1. Computation and analysis of the dependence graph.
668/// 2. Ordering of the nodes (instructions).
669/// 3. Attempt to Schedule the loop.
670bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
671 assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
672
673 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
674 SwingSchedulerDAG SMS(
675 *this, L, getAnalysis<LiveIntervalsWrapperPass>().getLIS(), RegClassInfo,
676 II_setByPragma, LI.LoopPipelinerInfo.get(), AA);
677
678 MachineBasicBlock *MBB = L.getHeader();
679 // The kernel should not include any terminator instructions. These
680 // will be added back later.
681 SMS.startBlock(BB: MBB);
682
683 // Compute the number of 'real' instructions in the basic block by
684 // ignoring terminators.
685 unsigned size = MBB->size();
686 for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
687 E = MBB->instr_end();
688 I != E; ++I, --size)
689 ;
690
691 SMS.enterRegion(bb: MBB, begin: MBB->begin(), end: MBB->getFirstTerminator(), regioninstrs: size);
692 SMS.schedule();
693 SMS.exitRegion();
694
695 SMS.finishBlock();
696 return SMS.hasNewSchedule();
697}
698
699void MachinePipeliner::getAnalysisUsage(AnalysisUsage &AU) const {
700 AU.addRequired<AAResultsWrapperPass>();
701 AU.addPreserved<AAResultsWrapperPass>();
702 AU.addRequired<MachineLoopInfoWrapperPass>();
703 AU.addRequired<MachineDominatorTreeWrapperPass>();
704 AU.addRequired<LiveIntervalsWrapperPass>();
705 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
706 AU.addRequired<TargetPassConfig>();
707 MachineFunctionPass::getAnalysisUsage(AU);
708}
709
710bool MachinePipeliner::runWindowScheduler(MachineLoop &L) {
711 MachineSchedContext Context;
712 Context.MF = MF;
713 Context.MLI = MLI;
714 Context.MDT = MDT;
715 Context.TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
716 Context.AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
717 Context.LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
718 Context.RegClassInfo->runOnMachineFunction(MF: *MF);
719 WindowScheduler WS(&Context, L);
720 return WS.run();
721}
722
723bool MachinePipeliner::useSwingModuloScheduler() {
724 // SwingModuloScheduler does not work when WindowScheduler is forced.
725 return WindowSchedulingOption != WindowSchedulingFlag::WS_Force;
726}
727
728bool MachinePipeliner::useWindowScheduler(bool Changed) {
729 // WindowScheduler does not work for following cases:
730 // 1. when it is off.
731 // 2. when SwingModuloScheduler is successfully scheduled.
732 // 3. when pragma II is enabled.
733 if (II_setByPragma) {
734 LLVM_DEBUG(dbgs() << "Window scheduling is disabled when "
735 "llvm.loop.pipeline.initiationinterval is set.\n");
736 return false;
737 }
738
739 return WindowSchedulingOption == WindowSchedulingFlag::WS_Force ||
740 (WindowSchedulingOption == WindowSchedulingFlag::WS_On && !Changed);
741}
742
743void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
744 if (SwpForceII > 0)
745 MII = SwpForceII;
746 else if (II_setByPragma > 0)
747 MII = II_setByPragma;
748 else
749 MII = std::max(a: ResMII, b: RecMII);
750}
751
752void SwingSchedulerDAG::setMAX_II() {
753 if (SwpForceII > 0)
754 MAX_II = SwpForceII;
755 else if (II_setByPragma > 0)
756 MAX_II = II_setByPragma;
757 else
758 MAX_II = MII + SwpIISearchRange;
759}
760
761/// We override the schedule function in ScheduleDAGInstrs to implement the
762/// scheduling part of the Swing Modulo Scheduling algorithm.
763void SwingSchedulerDAG::schedule() {
764 buildSchedGraph(AA);
765 const LoopCarriedEdges LCE = addLoopCarriedDependences();
766 updatePhiDependences();
767 Topo.InitDAGTopologicalSorting();
768 changeDependences();
769 postProcessDAG();
770 DDG = std::make_unique<SwingSchedulerDDG>(args&: SUnits, args: &EntrySU, args: &ExitSU, args: LCE);
771 LLVM_DEBUG({
772 dump();
773 dbgs() << "===== Loop Carried Edges Begin =====\n";
774 for (SUnit &SU : SUnits)
775 LCE.dump(&SU, TRI, &MRI);
776 dbgs() << "===== Loop Carried Edges End =====\n";
777 });
778
779 NodeSetType NodeSets;
780 findCircuits(NodeSets);
781 NodeSetType Circuits = NodeSets;
782
783 // Calculate the MII.
784 unsigned ResMII = calculateResMII();
785 unsigned RecMII = calculateRecMII(RecNodeSets&: NodeSets);
786
787 fuseRecs(NodeSets);
788
789 // This flag is used for testing and can cause correctness problems.
790 if (SwpIgnoreRecMII)
791 RecMII = 0;
792
793 setMII(ResMII, RecMII);
794 setMAX_II();
795
796 LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
797 << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
798
799 // Can't schedule a loop without a valid MII.
800 if (MII == 0) {
801 LLVM_DEBUG(dbgs() << "Invalid Minimal Initiation Interval: 0\n");
802 NumFailZeroMII++;
803 Pass.ORE->emit(RemarkBuilder: [&]() {
804 return MachineOptimizationRemarkAnalysis(
805 DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
806 << "Invalid Minimal Initiation Interval: 0";
807 });
808 return;
809 }
810
811 // Don't pipeline large loops.
812 if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) {
813 LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
814 << ", we don't pipeline large loops\n");
815 NumFailLargeMaxMII++;
816 Pass.ORE->emit(RemarkBuilder: [&]() {
817 return MachineOptimizationRemarkAnalysis(
818 DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
819 << "Minimal Initiation Interval too large: "
820 << ore::NV("MII", (int)MII) << " > "
821 << ore::NV("SwpMaxMii", SwpMaxMii) << "."
822 << "Refer to -pipeliner-max-mii.";
823 });
824 return;
825 }
826
827 computeNodeFunctions(NodeSets);
828
829 registerPressureFilter(NodeSets);
830
831 colocateNodeSets(NodeSets);
832
833 checkNodeSets(NodeSets);
834
835 LLVM_DEBUG({
836 for (auto &I : NodeSets) {
837 dbgs() << " Rec NodeSet ";
838 I.dump();
839 }
840 });
841
842 llvm::stable_sort(Range&: NodeSets, C: std::greater<NodeSet>());
843
844 groupRemainingNodes(NodeSets);
845
846 removeDuplicateNodes(NodeSets);
847
848 LLVM_DEBUG({
849 for (auto &I : NodeSets) {
850 dbgs() << " NodeSet ";
851 I.dump();
852 }
853 });
854
855 computeNodeOrder(NodeSets);
856
857 // check for node order issues
858 checkValidNodeOrder(Circuits);
859
860 SMSchedule Schedule(Pass.MF, this);
861 Scheduled = schedulePipeline(Schedule);
862
863 if (!Scheduled){
864 LLVM_DEBUG(dbgs() << "No schedule found, return\n");
865 NumFailNoSchedule++;
866 Pass.ORE->emit(RemarkBuilder: [&]() {
867 return MachineOptimizationRemarkAnalysis(
868 DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
869 << "Unable to find schedule";
870 });
871 return;
872 }
873
874 unsigned numStages = Schedule.getMaxStageCount();
875 // No need to generate pipeline if there are no overlapped iterations.
876 if (numStages == 0) {
877 LLVM_DEBUG(dbgs() << "No overlapped iterations, skip.\n");
878 NumFailZeroStage++;
879 Pass.ORE->emit(RemarkBuilder: [&]() {
880 return MachineOptimizationRemarkAnalysis(
881 DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
882 << "No need to pipeline - no overlapped iterations in schedule.";
883 });
884 return;
885 }
886 // Check that the maximum stage count is less than user-defined limit.
887 if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) {
888 LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages
889 << " : too many stages, abort\n");
890 NumFailLargeMaxStage++;
891 Pass.ORE->emit(RemarkBuilder: [&]() {
892 return MachineOptimizationRemarkAnalysis(
893 DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
894 << "Too many stages in schedule: "
895 << ore::NV("numStages", (int)numStages) << " > "
896 << ore::NV("SwpMaxStages", SwpMaxStages)
897 << ". Refer to -pipeliner-max-stages.";
898 });
899 return;
900 }
901
902 Pass.ORE->emit(RemarkBuilder: [&]() {
903 return MachineOptimizationRemark(DEBUG_TYPE, "schedule", Loop.getStartLoc(),
904 Loop.getHeader())
905 << "Pipelined succesfully!";
906 });
907
908 // Generate the schedule as a ModuloSchedule.
909 DenseMap<MachineInstr *, int> Cycles, Stages;
910 std::vector<MachineInstr *> OrderedInsts;
911 for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
912 ++Cycle) {
913 for (SUnit *SU : Schedule.getInstructions(cycle: Cycle)) {
914 OrderedInsts.push_back(x: SU->getInstr());
915 Cycles[SU->getInstr()] = Cycle;
916 Stages[SU->getInstr()] = Schedule.stageScheduled(SU);
917 }
918 }
919 DenseMap<MachineInstr *, std::pair<Register, int64_t>> NewInstrChanges;
920 for (auto &KV : NewMIs) {
921 Cycles[KV.first] = Cycles[KV.second];
922 Stages[KV.first] = Stages[KV.second];
923 NewInstrChanges[KV.first] = InstrChanges[getSUnit(MI: KV.first)];
924 }
925
926 ModuloSchedule MS(MF, &Loop, std::move(OrderedInsts), std::move(Cycles),
927 std::move(Stages));
928 if (EmitTestAnnotations) {
929 assert(NewInstrChanges.empty() &&
930 "Cannot serialize a schedule with InstrChanges!");
931 ModuloScheduleTestAnnotater MSTI(MF, MS);
932 MSTI.annotate();
933 return;
934 }
935 // The experimental code generator can't work if there are InstChanges.
936 if (ExperimentalCodeGen && NewInstrChanges.empty()) {
937 PeelingModuloScheduleExpander MSE(MF, MS, &LIS);
938 MSE.expand();
939 } else if (MVECodeGen && NewInstrChanges.empty() &&
940 LoopPipelinerInfo->isMVEExpanderSupported() &&
941 ModuloScheduleExpanderMVE::canApply(L&: Loop)) {
942 ModuloScheduleExpanderMVE MSE(MF, MS, LIS);
943 MSE.expand();
944 } else {
945 ModuloScheduleExpander MSE(MF, MS, LIS, std::move(NewInstrChanges));
946 MSE.expand();
947 MSE.cleanup();
948 }
949 ++NumPipelined;
950}
951
952/// Clean up after the software pipeliner runs.
953void SwingSchedulerDAG::finishBlock() {
954 for (auto &KV : NewMIs)
955 MF.deleteMachineInstr(MI: KV.second);
956 NewMIs.clear();
957
958 // Call the superclass.
959 ScheduleDAGInstrs::finishBlock();
960}
961
962/// Return the register values for the operands of a Phi instruction.
963/// This function assume the instruction is a Phi.
964static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
965 Register &InitVal, Register &LoopVal) {
966 assert(Phi.isPHI() && "Expecting a Phi.");
967
968 InitVal = Register();
969 LoopVal = Register();
970 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
971 if (Phi.getOperand(i: i + 1).getMBB() != Loop)
972 InitVal = Phi.getOperand(i).getReg();
973 else
974 LoopVal = Phi.getOperand(i).getReg();
975
976 assert(InitVal && LoopVal && "Unexpected Phi structure.");
977}
978
979/// Return the Phi register value that comes the loop block.
980static Register getLoopPhiReg(const MachineInstr &Phi,
981 const MachineBasicBlock *LoopBB) {
982 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
983 if (Phi.getOperand(i: i + 1).getMBB() == LoopBB)
984 return Phi.getOperand(i).getReg();
985 return Register();
986}
987
988/// Return true if SUb can be reached from SUa following the chain edges.
989static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
990 SmallPtrSet<SUnit *, 8> Visited;
991 SmallVector<SUnit *, 8> Worklist;
992 Worklist.push_back(Elt: SUa);
993 while (!Worklist.empty()) {
994 const SUnit *SU = Worklist.pop_back_val();
995 for (const auto &SI : SU->Succs) {
996 SUnit *SuccSU = SI.getSUnit();
997 if (SI.getKind() == SDep::Order) {
998 if (Visited.count(Ptr: SuccSU))
999 continue;
1000 if (SuccSU == SUb)
1001 return true;
1002 Worklist.push_back(Elt: SuccSU);
1003 Visited.insert(Ptr: SuccSU);
1004 }
1005 }
1006 }
1007 return false;
1008}
1009
1010SUnitWithMemInfo::SUnitWithMemInfo(SUnit *SU) : SU(SU) {
1011 if (!getUnderlyingObjects())
1012 return;
1013 for (const Value *Obj : UnderlyingObjs)
1014 if (!isIdentifiedObject(V: Obj)) {
1015 IsAllIdentified = false;
1016 break;
1017 }
1018}
1019
1020bool SUnitWithMemInfo::isTriviallyDisjoint(
1021 const SUnitWithMemInfo &Other) const {
1022 // If all underlying objects are identified objects and there is no overlap
1023 // between them, then these two instructions are disjoint.
1024 if (!IsAllIdentified || !Other.IsAllIdentified)
1025 return false;
1026 for (const Value *Obj : UnderlyingObjs)
1027 if (llvm::is_contained(Range: Other.UnderlyingObjs, Element: Obj))
1028 return false;
1029 return true;
1030}
1031
1032/// Collect the underlying objects for the memory references of an instruction.
1033/// This function calls the code in ValueTracking, but first checks that the
1034/// instruction has a memory operand.
1035/// Returns false if we cannot find the underlying objects.
1036bool SUnitWithMemInfo::getUnderlyingObjects() {
1037 const MachineInstr *MI = SU->getInstr();
1038 if (!MI->hasOneMemOperand())
1039 return false;
1040 MachineMemOperand *MM = *MI->memoperands_begin();
1041 if (!MM->getValue())
1042 return false;
1043 MemOpValue = MM->getValue();
1044 MemOpOffset = MM->getOffset();
1045 llvm::getUnderlyingObjects(V: MemOpValue, Objects&: UnderlyingObjs);
1046
1047 // TODO: A no alias scope may be valid only in a single iteration. In this
1048 // case we need to peel off it like LoopAccessAnalysis does.
1049 AATags = MM->getAAInfo();
1050 return true;
1051}
1052
1053/// Returns true if there is a loop-carried order dependency from \p Src to \p
1054/// Dst.
1055static bool hasLoopCarriedMemDep(const SUnitWithMemInfo &Src,
1056 const SUnitWithMemInfo &Dst,
1057 BatchAAResults &BAA,
1058 const TargetInstrInfo *TII,
1059 const TargetRegisterInfo *TRI,
1060 const SwingSchedulerDAG *SSD) {
1061 if (Src.isTriviallyDisjoint(Other: Dst))
1062 return false;
1063 if (isSuccOrder(SUa: Src.SU, SUb: Dst.SU))
1064 return false;
1065
1066 MachineInstr &SrcMI = *Src.SU->getInstr();
1067 MachineInstr &DstMI = *Dst.SU->getInstr();
1068
1069 if (!SSD->mayOverlapInLaterIter(BaseMI: &SrcMI, OtherMI: &DstMI))
1070 return false;
1071
1072 // Second, the more expensive check that uses alias analysis on the
1073 // base registers. If they alias, and the load offset is less than
1074 // the store offset, the mark the dependence as loop carried.
1075 if (Src.isUnknown() || Dst.isUnknown())
1076 return true;
1077 if (Src.MemOpValue == Dst.MemOpValue && Src.MemOpOffset <= Dst.MemOpOffset)
1078 return true;
1079
1080 if (BAA.isNoAlias(
1081 LocA: MemoryLocation::getBeforeOrAfter(Ptr: Src.MemOpValue, AATags: Src.AATags),
1082 LocB: MemoryLocation::getBeforeOrAfter(Ptr: Dst.MemOpValue, AATags: Dst.AATags)))
1083 return false;
1084
1085 // AliasAnalysis sometimes gives up on following the underlying
1086 // object. In such a case, separate checks for underlying objects may
1087 // prove that there are no aliases between two accesses.
1088 for (const Value *SrcObj : Src.UnderlyingObjs)
1089 for (const Value *DstObj : Dst.UnderlyingObjs)
1090 if (!BAA.isNoAlias(LocA: MemoryLocation::getBeforeOrAfter(Ptr: SrcObj, AATags: Src.AATags),
1091 LocB: MemoryLocation::getBeforeOrAfter(Ptr: DstObj, AATags: Dst.AATags)))
1092 return true;
1093
1094 return false;
1095}
1096
1097void LoopCarriedOrderDepsTracker::NoBarrierInstsChunk::append(SUnit *SU) {
1098 const MachineInstr *MI = SU->getInstr();
1099 if (MI->mayStore())
1100 Stores.emplace_back(Args&: SU);
1101 else if (MI->mayLoad())
1102 Loads.emplace_back(Args&: SU);
1103 else if (MI->mayRaiseFPException())
1104 FPExceptions.emplace_back(Args&: SU);
1105 else
1106 llvm_unreachable("Unexpected instruction type.");
1107}
1108
1109LoopCarriedOrderDepsTracker::LoopCarriedOrderDepsTracker(
1110 SwingSchedulerDAG *SSD, BatchAAResults *BAA, const TargetInstrInfo *TII,
1111 const TargetRegisterInfo *TRI)
1112 : DAG(SSD), BAA(BAA), SUnits(DAG->SUnits), N(SUnits.size()),
1113 LoopCarried(N, BitVector(N)), TII(TII), TRI(TRI) {}
1114
1115void LoopCarriedOrderDepsTracker::computeDependencies() {
1116 // Traverse all instructions and extract only what we are targetting.
1117 for (auto &SU : SUnits) {
1118 auto Tagged = getInstrTag(SU: &SU);
1119
1120 // This instruction has no loop-carried order-dependencies.
1121 if (!Tagged)
1122 continue;
1123 TaggedSUnits.emplace_back(args: &SU, args&: *Tagged);
1124 }
1125
1126 computeDependenciesAux();
1127}
1128
1129std::optional<LoopCarriedOrderDepsTracker::InstrTag>
1130LoopCarriedOrderDepsTracker::getInstrTag(SUnit *SU) const {
1131 MachineInstr *MI = SU->getInstr();
1132 if (TII->isGlobalMemoryObject(MI))
1133 return InstrTag::Barrier;
1134
1135 if (MI->mayStore() ||
1136 (MI->mayLoad() && !MI->isDereferenceableInvariantLoad()))
1137 return InstrTag::LoadOrStore;
1138
1139 if (MI->mayRaiseFPException())
1140 return InstrTag::FPExceptions;
1141
1142 return std::nullopt;
1143}
1144
1145void LoopCarriedOrderDepsTracker::addDependenciesBetweenSUs(
1146 const SUnitWithMemInfo &Src, const SUnitWithMemInfo &Dst) {
1147 // Avoid self-dependencies.
1148 if (Src.SU == Dst.SU)
1149 return;
1150
1151 if (hasLoopCarriedMemDep(Src, Dst, BAA&: *BAA, TII, TRI, SSD: DAG))
1152 setLoopCarriedDep(Src: Src.SU, Dst: Dst.SU);
1153}
1154
1155void LoopCarriedOrderDepsTracker::addLoopCarriedDepenenciesForChunks(
1156 const NoBarrierInstsChunk &From, const NoBarrierInstsChunk &To) {
1157 // Add load-to-store dependencies (WAR).
1158 for (const SUnitWithMemInfo &Src : From.Loads)
1159 for (const SUnitWithMemInfo &Dst : To.Stores)
1160 addDependenciesBetweenSUs(Src, Dst);
1161
1162 // Add store-to-load dependencies (RAW).
1163 for (const SUnitWithMemInfo &Src : From.Stores)
1164 for (const SUnitWithMemInfo &Dst : To.Loads)
1165 addDependenciesBetweenSUs(Src, Dst);
1166
1167 // Add store-to-store dependencies (WAW).
1168 for (const SUnitWithMemInfo &Src : From.Stores)
1169 for (const SUnitWithMemInfo &Dst : To.Stores)
1170 addDependenciesBetweenSUs(Src, Dst);
1171}
1172
1173void LoopCarriedOrderDepsTracker::computeDependenciesAux() {
1174 SmallVector<NoBarrierInstsChunk, 2> Chunks(1);
1175 SUnit *FirstBarrier = nullptr;
1176 SUnit *LastBarrier = nullptr;
1177 for (const auto &TSU : TaggedSUnits) {
1178 InstrTag Tag = TSU.getTag();
1179 SUnit *SU = TSU.getPointer();
1180 switch (Tag) {
1181 case InstrTag::Barrier:
1182 if (!FirstBarrier)
1183 FirstBarrier = SU;
1184 LastBarrier = SU;
1185 Chunks.emplace_back();
1186 break;
1187 case InstrTag::LoadOrStore:
1188 case InstrTag::FPExceptions:
1189 Chunks.back().append(SU);
1190 break;
1191 }
1192 }
1193
1194 // Add dependencies between memory operations. If there are one or more
1195 // barrier events between two memory instructions, we don't add a
1196 // loop-carried dependence for them.
1197 for (const NoBarrierInstsChunk &Chunk : Chunks)
1198 addLoopCarriedDepenenciesForChunks(From: Chunk, To: Chunk);
1199
1200 // There is no barrier instruction between load/store/fp-exception
1201 // instructions in the same chunk. If there are one or more barrier
1202 // instructions, the instructions sequence is as follows:
1203 //
1204 // Loads/Stores/FPExceptions (Chunks.front())
1205 // Barrier (FirstBarrier)
1206 // Loads/Stores/FPExceptions
1207 // Barrier
1208 // ...
1209 // Loads/Stores/FPExceptions
1210 // Barrier (LastBarrier)
1211 // Loads/Stores/FPExceptions (Chunks.back())
1212 //
1213 // Since loads/stores/fp-exceptions must not be reordered across barrier
1214 // instructions, and the order of barrier instructions must be preserved, add
1215 // the following loop-carried dependences:
1216 //
1217 // Loads/Stores/FPExceptions (Chunks.front()) <-----+
1218 // +--> Barrier (FirstBarrier) <----------------------+ |
1219 // | Loads/Stores/FPExceptions | |
1220 // | Barrier | |
1221 // | ... | |
1222 // | Loads/Stores/FPExceptions | |
1223 // | Barrier (LastBarrier) ------------------------+--+
1224 // +--- Loads/Stores/FPExceptions (Chunks.back())
1225 //
1226 if (FirstBarrier) {
1227 assert(LastBarrier && "Both barriers should be set.");
1228
1229 // LastBarrier -> Loads/Stores/FPExceptions in Chunks.front()
1230 for (const SUnitWithMemInfo &Dst : Chunks.front().Loads)
1231 setLoopCarriedDep(Src: LastBarrier, Dst: Dst.SU);
1232 for (const SUnitWithMemInfo &Dst : Chunks.front().Stores)
1233 setLoopCarriedDep(Src: LastBarrier, Dst: Dst.SU);
1234 for (const SUnitWithMemInfo &Dst : Chunks.front().FPExceptions)
1235 setLoopCarriedDep(Src: LastBarrier, Dst: Dst.SU);
1236
1237 // Loads/Stores/FPExceptions in Chunks.back() -> FirstBarrier
1238 for (const SUnitWithMemInfo &Src : Chunks.back().Loads)
1239 setLoopCarriedDep(Src: Src.SU, Dst: FirstBarrier);
1240 for (const SUnitWithMemInfo &Src : Chunks.back().Stores)
1241 setLoopCarriedDep(Src: Src.SU, Dst: FirstBarrier);
1242 for (const SUnitWithMemInfo &Src : Chunks.back().FPExceptions)
1243 setLoopCarriedDep(Src: Src.SU, Dst: FirstBarrier);
1244
1245 // LastBarrier -> FirstBarrier (if they are different)
1246 if (FirstBarrier != LastBarrier)
1247 setLoopCarriedDep(Src: LastBarrier, Dst: FirstBarrier);
1248 }
1249}
1250
1251/// Add a chain edge between a load and store if the store can be an
1252/// alias of the load on a subsequent iteration, i.e., a loop carried
1253/// dependence. This code is very similar to the code in ScheduleDAGInstrs
1254/// but that code doesn't create loop carried dependences.
1255/// TODO: Also compute output-dependencies.
1256LoopCarriedEdges SwingSchedulerDAG::addLoopCarriedDependences() {
1257 LoopCarriedEdges LCE;
1258
1259 // Add loop-carried order-dependencies
1260 LoopCarriedOrderDepsTracker LCODTracker(this, &BAA, TII, TRI);
1261 LCODTracker.computeDependencies();
1262 for (unsigned I = 0; I != SUnits.size(); I++)
1263 for (const int Succ : LCODTracker.getLoopCarried(Idx: I).set_bits())
1264 LCE.OrderDeps[&SUnits[I]].insert(X: &SUnits[Succ]);
1265
1266 LCE.modifySUnits(SUnits, TII);
1267 return LCE;
1268}
1269
1270/// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
1271/// processes dependences for PHIs. This function adds true dependences
1272/// from a PHI to a use, and a loop carried dependence from the use to the
1273/// PHI. The loop carried dependence is represented as an anti dependence
1274/// edge. This function also removes chain dependences between unrelated
1275/// PHIs.
1276void SwingSchedulerDAG::updatePhiDependences() {
1277 SmallVector<SDep, 4> RemoveDeps;
1278 const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
1279
1280 // Iterate over each DAG node.
1281 for (SUnit &I : SUnits) {
1282 RemoveDeps.clear();
1283 // Set to true if the instruction has an operand defined by a Phi.
1284 Register HasPhiUse;
1285 Register HasPhiDef;
1286 MachineInstr *MI = I.getInstr();
1287 // Iterate over each operand, and we process the definitions.
1288 for (const MachineOperand &MO : MI->operands()) {
1289 if (!MO.isReg())
1290 continue;
1291 Register Reg = MO.getReg();
1292 if (MO.isDef()) {
1293 // If the register is used by a Phi, then create an anti dependence.
1294 for (MachineRegisterInfo::use_instr_iterator
1295 UI = MRI.use_instr_begin(RegNo: Reg),
1296 UE = MRI.use_instr_end();
1297 UI != UE; ++UI) {
1298 MachineInstr *UseMI = &*UI;
1299 SUnit *SU = getSUnit(MI: UseMI);
1300 if (SU != nullptr && UseMI->isPHI()) {
1301 if (!MI->isPHI()) {
1302 SDep Dep(SU, SDep::Anti, Reg);
1303 Dep.setLatency(1);
1304 I.addPred(D: Dep);
1305 } else {
1306 HasPhiDef = Reg;
1307 // Add a chain edge to a dependent Phi that isn't an existing
1308 // predecessor.
1309
1310 // %3:intregs = PHI %21:intregs, %bb.6, %7:intregs, %bb.1 - SU0
1311 // %7:intregs = PHI %21:intregs, %bb.6, %13:intregs, %bb.1 - SU1
1312 // %27:intregs = A2_zxtb %3:intregs - SU2
1313 // %13:intregs = C2_muxri %45:predregs, 0, %46:intreg
1314 // If we have dependent phis, SU0 should be the successor of SU1
1315 // not the other way around. (it used to be SU1 is the successor
1316 // of SU0). In some cases, SU0 is scheduled earlier than SU1
1317 // resulting in bad IR as we do not have a value that can be used
1318 // by SU2.
1319
1320 if (SU->NodeNum < I.NodeNum && !SU->isPred(N: &I))
1321 SU->addPred(D: SDep(&I, SDep::Barrier));
1322 }
1323 }
1324 }
1325 } else if (MO.isUse()) {
1326 // If the register is defined by a Phi, then create a true dependence.
1327 MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
1328 if (DefMI == nullptr)
1329 continue;
1330 SUnit *SU = getSUnit(MI: DefMI);
1331 if (SU != nullptr && DefMI->isPHI()) {
1332 if (!MI->isPHI()) {
1333 SDep Dep(SU, SDep::Data, Reg);
1334 Dep.setLatency(0);
1335 ST.adjustSchedDependency(Def: SU, DefOpIdx: 0, Use: &I, UseOpIdx: MO.getOperandNo(), Dep,
1336 SchedModel: &SchedModel);
1337 I.addPred(D: Dep);
1338 } else {
1339 HasPhiUse = Reg;
1340 // Add a chain edge to a dependent Phi that isn't an existing
1341 // predecessor.
1342 if (SU->NodeNum < I.NodeNum && !I.isPred(N: SU))
1343 I.addPred(D: SDep(SU, SDep::Barrier));
1344 }
1345 }
1346 }
1347 }
1348 // Remove order dependences from an unrelated Phi.
1349 if (!SwpPruneDeps)
1350 continue;
1351 for (auto &PI : I.Preds) {
1352 MachineInstr *PMI = PI.getSUnit()->getInstr();
1353 if (PMI->isPHI() && PI.getKind() == SDep::Order) {
1354 if (I.getInstr()->isPHI()) {
1355 if (PMI->getOperand(i: 0).getReg() == HasPhiUse)
1356 continue;
1357 if (getLoopPhiReg(Phi: *PMI, LoopBB: PMI->getParent()) == HasPhiDef)
1358 continue;
1359 }
1360 RemoveDeps.push_back(Elt: PI);
1361 }
1362 }
1363 for (const SDep &D : RemoveDeps)
1364 I.removePred(D);
1365 }
1366}
1367
1368/// Iterate over each DAG node and see if we can change any dependences
1369/// in order to reduce the recurrence MII.
1370void SwingSchedulerDAG::changeDependences() {
1371 // See if an instruction can use a value from the previous iteration.
1372 // If so, we update the base and offset of the instruction and change
1373 // the dependences.
1374 for (SUnit &I : SUnits) {
1375 unsigned BasePos = 0, OffsetPos = 0;
1376 Register NewBase;
1377 int64_t NewOffset = 0;
1378 if (!canUseLastOffsetValue(MI: I.getInstr(), BasePos, OffsetPos, NewBase,
1379 NewOffset))
1380 continue;
1381
1382 // Get the MI and SUnit for the instruction that defines the original base.
1383 Register OrigBase = I.getInstr()->getOperand(i: BasePos).getReg();
1384 MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg: OrigBase);
1385 if (!DefMI)
1386 continue;
1387 SUnit *DefSU = getSUnit(MI: DefMI);
1388 if (!DefSU)
1389 continue;
1390 // Get the MI and SUnit for the instruction that defins the new base.
1391 MachineInstr *LastMI = MRI.getUniqueVRegDef(Reg: NewBase);
1392 if (!LastMI)
1393 continue;
1394 SUnit *LastSU = getSUnit(MI: LastMI);
1395 if (!LastSU)
1396 continue;
1397
1398 if (Topo.IsReachable(SU: &I, TargetSU: LastSU))
1399 continue;
1400
1401 // Remove the dependence. The value now depends on a prior iteration.
1402 SmallVector<SDep, 4> Deps;
1403 for (const SDep &P : I.Preds)
1404 if (P.getSUnit() == DefSU)
1405 Deps.push_back(Elt: P);
1406 for (const SDep &D : Deps) {
1407 Topo.RemovePred(M: &I, N: D.getSUnit());
1408 I.removePred(D);
1409 }
1410 // Remove the chain dependence between the instructions.
1411 Deps.clear();
1412 for (auto &P : LastSU->Preds)
1413 if (P.getSUnit() == &I && P.getKind() == SDep::Order)
1414 Deps.push_back(Elt: P);
1415 for (const SDep &D : Deps) {
1416 Topo.RemovePred(M: LastSU, N: D.getSUnit());
1417 LastSU->removePred(D);
1418 }
1419
1420 // Add a dependence between the new instruction and the instruction
1421 // that defines the new base.
1422 SDep Dep(&I, SDep::Anti, NewBase);
1423 Topo.AddPred(Y: LastSU, X: &I);
1424 LastSU->addPred(D: Dep);
1425
1426 // Remember the base and offset information so that we can update the
1427 // instruction during code generation.
1428 InstrChanges[&I] = std::make_pair(x&: NewBase, y&: NewOffset);
1429 }
1430}
1431
1432/// Create an instruction stream that represents a single iteration and stage of
1433/// each instruction. This function differs from SMSchedule::finalizeSchedule in
1434/// that this doesn't have any side-effect to SwingSchedulerDAG. That is, this
1435/// function is an approximation of SMSchedule::finalizeSchedule with all
1436/// non-const operations removed.
1437static void computeScheduledInsts(const SwingSchedulerDAG *SSD,
1438 SMSchedule &Schedule,
1439 std::vector<MachineInstr *> &OrderedInsts,
1440 DenseMap<MachineInstr *, unsigned> &Stages) {
1441 DenseMap<int, std::deque<SUnit *>> Instrs;
1442
1443 // Move all instructions to the first stage from the later stages.
1444 for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
1445 ++Cycle) {
1446 for (int Stage = 0, LastStage = Schedule.getMaxStageCount();
1447 Stage <= LastStage; ++Stage) {
1448 for (SUnit *SU : llvm::reverse(C&: Schedule.getInstructions(
1449 cycle: Cycle + Stage * Schedule.getInitiationInterval()))) {
1450 Instrs[Cycle].push_front(x: SU);
1451 }
1452 }
1453 }
1454
1455 for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
1456 ++Cycle) {
1457 std::deque<SUnit *> &CycleInstrs = Instrs[Cycle];
1458 CycleInstrs = Schedule.reorderInstructions(SSD, Instrs: CycleInstrs);
1459 for (SUnit *SU : CycleInstrs) {
1460 MachineInstr *MI = SU->getInstr();
1461 OrderedInsts.push_back(x: MI);
1462 Stages[MI] = Schedule.stageScheduled(SU);
1463 }
1464 }
1465}
1466
1467namespace {
1468
1469// FuncUnitSorter - Comparison operator used to sort instructions by
1470// the number of functional unit choices.
1471struct FuncUnitSorter {
1472 const InstrItineraryData *InstrItins;
1473 const MCSubtargetInfo *STI;
1474 DenseMap<InstrStage::FuncUnits, unsigned> Resources;
1475
1476 FuncUnitSorter(const TargetSubtargetInfo &TSI)
1477 : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
1478
1479 // Compute the number of functional unit alternatives needed
1480 // at each stage, and take the minimum value. We prioritize the
1481 // instructions by the least number of choices first.
1482 unsigned minFuncUnits(const MachineInstr *Inst,
1483 InstrStage::FuncUnits &F) const {
1484 unsigned SchedClass = Inst->getDesc().getSchedClass();
1485 unsigned min = UINT_MAX;
1486 if (InstrItins && !InstrItins->isEmpty()) {
1487 for (const InstrStage &IS :
1488 make_range(x: InstrItins->beginStage(ItinClassIndx: SchedClass),
1489 y: InstrItins->endStage(ItinClassIndx: SchedClass))) {
1490 InstrStage::FuncUnits funcUnits = IS.getUnits();
1491 unsigned numAlternatives = llvm::popcount(Value: funcUnits);
1492 if (numAlternatives < min) {
1493 min = numAlternatives;
1494 F = funcUnits;
1495 }
1496 }
1497 return min;
1498 }
1499 if (STI && STI->getSchedModel().hasInstrSchedModel()) {
1500 const MCSchedClassDesc *SCDesc =
1501 STI->getSchedModel().getSchedClassDesc(SchedClassIdx: SchedClass);
1502 if (!SCDesc->isValid())
1503 // No valid Schedule Class Desc for schedClass, should be
1504 // Pseudo/PostRAPseudo
1505 return min;
1506
1507 for (const MCWriteProcResEntry &PRE :
1508 make_range(x: STI->getWriteProcResBegin(SC: SCDesc),
1509 y: STI->getWriteProcResEnd(SC: SCDesc))) {
1510 if (!PRE.ReleaseAtCycle)
1511 continue;
1512 const MCProcResourceDesc *ProcResource =
1513 STI->getSchedModel().getProcResource(ProcResourceIdx: PRE.ProcResourceIdx);
1514 unsigned NumUnits = ProcResource->NumUnits;
1515 if (NumUnits < min) {
1516 min = NumUnits;
1517 F = PRE.ProcResourceIdx;
1518 }
1519 }
1520 return min;
1521 }
1522 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1523 }
1524
1525 // Compute the critical resources needed by the instruction. This
1526 // function records the functional units needed by instructions that
1527 // must use only one functional unit. We use this as a tie breaker
1528 // for computing the resource MII. The instrutions that require
1529 // the same, highly used, functional unit have high priority.
1530 void calcCriticalResources(MachineInstr &MI) {
1531 unsigned SchedClass = MI.getDesc().getSchedClass();
1532 if (InstrItins && !InstrItins->isEmpty()) {
1533 for (const InstrStage &IS :
1534 make_range(x: InstrItins->beginStage(ItinClassIndx: SchedClass),
1535 y: InstrItins->endStage(ItinClassIndx: SchedClass))) {
1536 InstrStage::FuncUnits FuncUnits = IS.getUnits();
1537 if (llvm::popcount(Value: FuncUnits) == 1)
1538 Resources[FuncUnits]++;
1539 }
1540 return;
1541 }
1542 if (STI && STI->getSchedModel().hasInstrSchedModel()) {
1543 const MCSchedClassDesc *SCDesc =
1544 STI->getSchedModel().getSchedClassDesc(SchedClassIdx: SchedClass);
1545 if (!SCDesc->isValid())
1546 // No valid Schedule Class Desc for schedClass, should be
1547 // Pseudo/PostRAPseudo
1548 return;
1549
1550 for (const MCWriteProcResEntry &PRE :
1551 make_range(x: STI->getWriteProcResBegin(SC: SCDesc),
1552 y: STI->getWriteProcResEnd(SC: SCDesc))) {
1553 if (!PRE.ReleaseAtCycle)
1554 continue;
1555 Resources[PRE.ProcResourceIdx]++;
1556 }
1557 return;
1558 }
1559 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1560 }
1561
1562 /// Return true if IS1 has less priority than IS2.
1563 bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
1564 InstrStage::FuncUnits F1 = 0, F2 = 0;
1565 unsigned MFUs1 = minFuncUnits(Inst: IS1, F&: F1);
1566 unsigned MFUs2 = minFuncUnits(Inst: IS2, F&: F2);
1567 if (MFUs1 == MFUs2)
1568 return Resources.lookup(Val: F1) < Resources.lookup(Val: F2);
1569 return MFUs1 > MFUs2;
1570 }
1571};
1572
1573/// Calculate the maximum register pressure of the scheduled instructions stream
1574class HighRegisterPressureDetector {
1575 MachineBasicBlock *OrigMBB;
1576 const MachineRegisterInfo &MRI;
1577 const TargetRegisterInfo *TRI;
1578
1579 const unsigned PSetNum;
1580
1581 // Indexed by PSet ID
1582 // InitSetPressure takes into account the register pressure of live-in
1583 // registers. It's not depend on how the loop is scheduled, so it's enough to
1584 // calculate them once at the beginning.
1585 std::vector<unsigned> InitSetPressure;
1586
1587 // Indexed by PSet ID
1588 // Upper limit for each register pressure set
1589 std::vector<unsigned> PressureSetLimit;
1590
1591 DenseMap<MachineInstr *, RegisterOperands> ROMap;
1592
1593 using Instr2LastUsesTy = DenseMap<MachineInstr *, SmallDenseSet<Register, 4>>;
1594
1595public:
1596 using OrderedInstsTy = std::vector<MachineInstr *>;
1597 using Instr2StageTy = DenseMap<MachineInstr *, unsigned>;
1598
1599private:
1600 static void dumpRegisterPressures(const std::vector<unsigned> &Pressures) {
1601 if (Pressures.size() == 0) {
1602 dbgs() << "[]";
1603 } else {
1604 char Prefix = '[';
1605 for (unsigned P : Pressures) {
1606 dbgs() << Prefix << P;
1607 Prefix = ' ';
1608 }
1609 dbgs() << ']';
1610 }
1611 }
1612
1613 void dumpPSet(Register Reg) const {
1614 dbgs() << "Reg=" << printReg(Reg, TRI, SubIdx: 0, MRI: &MRI) << " PSet=";
1615 // FIXME: The static_cast is a bug compensating bugs in the callers.
1616 VirtRegOrUnit VRegOrUnit =
1617 Reg.isVirtual() ? VirtRegOrUnit(Reg)
1618 : VirtRegOrUnit(static_cast<MCRegUnit>(Reg.id()));
1619 for (auto PSetIter = MRI.getPressureSets(VRegOrUnit); PSetIter.isValid();
1620 ++PSetIter) {
1621 dbgs() << *PSetIter << ' ';
1622 }
1623 dbgs() << '\n';
1624 }
1625
1626 void increaseRegisterPressure(std::vector<unsigned> &Pressure,
1627 Register Reg) const {
1628 // FIXME: The static_cast is a bug compensating bugs in the callers.
1629 VirtRegOrUnit VRegOrUnit =
1630 Reg.isVirtual() ? VirtRegOrUnit(Reg)
1631 : VirtRegOrUnit(static_cast<MCRegUnit>(Reg.id()));
1632 auto PSetIter = MRI.getPressureSets(VRegOrUnit);
1633 unsigned Weight = PSetIter.getWeight();
1634 for (; PSetIter.isValid(); ++PSetIter)
1635 Pressure[*PSetIter] += Weight;
1636 }
1637
1638 void decreaseRegisterPressure(std::vector<unsigned> &Pressure,
1639 Register Reg) const {
1640 auto PSetIter = MRI.getPressureSets(VRegOrUnit: VirtRegOrUnit(Reg));
1641 unsigned Weight = PSetIter.getWeight();
1642 for (; PSetIter.isValid(); ++PSetIter) {
1643 auto &P = Pressure[*PSetIter];
1644 assert(P >= Weight &&
1645 "register pressure must be greater than or equal weight");
1646 P -= Weight;
1647 }
1648 }
1649
1650 // Return true if Reg is reserved one, for example, stack pointer
1651 bool isReservedRegister(Register Reg) const {
1652 return Reg.isPhysical() && MRI.isReserved(PhysReg: Reg.asMCReg());
1653 }
1654
1655 bool isDefinedInThisLoop(Register Reg) const {
1656 return Reg.isVirtual() && MRI.getVRegDef(Reg)->getParent() == OrigMBB;
1657 }
1658
1659 // Search for live-in variables. They are factored into the register pressure
1660 // from the begining. Live-in variables used by every iteration should be
1661 // considered as alive throughout the loop. For example, the variable `c` in
1662 // following code. \code
1663 // int c = ...;
1664 // for (int i = 0; i < n; i++)
1665 // a[i] += b[i] + c;
1666 // \endcode
1667 void computeLiveIn() {
1668 DenseSet<Register> Used;
1669 for (auto &MI : *OrigMBB) {
1670 if (MI.isDebugInstr())
1671 continue;
1672 for (auto &Use : ROMap[&MI].Uses) {
1673 // FIXME: The static_cast is a bug.
1674 Register Reg =
1675 Use.VRegOrUnit.isVirtualReg()
1676 ? Use.VRegOrUnit.asVirtualReg()
1677 : Register(static_cast<unsigned>(Use.VRegOrUnit.asMCRegUnit()));
1678 // Ignore the variable that appears only on one side of phi instruction
1679 // because it's used only at the first iteration.
1680 if (MI.isPHI() && Reg != getLoopPhiReg(Phi: MI, LoopBB: OrigMBB))
1681 continue;
1682 if (isReservedRegister(Reg))
1683 continue;
1684 if (isDefinedInThisLoop(Reg))
1685 continue;
1686 Used.insert(V: Reg);
1687 }
1688 }
1689
1690 for (auto LiveIn : Used)
1691 increaseRegisterPressure(Pressure&: InitSetPressure, Reg: LiveIn);
1692 }
1693
1694 // Calculate the upper limit of each pressure set
1695 void computePressureSetLimit(const RegisterClassInfo &RCI) {
1696 for (unsigned PSet = 0; PSet < PSetNum; PSet++)
1697 PressureSetLimit[PSet] = RCI.getRegPressureSetLimit(Idx: PSet);
1698 }
1699
1700 // There are two patterns of last-use.
1701 // - by an instruction of the current iteration
1702 // - by a phi instruction of the next iteration (loop carried value)
1703 //
1704 // Furthermore, following two groups of instructions are executed
1705 // simultaneously
1706 // - next iteration's phi instructions in i-th stage
1707 // - current iteration's instructions in i+1-th stage
1708 //
1709 // This function calculates the last-use of each register while taking into
1710 // account the above two patterns.
1711 Instr2LastUsesTy computeLastUses(const OrderedInstsTy &OrderedInsts,
1712 Instr2StageTy &Stages) const {
1713 // We treat virtual registers that are defined and used in this loop.
1714 // Following virtual register will be ignored
1715 // - live-in one
1716 // - defined but not used in the loop (potentially live-out)
1717 DenseSet<Register> TargetRegs;
1718 const auto UpdateTargetRegs = [this, &TargetRegs](Register Reg) {
1719 if (isDefinedInThisLoop(Reg))
1720 TargetRegs.insert(V: Reg);
1721 };
1722 for (MachineInstr *MI : OrderedInsts) {
1723 if (MI->isPHI()) {
1724 Register Reg = getLoopPhiReg(Phi: *MI, LoopBB: OrigMBB);
1725 UpdateTargetRegs(Reg);
1726 } else {
1727 for (auto &Use : ROMap.find(Val: MI)->getSecond().Uses) {
1728 // FIXME: The static_cast is a bug.
1729 Register Reg = Use.VRegOrUnit.isVirtualReg()
1730 ? Use.VRegOrUnit.asVirtualReg()
1731 : Register(static_cast<unsigned>(
1732 Use.VRegOrUnit.asMCRegUnit()));
1733 UpdateTargetRegs(Reg);
1734 }
1735 }
1736 }
1737
1738 const auto InstrScore = [&Stages](MachineInstr *MI) {
1739 return Stages[MI] + MI->isPHI();
1740 };
1741
1742 DenseMap<Register, MachineInstr *> LastUseMI;
1743 for (MachineInstr *MI : llvm::reverse(C: OrderedInsts)) {
1744 for (auto &Use : ROMap.find(Val: MI)->getSecond().Uses) {
1745 // FIXME: The static_cast is a bug.
1746 Register Reg =
1747 Use.VRegOrUnit.isVirtualReg()
1748 ? Use.VRegOrUnit.asVirtualReg()
1749 : Register(static_cast<unsigned>(Use.VRegOrUnit.asMCRegUnit()));
1750 if (!TargetRegs.contains(V: Reg))
1751 continue;
1752 auto [Ite, Inserted] = LastUseMI.try_emplace(Key: Reg, Args&: MI);
1753 if (!Inserted) {
1754 MachineInstr *Orig = Ite->second;
1755 MachineInstr *New = MI;
1756 if (InstrScore(Orig) < InstrScore(New))
1757 Ite->second = New;
1758 }
1759 }
1760 }
1761
1762 Instr2LastUsesTy LastUses;
1763 for (auto [Reg, MI] : LastUseMI)
1764 LastUses[MI].insert(V: Reg);
1765 return LastUses;
1766 }
1767
1768 // Compute the maximum register pressure of the kernel. We'll simulate #Stage
1769 // iterations and check the register pressure at the point where all stages
1770 // overlapping.
1771 //
1772 // An example of unrolled loop where #Stage is 4..
1773 // Iter i+0 i+1 i+2 i+3
1774 // ------------------------
1775 // Stage 0
1776 // Stage 1 0
1777 // Stage 2 1 0
1778 // Stage 3 2 1 0 <- All stages overlap
1779 //
1780 std::vector<unsigned>
1781 computeMaxSetPressure(const OrderedInstsTy &OrderedInsts,
1782 Instr2StageTy &Stages,
1783 const unsigned StageCount) const {
1784 using RegSetTy = SmallDenseSet<Register, 16>;
1785
1786 // Indexed by #Iter. To treat "local" variables of each stage separately, we
1787 // manage the liveness of the registers independently by iterations.
1788 SmallVector<RegSetTy> LiveRegSets(StageCount);
1789
1790 auto CurSetPressure = InitSetPressure;
1791 auto MaxSetPressure = InitSetPressure;
1792 auto LastUses = computeLastUses(OrderedInsts, Stages);
1793
1794 LLVM_DEBUG({
1795 dbgs() << "Ordered instructions:\n";
1796 for (MachineInstr *MI : OrderedInsts) {
1797 dbgs() << "Stage " << Stages[MI] << ": ";
1798 MI->dump();
1799 }
1800 });
1801
1802 const auto InsertReg = [this, &CurSetPressure](RegSetTy &RegSet,
1803 VirtRegOrUnit VRegOrUnit) {
1804 // FIXME: The static_cast is a bug.
1805 Register Reg =
1806 VRegOrUnit.isVirtualReg()
1807 ? VRegOrUnit.asVirtualReg()
1808 : Register(static_cast<unsigned>(VRegOrUnit.asMCRegUnit()));
1809 if (!Reg.isValid() || isReservedRegister(Reg))
1810 return;
1811
1812 bool Inserted = RegSet.insert(V: Reg).second;
1813 if (!Inserted)
1814 return;
1815
1816 LLVM_DEBUG(dbgs() << "insert " << printReg(Reg, TRI, 0, &MRI) << "\n");
1817 increaseRegisterPressure(Pressure&: CurSetPressure, Reg);
1818 LLVM_DEBUG(dumpPSet(Reg));
1819 };
1820
1821 const auto EraseReg = [this, &CurSetPressure](RegSetTy &RegSet,
1822 Register Reg) {
1823 if (!Reg.isValid() || isReservedRegister(Reg))
1824 return;
1825
1826 // live-in register
1827 if (!RegSet.contains(V: Reg))
1828 return;
1829
1830 LLVM_DEBUG(dbgs() << "erase " << printReg(Reg, TRI, 0, &MRI) << "\n");
1831 RegSet.erase(V: Reg);
1832 decreaseRegisterPressure(Pressure&: CurSetPressure, Reg);
1833 LLVM_DEBUG(dumpPSet(Reg));
1834 };
1835
1836 for (unsigned I = 0; I < StageCount; I++) {
1837 for (MachineInstr *MI : OrderedInsts) {
1838 const auto Stage = Stages[MI];
1839 if (I < Stage)
1840 continue;
1841
1842 const unsigned Iter = I - Stage;
1843
1844 for (auto &Def : ROMap.find(Val: MI)->getSecond().Defs)
1845 InsertReg(LiveRegSets[Iter], Def.VRegOrUnit);
1846
1847 for (auto LastUse : LastUses[MI]) {
1848 if (MI->isPHI()) {
1849 if (Iter != 0)
1850 EraseReg(LiveRegSets[Iter - 1], LastUse);
1851 } else {
1852 EraseReg(LiveRegSets[Iter], LastUse);
1853 }
1854 }
1855
1856 for (unsigned PSet = 0; PSet < PSetNum; PSet++)
1857 MaxSetPressure[PSet] =
1858 std::max(a: MaxSetPressure[PSet], b: CurSetPressure[PSet]);
1859
1860 LLVM_DEBUG({
1861 dbgs() << "CurSetPressure=";
1862 dumpRegisterPressures(CurSetPressure);
1863 dbgs() << " iter=" << Iter << " stage=" << Stage << ":";
1864 MI->dump();
1865 });
1866 }
1867 }
1868
1869 return MaxSetPressure;
1870 }
1871
1872public:
1873 HighRegisterPressureDetector(MachineBasicBlock *OrigMBB,
1874 const MachineFunction &MF)
1875 : OrigMBB(OrigMBB), MRI(MF.getRegInfo()),
1876 TRI(MF.getSubtarget().getRegisterInfo()),
1877 PSetNum(TRI->getNumRegPressureSets()), InitSetPressure(PSetNum, 0),
1878 PressureSetLimit(PSetNum, 0) {}
1879
1880 // Used to calculate register pressure, which is independent of loop
1881 // scheduling.
1882 void init(const RegisterClassInfo &RCI) {
1883 for (MachineInstr &MI : *OrigMBB) {
1884 if (MI.isDebugInstr())
1885 continue;
1886 ROMap[&MI].collect(MI, TRI: *TRI, MRI, TrackLaneMasks: false, IgnoreDead: true);
1887 }
1888
1889 computeLiveIn();
1890 computePressureSetLimit(RCI);
1891 }
1892
1893 // Calculate the maximum register pressures of the loop and check if they
1894 // exceed the limit
1895 bool detect(const SwingSchedulerDAG *SSD, SMSchedule &Schedule,
1896 const unsigned MaxStage) const {
1897 assert(0 <= RegPressureMargin && RegPressureMargin <= 100 &&
1898 "the percentage of the margin must be between 0 to 100");
1899
1900 OrderedInstsTy OrderedInsts;
1901 Instr2StageTy Stages;
1902 computeScheduledInsts(SSD, Schedule, OrderedInsts, Stages);
1903 const auto MaxSetPressure =
1904 computeMaxSetPressure(OrderedInsts, Stages, StageCount: MaxStage + 1);
1905
1906 LLVM_DEBUG({
1907 dbgs() << "Dump MaxSetPressure:\n";
1908 for (unsigned I = 0; I < MaxSetPressure.size(); I++) {
1909 dbgs() << format("MaxSetPressure[%d]=%d\n", I, MaxSetPressure[I]);
1910 }
1911 dbgs() << '\n';
1912 });
1913
1914 for (unsigned PSet = 0; PSet < PSetNum; PSet++) {
1915 unsigned Limit = PressureSetLimit[PSet];
1916 unsigned Margin = Limit * RegPressureMargin / 100;
1917 LLVM_DEBUG(dbgs() << "PSet=" << PSet << " Limit=" << Limit
1918 << " Margin=" << Margin << "\n");
1919 if (Limit < MaxSetPressure[PSet] + Margin) {
1920 LLVM_DEBUG(
1921 dbgs()
1922 << "Rejected the schedule because of too high register pressure\n");
1923 return true;
1924 }
1925 }
1926 return false;
1927 }
1928};
1929
1930} // end anonymous namespace
1931
1932/// Calculate the resource constrained minimum initiation interval for the
1933/// specified loop. We use the DFA to model the resources needed for
1934/// each instruction, and we ignore dependences. A different DFA is created
1935/// for each cycle that is required. When adding a new instruction, we attempt
1936/// to add it to each existing DFA, until a legal space is found. If the
1937/// instruction cannot be reserved in an existing DFA, we create a new one.
1938unsigned SwingSchedulerDAG::calculateResMII() {
1939 LLVM_DEBUG(dbgs() << "calculateResMII:\n");
1940 ResourceManager RM(&MF.getSubtarget(), this);
1941 return RM.calculateResMII();
1942}
1943
1944/// Calculate the recurrence-constrainted minimum initiation interval.
1945/// Iterate over each circuit. Compute the delay(c) and distance(c)
1946/// for each circuit. The II needs to satisfy the inequality
1947/// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
1948/// II that satisfies the inequality, and the RecMII is the maximum
1949/// of those values.
1950unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1951 unsigned RecMII = 0;
1952
1953 for (NodeSet &Nodes : NodeSets) {
1954 if (Nodes.empty())
1955 continue;
1956
1957 unsigned Delay = Nodes.getLatency();
1958 unsigned Distance = 1;
1959
1960 // ii = ceil(delay / distance)
1961 unsigned CurMII = (Delay + Distance - 1) / Distance;
1962 Nodes.setRecMII(CurMII);
1963 if (CurMII > RecMII)
1964 RecMII = CurMII;
1965 }
1966
1967 return RecMII;
1968}
1969
1970/// Create the adjacency structure of the nodes in the graph.
1971void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1972 SwingSchedulerDAG *DAG) {
1973 BitVector Added(SUnits.size());
1974 DenseMap<int, int> OutputDeps;
1975 for (int i = 0, e = SUnits.size(); i != e; ++i) {
1976 Added.reset();
1977 // Add any successor to the adjacency matrix and exclude duplicates.
1978 for (auto &OE : DAG->DDG->getOutEdges(SU: &SUnits[i])) {
1979 // Only create a back-edge on the first and last nodes of a dependence
1980 // chain. This records any chains and adds them later.
1981 if (OE.isOutputDep()) {
1982 int N = OE.getDst()->NodeNum;
1983 int BackEdge = i;
1984 auto Dep = OutputDeps.find(Val: BackEdge);
1985 if (Dep != OutputDeps.end()) {
1986 BackEdge = Dep->second;
1987 OutputDeps.erase(I: Dep);
1988 }
1989 OutputDeps[N] = BackEdge;
1990 }
1991 // Do not process a boundary node, an artificial node.
1992 if (OE.getDst()->isBoundaryNode() || OE.isArtificial())
1993 continue;
1994
1995 // This code is retained o preserve previous behavior and prevent
1996 // regression. This condition means that anti-dependnecies within an
1997 // iteration are ignored when searching circuits. Therefore it's natural
1998 // to consider this dependence as well.
1999 // FIXME: Remove this code if it doesn't have significant impact on
2000 // performance.
2001 if (OE.isAntiDep())
2002 continue;
2003
2004 int N = OE.getDst()->NodeNum;
2005 if (!Added.test(Idx: N)) {
2006 AdjK[i].push_back(Elt: N);
2007 Added.set(N);
2008 }
2009 }
2010 // A chain edge between a store and a load is treated as a back-edge in the
2011 // adjacency matrix.
2012 for (auto &IE : DAG->DDG->getInEdges(SU: &SUnits[i])) {
2013 SUnit *Src = IE.getSrc();
2014 SUnit *Dst = IE.getDst();
2015 if (!Dst->getInstr()->mayStore() || !DAG->isLoopCarriedDep(Edge: IE))
2016 continue;
2017 if (IE.isOrderDep() && Src->getInstr()->mayLoad()) {
2018 int N = Src->NodeNum;
2019 if (!Added.test(Idx: N)) {
2020 AdjK[i].push_back(Elt: N);
2021 Added.set(N);
2022 }
2023 }
2024 }
2025 }
2026 // Add back-edges in the adjacency matrix for the output dependences.
2027 for (auto &OD : OutputDeps)
2028 if (!Added.test(Idx: OD.second)) {
2029 AdjK[OD.first].push_back(Elt: OD.second);
2030 Added.set(OD.second);
2031 }
2032}
2033
2034/// Identify an elementary circuit in the dependence graph starting at the
2035/// specified node.
2036bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
2037 const SwingSchedulerDAG *DAG,
2038 bool HasBackedge) {
2039 SUnit *SV = &SUnits[V];
2040 bool F = false;
2041 Stack.insert(X: SV);
2042 Blocked.set(V);
2043
2044 for (auto W : AdjK[V]) {
2045 if (NumPaths > MaxPaths)
2046 break;
2047 if (W < S)
2048 continue;
2049 if (W == S) {
2050 if (!HasBackedge)
2051 NodeSets.push_back(Elt: NodeSet(Stack.begin(), Stack.end(), DAG));
2052 F = true;
2053 ++NumPaths;
2054 break;
2055 }
2056 if (!Blocked.test(Idx: W)) {
2057 if (circuit(V: W, S, NodeSets, DAG,
2058 HasBackedge: Node2Idx->at(n: W) < Node2Idx->at(n: V) ? true : HasBackedge))
2059 F = true;
2060 }
2061 }
2062
2063 if (F)
2064 unblock(U: V);
2065 else {
2066 for (auto W : AdjK[V]) {
2067 if (W < S)
2068 continue;
2069 B[W].insert(Ptr: SV);
2070 }
2071 }
2072 Stack.pop_back();
2073 return F;
2074}
2075
2076/// Unblock a node in the circuit finding algorithm.
2077void SwingSchedulerDAG::Circuits::unblock(int U) {
2078 Blocked.reset(Idx: U);
2079 SmallPtrSet<SUnit *, 4> &BU = B[U];
2080 while (!BU.empty()) {
2081 SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
2082 assert(SI != BU.end() && "Invalid B set.");
2083 SUnit *W = *SI;
2084 BU.erase(Ptr: W);
2085 if (Blocked.test(Idx: W->NodeNum))
2086 unblock(U: W->NodeNum);
2087 }
2088}
2089
2090/// Identify all the elementary circuits in the dependence graph using
2091/// Johnson's circuit algorithm.
2092void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
2093 Circuits Cir(SUnits, Topo);
2094 // Create the adjacency structure.
2095 Cir.createAdjacencyStructure(DAG: this);
2096 for (int I = 0, E = SUnits.size(); I != E; ++I) {
2097 Cir.reset();
2098 Cir.circuit(V: I, S: I, NodeSets, DAG: this);
2099 }
2100}
2101
2102// Create artificial dependencies between the source of COPY/REG_SEQUENCE that
2103// is loop-carried to the USE in next iteration. This will help pipeliner avoid
2104// additional copies that are needed across iterations. An artificial dependence
2105// edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
2106
2107// PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
2108// SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
2109// PHI-------True-Dep------> USEOfPhi
2110
2111// The mutation creates
2112// USEOfPHI -------Artificial-Dep---> SRCOfCopy
2113
2114// This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
2115// (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
2116// late to avoid additional copies across iterations. The possible scheduling
2117// order would be
2118// USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE.
2119
2120void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
2121 for (SUnit &SU : DAG->SUnits) {
2122 // Find the COPY/REG_SEQUENCE instruction.
2123 if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
2124 continue;
2125
2126 // Record the loop carried PHIs.
2127 SmallVector<SUnit *, 4> PHISUs;
2128 // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
2129 SmallVector<SUnit *, 4> SrcSUs;
2130
2131 for (auto &Dep : SU.Preds) {
2132 SUnit *TmpSU = Dep.getSUnit();
2133 MachineInstr *TmpMI = TmpSU->getInstr();
2134 SDep::Kind DepKind = Dep.getKind();
2135 // Save the loop carried PHI.
2136 if (DepKind == SDep::Anti && TmpMI->isPHI())
2137 PHISUs.push_back(Elt: TmpSU);
2138 // Save the source of COPY/REG_SEQUENCE.
2139 // If the source has no pre-decessors, we will end up creating cycles.
2140 else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
2141 SrcSUs.push_back(Elt: TmpSU);
2142 }
2143
2144 if (PHISUs.size() == 0 || SrcSUs.size() == 0)
2145 continue;
2146
2147 // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
2148 // SUnit to the container.
2149 SmallVector<SUnit *, 8> UseSUs;
2150 // Do not use iterator based loop here as we are updating the container.
2151 for (size_t Index = 0; Index < PHISUs.size(); ++Index) {
2152 for (auto &Dep : PHISUs[Index]->Succs) {
2153 if (Dep.getKind() != SDep::Data)
2154 continue;
2155
2156 SUnit *TmpSU = Dep.getSUnit();
2157 MachineInstr *TmpMI = TmpSU->getInstr();
2158 if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
2159 PHISUs.push_back(Elt: TmpSU);
2160 continue;
2161 }
2162 UseSUs.push_back(Elt: TmpSU);
2163 }
2164 }
2165
2166 if (UseSUs.size() == 0)
2167 continue;
2168
2169 SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(Val: DAG);
2170 // Add the artificial dependencies if it does not form a cycle.
2171 for (auto *I : UseSUs) {
2172 for (auto *Src : SrcSUs) {
2173 if (!SDAG->Topo.IsReachable(SU: I, TargetSU: Src) && Src != I) {
2174 Src->addPred(D: SDep(I, SDep::Artificial));
2175 SDAG->Topo.AddPred(Y: Src, X: I);
2176 }
2177 }
2178 }
2179 }
2180}
2181
2182/// Compute several functions need to order the nodes for scheduling.
2183/// ASAP - Earliest time to schedule a node.
2184/// ALAP - Latest time to schedule a node.
2185/// MOV - Mobility function, difference between ALAP and ASAP.
2186/// D - Depth of each node.
2187/// H - Height of each node.
2188void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
2189 ScheduleInfo.resize(new_size: SUnits.size());
2190
2191 LLVM_DEBUG({
2192 for (int I : Topo) {
2193 const SUnit &SU = SUnits[I];
2194 dumpNode(SU);
2195 }
2196 });
2197
2198 int maxASAP = 0;
2199 // Compute ASAP and ZeroLatencyDepth.
2200 for (int I : Topo) {
2201 int asap = 0;
2202 int zeroLatencyDepth = 0;
2203 SUnit *SU = &SUnits[I];
2204 for (const auto &IE : DDG->getInEdges(SU)) {
2205 SUnit *Pred = IE.getSrc();
2206 if (IE.getLatency() == 0)
2207 zeroLatencyDepth =
2208 std::max(a: zeroLatencyDepth, b: getZeroLatencyDepth(Node: Pred) + 1);
2209 if (IE.ignoreDependence(IgnoreAnti: true))
2210 continue;
2211 asap = std::max(a: asap, b: (int)(getASAP(Node: Pred) + IE.getLatency() -
2212 IE.getDistance() * MII));
2213 }
2214 maxASAP = std::max(a: maxASAP, b: asap);
2215 ScheduleInfo[I].ASAP = asap;
2216 ScheduleInfo[I].ZeroLatencyDepth = zeroLatencyDepth;
2217 }
2218
2219 // Compute ALAP, ZeroLatencyHeight, and MOV.
2220 for (int I : llvm::reverse(C&: Topo)) {
2221 int alap = maxASAP;
2222 int zeroLatencyHeight = 0;
2223 SUnit *SU = &SUnits[I];
2224 for (const auto &OE : DDG->getOutEdges(SU)) {
2225 SUnit *Succ = OE.getDst();
2226 if (Succ->isBoundaryNode())
2227 continue;
2228 if (OE.getLatency() == 0)
2229 zeroLatencyHeight =
2230 std::max(a: zeroLatencyHeight, b: getZeroLatencyHeight(Node: Succ) + 1);
2231 if (OE.ignoreDependence(IgnoreAnti: true))
2232 continue;
2233 alap = std::min(a: alap, b: (int)(getALAP(Node: Succ) - OE.getLatency() +
2234 OE.getDistance() * MII));
2235 }
2236
2237 ScheduleInfo[I].ALAP = alap;
2238 ScheduleInfo[I].ZeroLatencyHeight = zeroLatencyHeight;
2239 }
2240
2241 // After computing the node functions, compute the summary for each node set.
2242 for (NodeSet &I : NodeSets)
2243 I.computeNodeSetInfo(SSD: this);
2244
2245 LLVM_DEBUG({
2246 for (unsigned i = 0; i < SUnits.size(); i++) {
2247 dbgs() << "\tNode " << i << ":\n";
2248 dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n";
2249 dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n";
2250 dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n";
2251 dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n";
2252 dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n";
2253 dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
2254 dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
2255 }
2256 });
2257}
2258
2259/// Compute the Pred_L(O) set, as defined in the paper. The set is defined
2260/// as the predecessors of the elements of NodeOrder that are not also in
2261/// NodeOrder.
2262static bool pred_L(SetVector<SUnit *> &NodeOrder,
2263 SmallSetVector<SUnit *, 8> &Preds, SwingSchedulerDDG *DDG,
2264 const NodeSet *S = nullptr) {
2265 Preds.clear();
2266
2267 for (SUnit *SU : NodeOrder) {
2268 for (const auto &IE : DDG->getInEdges(SU)) {
2269 SUnit *PredSU = IE.getSrc();
2270 if (S && S->count(SU: PredSU) == 0)
2271 continue;
2272 if (IE.ignoreDependence(IgnoreAnti: true))
2273 continue;
2274 if (NodeOrder.count(key: PredSU) == 0)
2275 Preds.insert(X: PredSU);
2276 }
2277
2278 // FIXME: The following loop-carried dependencies may also need to be
2279 // considered.
2280 // - Physical register dependencies (true-dependence and WAW).
2281 // - Memory dependencies.
2282 for (const auto &OE : DDG->getOutEdges(SU)) {
2283 SUnit *SuccSU = OE.getDst();
2284 if (!OE.isAntiDep())
2285 continue;
2286 if (S && S->count(SU: SuccSU) == 0)
2287 continue;
2288 if (NodeOrder.count(key: SuccSU) == 0)
2289 Preds.insert(X: SuccSU);
2290 }
2291 }
2292 return !Preds.empty();
2293}
2294
2295/// Compute the Succ_L(O) set, as defined in the paper. The set is defined
2296/// as the successors of the elements of NodeOrder that are not also in
2297/// NodeOrder.
2298static bool succ_L(SetVector<SUnit *> &NodeOrder,
2299 SmallSetVector<SUnit *, 8> &Succs, SwingSchedulerDDG *DDG,
2300 const NodeSet *S = nullptr) {
2301 Succs.clear();
2302
2303 for (SUnit *SU : NodeOrder) {
2304 for (const auto &OE : DDG->getOutEdges(SU)) {
2305 SUnit *SuccSU = OE.getDst();
2306 if (S && S->count(SU: SuccSU) == 0)
2307 continue;
2308 if (OE.ignoreDependence(IgnoreAnti: false))
2309 continue;
2310 if (NodeOrder.count(key: SuccSU) == 0)
2311 Succs.insert(X: SuccSU);
2312 }
2313
2314 // FIXME: The following loop-carried dependencies may also need to be
2315 // considered.
2316 // - Physical register dependnecies (true-dependnece and WAW).
2317 // - Memory dependencies.
2318 for (const auto &IE : DDG->getInEdges(SU)) {
2319 SUnit *PredSU = IE.getSrc();
2320 if (!IE.isAntiDep())
2321 continue;
2322 if (S && S->count(SU: PredSU) == 0)
2323 continue;
2324 if (NodeOrder.count(key: PredSU) == 0)
2325 Succs.insert(X: PredSU);
2326 }
2327 }
2328 return !Succs.empty();
2329}
2330
2331/// Return true if there is a path from the specified node to any of the nodes
2332/// in DestNodes. Keep track and return the nodes in any path.
2333static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
2334 SetVector<SUnit *> &DestNodes,
2335 SetVector<SUnit *> &Exclude,
2336 SmallPtrSet<SUnit *, 8> &Visited,
2337 SwingSchedulerDDG *DDG) {
2338 if (Cur->isBoundaryNode())
2339 return false;
2340 if (Exclude.contains(key: Cur))
2341 return false;
2342 if (DestNodes.contains(key: Cur))
2343 return true;
2344 if (!Visited.insert(Ptr: Cur).second)
2345 return Path.contains(key: Cur);
2346 bool FoundPath = false;
2347 for (const auto &OE : DDG->getOutEdges(SU: Cur))
2348 if (!OE.ignoreDependence(IgnoreAnti: false))
2349 FoundPath |=
2350 computePath(Cur: OE.getDst(), Path, DestNodes, Exclude, Visited, DDG);
2351 for (const auto &IE : DDG->getInEdges(SU: Cur))
2352 if (IE.isAntiDep() && IE.getDistance() == 0)
2353 FoundPath |=
2354 computePath(Cur: IE.getSrc(), Path, DestNodes, Exclude, Visited, DDG);
2355 if (FoundPath)
2356 Path.insert(X: Cur);
2357 return FoundPath;
2358}
2359
2360/// Compute the live-out registers for the instructions in a node-set.
2361/// The live-out registers are those that are defined in the node-set,
2362/// but not used. Except for use operands of Phis.
2363static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
2364 NodeSet &NS) {
2365 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2366 MachineRegisterInfo &MRI = MF.getRegInfo();
2367 SmallVector<VRegMaskOrUnit, 8> LiveOutRegs;
2368 SmallSet<VirtRegOrUnit, 4> Uses;
2369 for (SUnit *SU : NS) {
2370 const MachineInstr *MI = SU->getInstr();
2371 if (MI->isPHI())
2372 continue;
2373 for (const MachineOperand &MO : MI->all_uses()) {
2374 Register Reg = MO.getReg();
2375 if (Reg.isVirtual())
2376 Uses.insert(V: VirtRegOrUnit(Reg));
2377 else if (MRI.isAllocatable(PhysReg: Reg))
2378 for (MCRegUnit Unit : TRI->regunits(Reg: Reg.asMCReg()))
2379 Uses.insert(V: VirtRegOrUnit(Unit));
2380 }
2381 }
2382 for (SUnit *SU : NS)
2383 for (const MachineOperand &MO : SU->getInstr()->all_defs())
2384 if (!MO.isDead()) {
2385 Register Reg = MO.getReg();
2386 if (Reg.isVirtual()) {
2387 if (!Uses.count(V: VirtRegOrUnit(Reg)))
2388 LiveOutRegs.emplace_back(Args: VirtRegOrUnit(Reg),
2389 Args: LaneBitmask::getNone());
2390 } else if (MRI.isAllocatable(PhysReg: Reg)) {
2391 for (MCRegUnit Unit : TRI->regunits(Reg: Reg.asMCReg()))
2392 if (!Uses.count(V: VirtRegOrUnit(Unit)))
2393 LiveOutRegs.emplace_back(Args: VirtRegOrUnit(Unit),
2394 Args: LaneBitmask::getNone());
2395 }
2396 }
2397 RPTracker.addLiveRegs(Regs: LiveOutRegs);
2398}
2399
2400/// A heuristic to filter nodes in recurrent node-sets if the register
2401/// pressure of a set is too high.
2402void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
2403 for (auto &NS : NodeSets) {
2404 // Skip small node-sets since they won't cause register pressure problems.
2405 if (NS.size() <= 2)
2406 continue;
2407 IntervalPressure RecRegPressure;
2408 RegPressureTracker RecRPTracker(RecRegPressure);
2409 RecRPTracker.init(mf: &MF, rci: &RegClassInfo, lis: &LIS, mbb: BB, pos: BB->end(), TrackLaneMasks: false, TrackUntiedDefs: true);
2410 computeLiveOuts(MF, RPTracker&: RecRPTracker, NS);
2411 RecRPTracker.closeBottom();
2412
2413 std::vector<SUnit *> SUnits(NS.begin(), NS.end());
2414 llvm::sort(C&: SUnits, Comp: [](const SUnit *A, const SUnit *B) {
2415 return A->NodeNum > B->NodeNum;
2416 });
2417
2418 for (auto &SU : SUnits) {
2419 // Since we're computing the register pressure for a subset of the
2420 // instructions in a block, we need to set the tracker for each
2421 // instruction in the node-set. The tracker is set to the instruction
2422 // just after the one we're interested in.
2423 MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
2424 RecRPTracker.setPos(std::next(x: CurInstI));
2425
2426 RegPressureDelta RPDelta;
2427 ArrayRef<PressureChange> CriticalPSets;
2428 RecRPTracker.getMaxUpwardPressureDelta(MI: SU->getInstr(), PDiff: nullptr, Delta&: RPDelta,
2429 CriticalPSets,
2430 MaxPressureLimit: RecRegPressure.MaxSetPressure);
2431 if (RPDelta.Excess.isValid()) {
2432 LLVM_DEBUG(
2433 dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
2434 << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
2435 << ":" << RPDelta.Excess.getUnitInc() << "\n");
2436 NS.setExceedPressure(SU);
2437 break;
2438 }
2439 RecRPTracker.recede();
2440 }
2441 }
2442}
2443
2444/// A heuristic to colocate node sets that have the same set of
2445/// successors.
2446void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
2447 unsigned Colocate = 0;
2448 for (int i = 0, e = NodeSets.size(); i < e; ++i) {
2449 NodeSet &N1 = NodeSets[i];
2450 SmallSetVector<SUnit *, 8> S1;
2451 if (N1.empty() || !succ_L(NodeOrder&: N1, Succs&: S1, DDG: DDG.get()))
2452 continue;
2453 for (int j = i + 1; j < e; ++j) {
2454 NodeSet &N2 = NodeSets[j];
2455 if (N1.compareRecMII(RHS&: N2) != 0)
2456 continue;
2457 SmallSetVector<SUnit *, 8> S2;
2458 if (N2.empty() || !succ_L(NodeOrder&: N2, Succs&: S2, DDG: DDG.get()))
2459 continue;
2460 if (llvm::set_is_subset(S1, S2) && S1.size() == S2.size()) {
2461 N1.setColocate(++Colocate);
2462 N2.setColocate(Colocate);
2463 break;
2464 }
2465 }
2466 }
2467}
2468
2469/// Check if the existing node-sets are profitable. If not, then ignore the
2470/// recurrent node-sets, and attempt to schedule all nodes together. This is
2471/// a heuristic. If the MII is large and all the recurrent node-sets are small,
2472/// then it's best to try to schedule all instructions together instead of
2473/// starting with the recurrent node-sets.
2474void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
2475 // Look for loops with a large MII.
2476 if (MII < 17)
2477 return;
2478 // Check if the node-set contains only a simple add recurrence.
2479 for (auto &NS : NodeSets) {
2480 if (NS.getRecMII() > 2)
2481 return;
2482 if (NS.getMaxDepth() > MII)
2483 return;
2484 }
2485 NodeSets.clear();
2486 LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
2487}
2488
2489/// Add the nodes that do not belong to a recurrence set into groups
2490/// based upon connected components.
2491void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
2492 SetVector<SUnit *> NodesAdded;
2493 SmallPtrSet<SUnit *, 8> Visited;
2494 // Add the nodes that are on a path between the previous node sets and
2495 // the current node set.
2496 for (NodeSet &I : NodeSets) {
2497 SmallSetVector<SUnit *, 8> N;
2498 // Add the nodes from the current node set to the previous node set.
2499 if (succ_L(NodeOrder&: I, Succs&: N, DDG: DDG.get())) {
2500 SetVector<SUnit *> Path;
2501 for (SUnit *NI : N) {
2502 Visited.clear();
2503 computePath(Cur: NI, Path, DestNodes&: NodesAdded, Exclude&: I, Visited, DDG: DDG.get());
2504 }
2505 if (!Path.empty())
2506 I.insert(S: Path.begin(), E: Path.end());
2507 }
2508 // Add the nodes from the previous node set to the current node set.
2509 N.clear();
2510 if (succ_L(NodeOrder&: NodesAdded, Succs&: N, DDG: DDG.get())) {
2511 SetVector<SUnit *> Path;
2512 for (SUnit *NI : N) {
2513 Visited.clear();
2514 computePath(Cur: NI, Path, DestNodes&: I, Exclude&: NodesAdded, Visited, DDG: DDG.get());
2515 }
2516 if (!Path.empty())
2517 I.insert(S: Path.begin(), E: Path.end());
2518 }
2519 NodesAdded.insert_range(R&: I);
2520 }
2521
2522 // Create a new node set with the connected nodes of any successor of a node
2523 // in a recurrent set.
2524 NodeSet NewSet;
2525 SmallSetVector<SUnit *, 8> N;
2526 if (succ_L(NodeOrder&: NodesAdded, Succs&: N, DDG: DDG.get()))
2527 for (SUnit *I : N)
2528 addConnectedNodes(SU: I, NewSet, NodesAdded);
2529 if (!NewSet.empty())
2530 NodeSets.push_back(Elt: NewSet);
2531
2532 // Create a new node set with the connected nodes of any predecessor of a node
2533 // in a recurrent set.
2534 NewSet.clear();
2535 if (pred_L(NodeOrder&: NodesAdded, Preds&: N, DDG: DDG.get()))
2536 for (SUnit *I : N)
2537 addConnectedNodes(SU: I, NewSet, NodesAdded);
2538 if (!NewSet.empty())
2539 NodeSets.push_back(Elt: NewSet);
2540
2541 // Create new nodes sets with the connected nodes any remaining node that
2542 // has no predecessor.
2543 for (SUnit &SU : SUnits) {
2544 if (NodesAdded.count(key: &SU) == 0) {
2545 NewSet.clear();
2546 addConnectedNodes(SU: &SU, NewSet, NodesAdded);
2547 if (!NewSet.empty())
2548 NodeSets.push_back(Elt: NewSet);
2549 }
2550 }
2551}
2552
2553/// Add the node to the set, and add all of its connected nodes to the set.
2554void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
2555 SetVector<SUnit *> &NodesAdded) {
2556 NewSet.insert(SU);
2557 NodesAdded.insert(X: SU);
2558 for (auto &OE : DDG->getOutEdges(SU)) {
2559 SUnit *Successor = OE.getDst();
2560 if (!OE.isArtificial() && !Successor->isBoundaryNode() &&
2561 NodesAdded.count(key: Successor) == 0)
2562 addConnectedNodes(SU: Successor, NewSet, NodesAdded);
2563 }
2564 for (auto &IE : DDG->getInEdges(SU)) {
2565 SUnit *Predecessor = IE.getSrc();
2566 if (!IE.isArtificial() && NodesAdded.count(key: Predecessor) == 0)
2567 addConnectedNodes(SU: Predecessor, NewSet, NodesAdded);
2568 }
2569}
2570
2571/// Return true if Set1 contains elements in Set2. The elements in common
2572/// are returned in a different container.
2573static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
2574 SmallSetVector<SUnit *, 8> &Result) {
2575 Result.clear();
2576 for (SUnit *SU : Set1) {
2577 if (Set2.count(SU) != 0)
2578 Result.insert(X: SU);
2579 }
2580 return !Result.empty();
2581}
2582
2583/// Merge the recurrence node sets that have the same initial node.
2584void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
2585 for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
2586 ++I) {
2587 NodeSet &NI = *I;
2588 for (NodeSetType::iterator J = I + 1; J != E;) {
2589 NodeSet &NJ = *J;
2590 if (NI.getNode(i: 0)->NodeNum == NJ.getNode(i: 0)->NodeNum) {
2591 if (NJ.compareRecMII(RHS&: NI) > 0)
2592 NI.setRecMII(NJ.getRecMII());
2593 for (SUnit *SU : *J)
2594 I->insert(SU);
2595 NodeSets.erase(CI: J);
2596 E = NodeSets.end();
2597 } else {
2598 ++J;
2599 }
2600 }
2601 }
2602}
2603
2604/// Remove nodes that have been scheduled in previous NodeSets.
2605void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
2606 for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
2607 ++I)
2608 for (NodeSetType::iterator J = I + 1; J != E;) {
2609 J->remove_if(P: [&](SUnit *SUJ) { return I->count(SU: SUJ); });
2610
2611 if (J->empty()) {
2612 NodeSets.erase(CI: J);
2613 E = NodeSets.end();
2614 } else {
2615 ++J;
2616 }
2617 }
2618}
2619
2620/// Compute an ordered list of the dependence graph nodes, which
2621/// indicates the order that the nodes will be scheduled. This is a
2622/// two-level algorithm. First, a partial order is created, which
2623/// consists of a list of sets ordered from highest to lowest priority.
2624void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
2625 SmallSetVector<SUnit *, 8> R;
2626 NodeOrder.clear();
2627
2628 for (auto &Nodes : NodeSets) {
2629 LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
2630 OrderKind Order;
2631 SmallSetVector<SUnit *, 8> N;
2632 if (pred_L(NodeOrder, Preds&: N, DDG: DDG.get()) && llvm::set_is_subset(S1: N, S2: Nodes)) {
2633 R.insert_range(R&: N);
2634 Order = BottomUp;
2635 LLVM_DEBUG(dbgs() << " Bottom up (preds) ");
2636 } else if (succ_L(NodeOrder, Succs&: N, DDG: DDG.get()) &&
2637 llvm::set_is_subset(S1: N, S2: Nodes)) {
2638 R.insert_range(R&: N);
2639 Order = TopDown;
2640 LLVM_DEBUG(dbgs() << " Top down (succs) ");
2641 } else if (isIntersect(Set1&: N, Set2: Nodes, Result&: R)) {
2642 // If some of the successors are in the existing node-set, then use the
2643 // top-down ordering.
2644 Order = TopDown;
2645 LLVM_DEBUG(dbgs() << " Top down (intersect) ");
2646 } else if (NodeSets.size() == 1) {
2647 for (const auto &N : Nodes)
2648 if (N->Succs.size() == 0)
2649 R.insert(X: N);
2650 Order = BottomUp;
2651 LLVM_DEBUG(dbgs() << " Bottom up (all) ");
2652 } else {
2653 // Find the node with the highest ASAP.
2654 SUnit *maxASAP = nullptr;
2655 for (SUnit *SU : Nodes) {
2656 if (maxASAP == nullptr || getASAP(Node: SU) > getASAP(Node: maxASAP) ||
2657 (getASAP(Node: SU) == getASAP(Node: maxASAP) && SU->NodeNum > maxASAP->NodeNum))
2658 maxASAP = SU;
2659 }
2660 R.insert(X: maxASAP);
2661 Order = BottomUp;
2662 LLVM_DEBUG(dbgs() << " Bottom up (default) ");
2663 }
2664
2665 while (!R.empty()) {
2666 if (Order == TopDown) {
2667 // Choose the node with the maximum height. If more than one, choose
2668 // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
2669 // choose the node with the lowest MOV.
2670 while (!R.empty()) {
2671 SUnit *maxHeight = nullptr;
2672 for (SUnit *I : R) {
2673 if (maxHeight == nullptr || getHeight(Node: I) > getHeight(Node: maxHeight))
2674 maxHeight = I;
2675 else if (getHeight(Node: I) == getHeight(Node: maxHeight) &&
2676 getZeroLatencyHeight(Node: I) > getZeroLatencyHeight(Node: maxHeight))
2677 maxHeight = I;
2678 else if (getHeight(Node: I) == getHeight(Node: maxHeight) &&
2679 getZeroLatencyHeight(Node: I) ==
2680 getZeroLatencyHeight(Node: maxHeight) &&
2681 getMOV(Node: I) < getMOV(Node: maxHeight))
2682 maxHeight = I;
2683 }
2684 NodeOrder.insert(X: maxHeight);
2685 LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
2686 R.remove(X: maxHeight);
2687 for (const auto &OE : DDG->getOutEdges(SU: maxHeight)) {
2688 SUnit *SU = OE.getDst();
2689 if (Nodes.count(SU) == 0)
2690 continue;
2691 if (NodeOrder.contains(key: SU))
2692 continue;
2693 if (OE.ignoreDependence(IgnoreAnti: false))
2694 continue;
2695 R.insert(X: SU);
2696 }
2697
2698 // FIXME: The following loop-carried dependencies may also need to be
2699 // considered.
2700 // - Physical register dependnecies (true-dependnece and WAW).
2701 // - Memory dependencies.
2702 for (const auto &IE : DDG->getInEdges(SU: maxHeight)) {
2703 SUnit *SU = IE.getSrc();
2704 if (!IE.isAntiDep())
2705 continue;
2706 if (Nodes.count(SU) == 0)
2707 continue;
2708 if (NodeOrder.contains(key: SU))
2709 continue;
2710 R.insert(X: SU);
2711 }
2712 }
2713 Order = BottomUp;
2714 LLVM_DEBUG(dbgs() << "\n Switching order to bottom up ");
2715 SmallSetVector<SUnit *, 8> N;
2716 if (pred_L(NodeOrder, Preds&: N, DDG: DDG.get(), S: &Nodes))
2717 R.insert_range(R&: N);
2718 } else {
2719 // Choose the node with the maximum depth. If more than one, choose
2720 // the node with the maximum ZeroLatencyDepth. If still more than one,
2721 // choose the node with the lowest MOV.
2722 while (!R.empty()) {
2723 SUnit *maxDepth = nullptr;
2724 for (SUnit *I : R) {
2725 if (maxDepth == nullptr || getDepth(Node: I) > getDepth(Node: maxDepth))
2726 maxDepth = I;
2727 else if (getDepth(Node: I) == getDepth(Node: maxDepth) &&
2728 getZeroLatencyDepth(Node: I) > getZeroLatencyDepth(Node: maxDepth))
2729 maxDepth = I;
2730 else if (getDepth(Node: I) == getDepth(Node: maxDepth) &&
2731 getZeroLatencyDepth(Node: I) == getZeroLatencyDepth(Node: maxDepth) &&
2732 getMOV(Node: I) < getMOV(Node: maxDepth))
2733 maxDepth = I;
2734 }
2735 NodeOrder.insert(X: maxDepth);
2736 LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
2737 R.remove(X: maxDepth);
2738 if (Nodes.isExceedSU(SU: maxDepth)) {
2739 Order = TopDown;
2740 R.clear();
2741 R.insert(X: Nodes.getNode(i: 0));
2742 break;
2743 }
2744 for (const auto &IE : DDG->getInEdges(SU: maxDepth)) {
2745 SUnit *SU = IE.getSrc();
2746 if (Nodes.count(SU) == 0)
2747 continue;
2748 if (NodeOrder.contains(key: SU))
2749 continue;
2750 R.insert(X: SU);
2751 }
2752
2753 // FIXME: The following loop-carried dependencies may also need to be
2754 // considered.
2755 // - Physical register dependnecies (true-dependnece and WAW).
2756 // - Memory dependencies.
2757 for (const auto &OE : DDG->getOutEdges(SU: maxDepth)) {
2758 SUnit *SU = OE.getDst();
2759 if (!OE.isAntiDep())
2760 continue;
2761 if (Nodes.count(SU) == 0)
2762 continue;
2763 if (NodeOrder.contains(key: SU))
2764 continue;
2765 R.insert(X: SU);
2766 }
2767 }
2768 Order = TopDown;
2769 LLVM_DEBUG(dbgs() << "\n Switching order to top down ");
2770 SmallSetVector<SUnit *, 8> N;
2771 if (succ_L(NodeOrder, Succs&: N, DDG: DDG.get(), S: &Nodes))
2772 R.insert_range(R&: N);
2773 }
2774 }
2775 LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
2776 }
2777
2778 LLVM_DEBUG({
2779 dbgs() << "Node order: ";
2780 for (SUnit *I : NodeOrder)
2781 dbgs() << " " << I->NodeNum << " ";
2782 dbgs() << "\n";
2783 });
2784}
2785
2786/// Process the nodes in the computed order and create the pipelined schedule
2787/// of the instructions, if possible. Return true if a schedule is found.
2788bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
2789
2790 if (NodeOrder.empty()){
2791 LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
2792 return false;
2793 }
2794
2795 bool scheduleFound = false;
2796 std::unique_ptr<HighRegisterPressureDetector> HRPDetector;
2797 if (LimitRegPressure) {
2798 HRPDetector =
2799 std::make_unique<HighRegisterPressureDetector>(args: Loop.getHeader(), args&: MF);
2800 HRPDetector->init(RCI: RegClassInfo);
2801 }
2802 // Keep increasing II until a valid schedule is found.
2803 for (unsigned II = MII; II <= MAX_II && !scheduleFound; ++II) {
2804 Schedule.reset();
2805 Schedule.setInitiationInterval(II);
2806 LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
2807
2808 SetVector<SUnit *>::iterator NI = NodeOrder.begin();
2809 SetVector<SUnit *>::iterator NE = NodeOrder.end();
2810 do {
2811 SUnit *SU = *NI;
2812
2813 // Compute the schedule time for the instruction, which is based
2814 // upon the scheduled time for any predecessors/successors.
2815 int EarlyStart = INT_MIN;
2816 int LateStart = INT_MAX;
2817 Schedule.computeStart(SU, MaxEarlyStart: &EarlyStart, MinLateStart: &LateStart, II, DAG: this);
2818 LLVM_DEBUG({
2819 dbgs() << "\n";
2820 dbgs() << "Inst (" << SU->NodeNum << ") ";
2821 SU->getInstr()->dump();
2822 dbgs() << "\n";
2823 });
2824 LLVM_DEBUG(
2825 dbgs() << format("\tes: %8x ls: %8x\n", EarlyStart, LateStart));
2826
2827 if (EarlyStart > LateStart)
2828 scheduleFound = false;
2829 else if (EarlyStart != INT_MIN && LateStart == INT_MAX)
2830 scheduleFound =
2831 Schedule.insert(SU, StartCycle: EarlyStart, EndCycle: EarlyStart + (int)II - 1, II);
2832 else if (EarlyStart == INT_MIN && LateStart != INT_MAX)
2833 scheduleFound =
2834 Schedule.insert(SU, StartCycle: LateStart, EndCycle: LateStart - (int)II + 1, II);
2835 else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
2836 LateStart = std::min(a: LateStart, b: EarlyStart + (int)II - 1);
2837 // When scheduling a Phi it is better to start at the late cycle and
2838 // go backwards. The default order may insert the Phi too far away
2839 // from its first dependence.
2840 // Also, do backward search when all scheduled predecessors are
2841 // loop-carried output/order dependencies. Empirically, there are also
2842 // cases where scheduling becomes possible with backward search.
2843 if (SU->getInstr()->isPHI() ||
2844 Schedule.onlyHasLoopCarriedOutputOrOrderPreds(SU, DDG: this->getDDG()))
2845 scheduleFound = Schedule.insert(SU, StartCycle: LateStart, EndCycle: EarlyStart, II);
2846 else
2847 scheduleFound = Schedule.insert(SU, StartCycle: EarlyStart, EndCycle: LateStart, II);
2848 } else {
2849 int FirstCycle = Schedule.getFirstCycle();
2850 scheduleFound = Schedule.insert(SU, StartCycle: FirstCycle + getASAP(Node: SU),
2851 EndCycle: FirstCycle + getASAP(Node: SU) + II - 1, II);
2852 }
2853
2854 // Even if we find a schedule, make sure the schedule doesn't exceed the
2855 // allowable number of stages. We keep trying if this happens.
2856 if (scheduleFound)
2857 if (SwpMaxStages > -1 &&
2858 Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
2859 scheduleFound = false;
2860
2861 LLVM_DEBUG({
2862 if (!scheduleFound)
2863 dbgs() << "\tCan't schedule\n";
2864 });
2865 } while (++NI != NE && scheduleFound);
2866
2867 // If a schedule is found, validate it against the validation-only
2868 // dependencies.
2869 if (scheduleFound)
2870 scheduleFound = DDG->isValidSchedule(Schedule);
2871
2872 // If a schedule is found, ensure non-pipelined instructions are in stage 0
2873 if (scheduleFound)
2874 scheduleFound =
2875 Schedule.normalizeNonPipelinedInstructions(SSD: this, PLI: LoopPipelinerInfo);
2876
2877 // If a schedule is found, check if it is a valid schedule too.
2878 if (scheduleFound)
2879 scheduleFound = Schedule.isValidSchedule(SSD: this);
2880
2881 // If a schedule was found and the option is enabled, check if the schedule
2882 // might generate additional register spills/fills.
2883 if (scheduleFound && LimitRegPressure)
2884 scheduleFound =
2885 !HRPDetector->detect(SSD: this, Schedule, MaxStage: Schedule.getMaxStageCount());
2886 }
2887
2888 LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound
2889 << " (II=" << Schedule.getInitiationInterval()
2890 << ")\n");
2891
2892 if (scheduleFound) {
2893 scheduleFound = LoopPipelinerInfo->shouldUseSchedule(SSD&: *this, SMS&: Schedule);
2894 if (!scheduleFound)
2895 LLVM_DEBUG(dbgs() << "Target rejected schedule\n");
2896 }
2897
2898 if (scheduleFound) {
2899 Schedule.finalizeSchedule(SSD: this);
2900 Pass.ORE->emit(RemarkBuilder: [&]() {
2901 return MachineOptimizationRemarkAnalysis(
2902 DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
2903 << "Schedule found with Initiation Interval: "
2904 << ore::NV("II", Schedule.getInitiationInterval())
2905 << ", MaxStageCount: "
2906 << ore::NV("MaxStageCount", Schedule.getMaxStageCount());
2907 });
2908 } else
2909 Schedule.reset();
2910
2911 return scheduleFound && Schedule.getMaxStageCount() > 0;
2912}
2913
2914static Register findUniqueOperandDefinedInLoop(const MachineInstr &MI) {
2915 const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2916 Register Result;
2917 for (const MachineOperand &Use : MI.all_uses()) {
2918 Register Reg = Use.getReg();
2919 if (!Reg.isVirtual())
2920 return Register();
2921 if (MRI.getVRegDef(Reg)->getParent() != MI.getParent())
2922 continue;
2923 if (Result)
2924 return Register();
2925 Result = Reg;
2926 }
2927 return Result;
2928}
2929
2930/// When Op is a value that is incremented recursively in a loop and there is a
2931/// unique instruction that increments it, returns true and sets Value.
2932static bool findLoopIncrementValue(const MachineOperand &Op, int &Value) {
2933 if (!Op.isReg() || !Op.getReg().isVirtual())
2934 return false;
2935
2936 Register OrgReg = Op.getReg();
2937 Register CurReg = OrgReg;
2938 const MachineBasicBlock *LoopBB = Op.getParent()->getParent();
2939 const MachineRegisterInfo &MRI = LoopBB->getParent()->getRegInfo();
2940
2941 const TargetInstrInfo *TII =
2942 LoopBB->getParent()->getSubtarget().getInstrInfo();
2943 const TargetRegisterInfo *TRI =
2944 LoopBB->getParent()->getSubtarget().getRegisterInfo();
2945
2946 MachineInstr *Phi = nullptr;
2947 MachineInstr *Increment = nullptr;
2948
2949 // Traverse definitions until it reaches Op or an instruction that does not
2950 // satisfy the condition.
2951 // Acceptable example:
2952 // bb.0:
2953 // %0 = PHI %3, %bb.0, ...
2954 // %2 = ADD %0, Value
2955 // ... = LOAD %2(Op)
2956 // %3 = COPY %2
2957 while (true) {
2958 if (!CurReg.isValid() || !CurReg.isVirtual())
2959 return false;
2960 MachineInstr *Def = MRI.getVRegDef(Reg: CurReg);
2961 if (Def->getParent() != LoopBB)
2962 return false;
2963
2964 if (Def->isCopy()) {
2965 // Ignore copy instructions unless they contain subregisters
2966 if (Def->getOperand(i: 0).getSubReg() || Def->getOperand(i: 1).getSubReg())
2967 return false;
2968 CurReg = Def->getOperand(i: 1).getReg();
2969 } else if (Def->isPHI()) {
2970 // There must be just one Phi
2971 if (Phi)
2972 return false;
2973 Phi = Def;
2974 CurReg = getLoopPhiReg(Phi: *Def, LoopBB);
2975 } else if (TII->getIncrementValue(MI: *Def, Value)) {
2976 // Potentially a unique increment
2977 if (Increment)
2978 // Multiple increments exist
2979 return false;
2980
2981 const MachineOperand *BaseOp;
2982 int64_t Offset;
2983 bool OffsetIsScalable;
2984 if (TII->getMemOperandWithOffset(MI: *Def, BaseOp, Offset, OffsetIsScalable,
2985 TRI)) {
2986 // Pre/post increment instruction
2987 CurReg = BaseOp->getReg();
2988 } else {
2989 // If only one of the operands is defined within the loop, it is assumed
2990 // to be an incremented value.
2991 CurReg = findUniqueOperandDefinedInLoop(MI: *Def);
2992 if (!CurReg.isValid())
2993 return false;
2994 }
2995 Increment = Def;
2996 } else {
2997 return false;
2998 }
2999 if (CurReg == OrgReg)
3000 break;
3001 }
3002
3003 if (!Phi || !Increment)
3004 return false;
3005
3006 return true;
3007}
3008
3009/// Return true if we can compute the amount the instruction changes
3010/// during each iteration. Set Delta to the amount of the change.
3011bool SwingSchedulerDAG::computeDelta(const MachineInstr &MI, int &Delta) const {
3012 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3013 const MachineOperand *BaseOp;
3014 int64_t Offset;
3015 bool OffsetIsScalable;
3016 if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
3017 return false;
3018
3019 // FIXME: This algorithm assumes instructions have fixed-size offsets.
3020 if (OffsetIsScalable)
3021 return false;
3022
3023 if (!BaseOp->isReg())
3024 return false;
3025
3026 return findLoopIncrementValue(Op: *BaseOp, Value&: Delta);
3027}
3028
3029/// Check if we can change the instruction to use an offset value from the
3030/// previous iteration. If so, return true and set the base and offset values
3031/// so that we can rewrite the load, if necessary.
3032/// v1 = Phi(v0, v3)
3033/// v2 = load v1, 0
3034/// v3 = post_store v1, 4, x
3035/// This function enables the load to be rewritten as v2 = load v3, 4.
3036bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
3037 unsigned &BasePos,
3038 unsigned &OffsetPos,
3039 Register &NewBase,
3040 int64_t &Offset) {
3041 // Get the load instruction.
3042 if (TII->isPostIncrement(MI: *MI))
3043 return false;
3044 unsigned BasePosLd, OffsetPosLd;
3045 if (!TII->getBaseAndOffsetPosition(MI: *MI, BasePos&: BasePosLd, OffsetPos&: OffsetPosLd))
3046 return false;
3047 Register BaseReg = MI->getOperand(i: BasePosLd).getReg();
3048
3049 // Look for the Phi instruction.
3050 MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
3051 MachineInstr *Phi = MRI.getVRegDef(Reg: BaseReg);
3052 if (!Phi || !Phi->isPHI())
3053 return false;
3054 // Get the register defined in the loop block.
3055 Register PrevReg = getLoopPhiReg(Phi: *Phi, LoopBB: MI->getParent());
3056 if (!PrevReg)
3057 return false;
3058
3059 // Check for the post-increment load/store instruction.
3060 MachineInstr *PrevDef = MRI.getVRegDef(Reg: PrevReg);
3061 if (!PrevDef || PrevDef == MI)
3062 return false;
3063
3064 if (!TII->isPostIncrement(MI: *PrevDef))
3065 return false;
3066
3067 unsigned BasePos1 = 0, OffsetPos1 = 0;
3068 if (!TII->getBaseAndOffsetPosition(MI: *PrevDef, BasePos&: BasePos1, OffsetPos&: OffsetPos1))
3069 return false;
3070
3071 // Make sure that the instructions do not access the same memory location in
3072 // the next iteration.
3073 int64_t LoadOffset = MI->getOperand(i: OffsetPosLd).getImm();
3074 int64_t StoreOffset = PrevDef->getOperand(i: OffsetPos1).getImm();
3075 MachineInstr *NewMI = MF.CloneMachineInstr(Orig: MI);
3076 NewMI->getOperand(i: OffsetPosLd).setImm(LoadOffset + StoreOffset);
3077 bool Disjoint = TII->areMemAccessesTriviallyDisjoint(MIa: *NewMI, MIb: *PrevDef);
3078 MF.deleteMachineInstr(MI: NewMI);
3079 if (!Disjoint)
3080 return false;
3081
3082 // Set the return value once we determine that we return true.
3083 BasePos = BasePosLd;
3084 OffsetPos = OffsetPosLd;
3085 NewBase = PrevReg;
3086 Offset = StoreOffset;
3087 return true;
3088}
3089
3090/// Apply changes to the instruction if needed. The changes are need
3091/// to improve the scheduling and depend up on the final schedule.
3092void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
3093 SMSchedule &Schedule) {
3094 SUnit *SU = getSUnit(MI);
3095 DenseMap<SUnit *, std::pair<Register, int64_t>>::iterator It =
3096 InstrChanges.find(Val: SU);
3097 if (It != InstrChanges.end()) {
3098 std::pair<Register, int64_t> RegAndOffset = It->second;
3099 unsigned BasePos, OffsetPos;
3100 if (!TII->getBaseAndOffsetPosition(MI: *MI, BasePos, OffsetPos))
3101 return;
3102 Register BaseReg = MI->getOperand(i: BasePos).getReg();
3103 MachineInstr *LoopDef = findDefInLoop(Reg: BaseReg);
3104 int DefStageNum = Schedule.stageScheduled(SU: getSUnit(MI: LoopDef));
3105 int DefCycleNum = Schedule.cycleScheduled(SU: getSUnit(MI: LoopDef));
3106 int BaseStageNum = Schedule.stageScheduled(SU);
3107 int BaseCycleNum = Schedule.cycleScheduled(SU);
3108 if (BaseStageNum < DefStageNum) {
3109 MachineInstr *NewMI = MF.CloneMachineInstr(Orig: MI);
3110 int OffsetDiff = DefStageNum - BaseStageNum;
3111 if (DefCycleNum < BaseCycleNum) {
3112 NewMI->getOperand(i: BasePos).setReg(RegAndOffset.first);
3113 if (OffsetDiff > 0)
3114 --OffsetDiff;
3115 }
3116 int64_t NewOffset =
3117 MI->getOperand(i: OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
3118 NewMI->getOperand(i: OffsetPos).setImm(NewOffset);
3119 SU->setInstr(NewMI);
3120 MISUnitMap[NewMI] = SU;
3121 NewMIs[MI] = NewMI;
3122 }
3123 }
3124}
3125
3126/// Return the instruction in the loop that defines the register.
3127/// If the definition is a Phi, then follow the Phi operand to
3128/// the instruction in the loop.
3129MachineInstr *SwingSchedulerDAG::findDefInLoop(Register Reg) {
3130 SmallPtrSet<MachineInstr *, 8> Visited;
3131 MachineInstr *Def = MRI.getVRegDef(Reg);
3132 while (Def->isPHI()) {
3133 if (!Visited.insert(Ptr: Def).second)
3134 break;
3135 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
3136 if (Def->getOperand(i: i + 1).getMBB() == BB) {
3137 Def = MRI.getVRegDef(Reg: Def->getOperand(i).getReg());
3138 break;
3139 }
3140 }
3141 return Def;
3142}
3143
3144/// Return false if there is no overlap between the region accessed by BaseMI in
3145/// an iteration and the region accessed by OtherMI in subsequent iterations.
3146bool SwingSchedulerDAG::mayOverlapInLaterIter(
3147 const MachineInstr *BaseMI, const MachineInstr *OtherMI) const {
3148 int DeltaB, DeltaO, Delta;
3149 if (!computeDelta(MI: *BaseMI, Delta&: DeltaB) || !computeDelta(MI: *OtherMI, Delta&: DeltaO) ||
3150 DeltaB != DeltaO)
3151 return true;
3152 Delta = DeltaB;
3153
3154 const MachineOperand *BaseOpB, *BaseOpO;
3155 int64_t OffsetB, OffsetO;
3156 bool OffsetBIsScalable, OffsetOIsScalable;
3157 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3158 if (!TII->getMemOperandWithOffset(MI: *BaseMI, BaseOp&: BaseOpB, Offset&: OffsetB,
3159 OffsetIsScalable&: OffsetBIsScalable, TRI) ||
3160 !TII->getMemOperandWithOffset(MI: *OtherMI, BaseOp&: BaseOpO, Offset&: OffsetO,
3161 OffsetIsScalable&: OffsetOIsScalable, TRI))
3162 return true;
3163
3164 if (OffsetBIsScalable || OffsetOIsScalable)
3165 return true;
3166
3167 if (!BaseOpB->isIdenticalTo(Other: *BaseOpO)) {
3168 // Pass cases with different base operands but same initial values.
3169 // Typically for when pre/post increment is used.
3170
3171 if (!BaseOpB->isReg() || !BaseOpO->isReg())
3172 return true;
3173 Register RegB = BaseOpB->getReg(), RegO = BaseOpO->getReg();
3174 if (!RegB.isVirtual() || !RegO.isVirtual())
3175 return true;
3176
3177 MachineInstr *DefB = MRI.getVRegDef(Reg: BaseOpB->getReg());
3178 MachineInstr *DefO = MRI.getVRegDef(Reg: BaseOpO->getReg());
3179 if (!DefB || !DefO || !DefB->isPHI() || !DefO->isPHI())
3180 return true;
3181
3182 Register InitValB;
3183 Register LoopValB;
3184 Register InitValO;
3185 Register LoopValO;
3186 getPhiRegs(Phi&: *DefB, Loop: BB, InitVal&: InitValB, LoopVal&: LoopValB);
3187 getPhiRegs(Phi&: *DefO, Loop: BB, InitVal&: InitValO, LoopVal&: LoopValO);
3188 MachineInstr *InitDefB = MRI.getVRegDef(Reg: InitValB);
3189 MachineInstr *InitDefO = MRI.getVRegDef(Reg: InitValO);
3190
3191 if (!InitDefB->isIdenticalTo(Other: *InitDefO))
3192 return true;
3193 }
3194
3195 LocationSize AccessSizeB = (*BaseMI->memoperands_begin())->getSize();
3196 LocationSize AccessSizeO = (*OtherMI->memoperands_begin())->getSize();
3197
3198 // This is the main test, which checks the offset values and the loop
3199 // increment value to determine if the accesses may be loop carried.
3200 if (!AccessSizeB.hasValue() || !AccessSizeO.hasValue())
3201 return true;
3202
3203 LLVM_DEBUG({
3204 dbgs() << "Overlap check:\n";
3205 dbgs() << " BaseMI: ";
3206 BaseMI->dump();
3207 dbgs() << " Base + " << OffsetB << " + I * " << Delta
3208 << ", Len: " << AccessSizeB.getValue() << "\n";
3209 dbgs() << " OtherMI: ";
3210 OtherMI->dump();
3211 dbgs() << " Base + " << OffsetO << " + I * " << Delta
3212 << ", Len: " << AccessSizeO.getValue() << "\n";
3213 });
3214
3215 // Excessive overlap may be detected in strided patterns.
3216 // For example, the memory addresses of the store and the load in
3217 // for (i=0; i<n; i+=2) a[i+1] = a[i];
3218 // are assumed to overlap.
3219 if (Delta < 0) {
3220 int64_t BaseMinAddr = OffsetB;
3221 int64_t OhterNextIterMaxAddr = OffsetO + Delta + AccessSizeO.getValue() - 1;
3222 if (BaseMinAddr > OhterNextIterMaxAddr) {
3223 LLVM_DEBUG(dbgs() << " Result: No overlap\n");
3224 return false;
3225 }
3226 } else {
3227 int64_t BaseMaxAddr = OffsetB + AccessSizeB.getValue() - 1;
3228 int64_t OtherNextIterMinAddr = OffsetO + Delta;
3229 if (BaseMaxAddr < OtherNextIterMinAddr) {
3230 LLVM_DEBUG(dbgs() << " Result: No overlap\n");
3231 return false;
3232 }
3233 }
3234 LLVM_DEBUG(dbgs() << " Result: Overlap\n");
3235 return true;
3236}
3237
3238/// Return true for an order or output dependence that is loop carried
3239/// potentially. A dependence is loop carried if the destination defines a value
3240/// that may be used or defined by the source in a subsequent iteration.
3241bool SwingSchedulerDAG::isLoopCarriedDep(
3242 const SwingSchedulerDDGEdge &Edge) const {
3243 if ((!Edge.isOrderDep() && !Edge.isOutputDep()) || Edge.isArtificial() ||
3244 Edge.getDst()->isBoundaryNode())
3245 return false;
3246
3247 if (!SwpPruneLoopCarried)
3248 return true;
3249
3250 if (Edge.isOutputDep())
3251 return true;
3252
3253 MachineInstr *SI = Edge.getSrc()->getInstr();
3254 MachineInstr *DI = Edge.getDst()->getInstr();
3255 assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
3256
3257 // Assume ordered loads and stores may have a loop carried dependence.
3258 if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
3259 SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
3260 SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
3261 return true;
3262
3263 if (!DI->mayLoadOrStore() || !SI->mayLoadOrStore())
3264 return false;
3265
3266 // The conservative assumption is that a dependence between memory operations
3267 // may be loop carried. The following code checks when it can be proved that
3268 // there is no loop carried dependence.
3269 return mayOverlapInLaterIter(BaseMI: DI, OtherMI: SI);
3270}
3271
3272void SwingSchedulerDAG::postProcessDAG() {
3273 for (auto &M : Mutations)
3274 M->apply(DAG: this);
3275}
3276
3277/// Try to schedule the node at the specified StartCycle and continue
3278/// until the node is schedule or the EndCycle is reached. This function
3279/// returns true if the node is scheduled. This routine may search either
3280/// forward or backward for a place to insert the instruction based upon
3281/// the relative values of StartCycle and EndCycle.
3282bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
3283 bool forward = true;
3284 LLVM_DEBUG({
3285 dbgs() << "Trying to insert node between " << StartCycle << " and "
3286 << EndCycle << " II: " << II << "\n";
3287 });
3288 if (StartCycle > EndCycle)
3289 forward = false;
3290
3291 // The terminating condition depends on the direction.
3292 int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
3293 for (int curCycle = StartCycle; curCycle != termCycle;
3294 forward ? ++curCycle : --curCycle) {
3295
3296 if (ST.getInstrInfo()->isZeroCost(Opcode: SU->getInstr()->getOpcode()) ||
3297 ProcItinResources.canReserveResources(SU&: *SU, Cycle: curCycle)) {
3298 LLVM_DEBUG({
3299 dbgs() << "\tinsert at cycle " << curCycle << " ";
3300 SU->getInstr()->dump();
3301 });
3302
3303 if (!ST.getInstrInfo()->isZeroCost(Opcode: SU->getInstr()->getOpcode()))
3304 ProcItinResources.reserveResources(SU&: *SU, Cycle: curCycle);
3305 ScheduledInstrs[curCycle].push_back(x: SU);
3306 InstrToCycle.insert(x: std::make_pair(x&: SU, y&: curCycle));
3307 if (curCycle > LastCycle)
3308 LastCycle = curCycle;
3309 if (curCycle < FirstCycle)
3310 FirstCycle = curCycle;
3311 return true;
3312 }
3313 LLVM_DEBUG({
3314 dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
3315 SU->getInstr()->dump();
3316 });
3317 }
3318 return false;
3319}
3320
3321/// If an instruction has a use that spans multiple iterations, then
3322/// return true. These instructions are characterized by having a back-ege
3323/// to a Phi, which contains a reference to another Phi.
3324static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
3325 for (auto &P : SU->Preds)
3326 if (P.getKind() == SDep::Anti && P.getSUnit()->getInstr()->isPHI())
3327 for (auto &S : P.getSUnit()->Succs)
3328 if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
3329 return P.getSUnit();
3330 return nullptr;
3331}
3332
3333/// Compute the scheduling start slot for the instruction. The start slot
3334/// depends on any predecessor or successor nodes scheduled already.
3335void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
3336 int II, SwingSchedulerDAG *DAG) {
3337 const SwingSchedulerDDG *DDG = DAG->getDDG();
3338
3339 // Iterate over each instruction that has been scheduled already. The start
3340 // slot computation depends on whether the previously scheduled instruction
3341 // is a predecessor or successor of the specified instruction.
3342 for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
3343 for (SUnit *I : getInstructions(cycle)) {
3344 for (const auto &IE : DDG->getInEdges(SU)) {
3345 if (IE.getSrc() == I) {
3346 int EarlyStart = cycle + IE.getLatency() - IE.getDistance() * II;
3347 *MaxEarlyStart = std::max(a: *MaxEarlyStart, b: EarlyStart);
3348 }
3349 }
3350
3351 for (const auto &OE : DDG->getOutEdges(SU)) {
3352 if (OE.getDst() == I) {
3353 int LateStart = cycle - OE.getLatency() + OE.getDistance() * II;
3354 *MinLateStart = std::min(a: *MinLateStart, b: LateStart);
3355 }
3356 }
3357
3358 SUnit *BE = multipleIterations(SU: I, DAG);
3359 for (const auto &Dep : SU->Preds) {
3360 // For instruction that requires multiple iterations, make sure that
3361 // the dependent instruction is not scheduled past the definition.
3362 if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
3363 !SU->isPred(N: I))
3364 *MinLateStart = std::min(a: *MinLateStart, b: cycle);
3365 }
3366 }
3367 }
3368}
3369
3370/// Order the instructions within a cycle so that the definitions occur
3371/// before the uses. Returns true if the instruction is added to the start
3372/// of the list, or false if added to the end.
3373void SMSchedule::orderDependence(const SwingSchedulerDAG *SSD, SUnit *SU,
3374 std::deque<SUnit *> &Insts) const {
3375 MachineInstr *MI = SU->getInstr();
3376 bool OrderBeforeUse = false;
3377 bool OrderAfterDef = false;
3378 bool OrderBeforeDef = false;
3379 unsigned MoveDef = 0;
3380 unsigned MoveUse = 0;
3381 int StageInst1 = stageScheduled(SU);
3382 const SwingSchedulerDDG *DDG = SSD->getDDG();
3383
3384 unsigned Pos = 0;
3385 for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
3386 ++I, ++Pos) {
3387 for (MachineOperand &MO : MI->operands()) {
3388 if (!MO.isReg() || !MO.getReg().isVirtual())
3389 continue;
3390
3391 Register Reg = MO.getReg();
3392 unsigned BasePos, OffsetPos;
3393 if (ST.getInstrInfo()->getBaseAndOffsetPosition(MI: *MI, BasePos, OffsetPos))
3394 if (MI->getOperand(i: BasePos).getReg() == Reg)
3395 if (Register NewReg = SSD->getInstrBaseReg(SU))
3396 Reg = NewReg;
3397 bool Reads, Writes;
3398 std::tie(args&: Reads, args&: Writes) =
3399 (*I)->getInstr()->readsWritesVirtualRegister(Reg);
3400 if (MO.isDef() && Reads && stageScheduled(SU: *I) <= StageInst1) {
3401 OrderBeforeUse = true;
3402 if (MoveUse == 0)
3403 MoveUse = Pos;
3404 } else if (MO.isDef() && Reads && stageScheduled(SU: *I) > StageInst1) {
3405 // Add the instruction after the scheduled instruction.
3406 OrderAfterDef = true;
3407 MoveDef = Pos;
3408 } else if (MO.isUse() && Writes && stageScheduled(SU: *I) == StageInst1) {
3409 if (cycleScheduled(SU: *I) == cycleScheduled(SU) && !(*I)->isSucc(N: SU)) {
3410 OrderBeforeUse = true;
3411 if (MoveUse == 0)
3412 MoveUse = Pos;
3413 } else {
3414 OrderAfterDef = true;
3415 MoveDef = Pos;
3416 }
3417 } else if (MO.isUse() && Writes && stageScheduled(SU: *I) > StageInst1) {
3418 OrderBeforeUse = true;
3419 if (MoveUse == 0)
3420 MoveUse = Pos;
3421 if (MoveUse != 0) {
3422 OrderAfterDef = true;
3423 MoveDef = Pos - 1;
3424 }
3425 } else if (MO.isUse() && Writes && stageScheduled(SU: *I) < StageInst1) {
3426 // Add the instruction before the scheduled instruction.
3427 OrderBeforeUse = true;
3428 if (MoveUse == 0)
3429 MoveUse = Pos;
3430 } else if (MO.isUse() && stageScheduled(SU: *I) == StageInst1 &&
3431 isLoopCarriedDefOfUse(SSD, Def: (*I)->getInstr(), MO)) {
3432 if (MoveUse == 0) {
3433 OrderBeforeDef = true;
3434 MoveUse = Pos;
3435 }
3436 }
3437 }
3438 // Check for order dependences between instructions. Make sure the source
3439 // is ordered before the destination.
3440 for (auto &OE : DDG->getOutEdges(SU)) {
3441 if (OE.getDst() != *I)
3442 continue;
3443 if (OE.isOrderDep() && stageScheduled(SU: *I) == StageInst1) {
3444 OrderBeforeUse = true;
3445 if (Pos < MoveUse)
3446 MoveUse = Pos;
3447 }
3448 // We did not handle HW dependences in previous for loop,
3449 // and we normally set Latency = 0 for Anti/Output deps,
3450 // so may have nodes in same cycle with Anti/Output dependent on HW regs.
3451 else if ((OE.isAntiDep() || OE.isOutputDep()) &&
3452 stageScheduled(SU: *I) == StageInst1) {
3453 OrderBeforeUse = true;
3454 if ((MoveUse == 0) || (Pos < MoveUse))
3455 MoveUse = Pos;
3456 }
3457 }
3458 for (auto &IE : DDG->getInEdges(SU)) {
3459 if (IE.getSrc() != *I)
3460 continue;
3461 if ((IE.isAntiDep() || IE.isOutputDep() || IE.isOrderDep()) &&
3462 stageScheduled(SU: *I) == StageInst1) {
3463 OrderAfterDef = true;
3464 MoveDef = Pos;
3465 }
3466 }
3467 }
3468
3469 // A circular dependence.
3470 if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
3471 OrderBeforeUse = false;
3472
3473 // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
3474 // to a loop-carried dependence.
3475 if (OrderBeforeDef)
3476 OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
3477
3478 // The uncommon case when the instruction order needs to be updated because
3479 // there is both a use and def.
3480 if (OrderBeforeUse && OrderAfterDef) {
3481 SUnit *UseSU = Insts.at(n: MoveUse);
3482 SUnit *DefSU = Insts.at(n: MoveDef);
3483 if (MoveUse > MoveDef) {
3484 Insts.erase(position: Insts.begin() + MoveUse);
3485 Insts.erase(position: Insts.begin() + MoveDef);
3486 } else {
3487 Insts.erase(position: Insts.begin() + MoveDef);
3488 Insts.erase(position: Insts.begin() + MoveUse);
3489 }
3490 orderDependence(SSD, SU: UseSU, Insts);
3491 orderDependence(SSD, SU, Insts);
3492 orderDependence(SSD, SU: DefSU, Insts);
3493 return;
3494 }
3495 // Put the new instruction first if there is a use in the list. Otherwise,
3496 // put it at the end of the list.
3497 if (OrderBeforeUse)
3498 Insts.push_front(x: SU);
3499 else
3500 Insts.push_back(x: SU);
3501}
3502
3503/// Return true if the scheduled Phi has a loop carried operand.
3504bool SMSchedule::isLoopCarried(const SwingSchedulerDAG *SSD,
3505 MachineInstr &Phi) const {
3506 if (!Phi.isPHI())
3507 return false;
3508 assert(Phi.isPHI() && "Expecting a Phi.");
3509 SUnit *DefSU = SSD->getSUnit(MI: &Phi);
3510 unsigned DefCycle = cycleScheduled(SU: DefSU);
3511 int DefStage = stageScheduled(SU: DefSU);
3512
3513 Register InitVal;
3514 Register LoopVal;
3515 getPhiRegs(Phi, Loop: Phi.getParent(), InitVal, LoopVal);
3516 SUnit *UseSU = SSD->getSUnit(MI: MRI.getVRegDef(Reg: LoopVal));
3517 if (!UseSU)
3518 return true;
3519 if (UseSU->getInstr()->isPHI())
3520 return true;
3521 unsigned LoopCycle = cycleScheduled(SU: UseSU);
3522 int LoopStage = stageScheduled(SU: UseSU);
3523 return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
3524}
3525
3526/// Return true if the instruction is a definition that is loop carried
3527/// and defines the use on the next iteration.
3528/// v1 = phi(v2, v3)
3529/// (Def) v3 = op v1
3530/// (MO) = v1
3531/// If MO appears before Def, then v1 and v3 may get assigned to the same
3532/// register.
3533bool SMSchedule::isLoopCarriedDefOfUse(const SwingSchedulerDAG *SSD,
3534 MachineInstr *Def,
3535 MachineOperand &MO) const {
3536 if (!MO.isReg())
3537 return false;
3538 if (Def->isPHI())
3539 return false;
3540 MachineInstr *Phi = MRI.getVRegDef(Reg: MO.getReg());
3541 if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
3542 return false;
3543 if (!isLoopCarried(SSD, Phi&: *Phi))
3544 return false;
3545 Register LoopReg = getLoopPhiReg(Phi: *Phi, LoopBB: Phi->getParent());
3546 for (MachineOperand &DMO : Def->all_defs()) {
3547 if (DMO.getReg() == LoopReg)
3548 return true;
3549 }
3550 return false;
3551}
3552
3553/// Return true if all scheduled predecessors are loop-carried output/order
3554/// dependencies.
3555bool SMSchedule::onlyHasLoopCarriedOutputOrOrderPreds(
3556 SUnit *SU, const SwingSchedulerDDG *DDG) const {
3557 for (const auto &IE : DDG->getInEdges(SU))
3558 if (InstrToCycle.count(x: IE.getSrc()))
3559 return false;
3560 return true;
3561}
3562
3563/// Determine transitive dependences of unpipelineable instructions
3564SmallPtrSet<SUnit *, 8> SMSchedule::computeUnpipelineableNodes(
3565 SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI) {
3566 SmallPtrSet<SUnit *, 8> DoNotPipeline;
3567 SmallVector<SUnit *, 8> Worklist;
3568
3569 for (auto &SU : SSD->SUnits)
3570 if (SU.isInstr() && PLI->shouldIgnoreForPipelining(MI: SU.getInstr()))
3571 Worklist.push_back(Elt: &SU);
3572
3573 const SwingSchedulerDDG *DDG = SSD->getDDG();
3574 while (!Worklist.empty()) {
3575 auto SU = Worklist.pop_back_val();
3576 if (DoNotPipeline.count(Ptr: SU))
3577 continue;
3578 LLVM_DEBUG(dbgs() << "Do not pipeline SU(" << SU->NodeNum << ")\n");
3579 DoNotPipeline.insert(Ptr: SU);
3580 for (const auto &IE : DDG->getInEdges(SU))
3581 Worklist.push_back(Elt: IE.getSrc());
3582
3583 // To preserve previous behavior and prevent regression
3584 // FIXME: Remove if this doesn't have significant impact on
3585 for (const auto &OE : DDG->getOutEdges(SU))
3586 if (OE.getDistance() == 1)
3587 Worklist.push_back(Elt: OE.getDst());
3588 }
3589 return DoNotPipeline;
3590}
3591
3592// Determine all instructions upon which any unpipelineable instruction depends
3593// and ensure that they are in stage 0. If unable to do so, return false.
3594bool SMSchedule::normalizeNonPipelinedInstructions(
3595 SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI) {
3596 SmallPtrSet<SUnit *, 8> DNP = computeUnpipelineableNodes(SSD, PLI);
3597
3598 int NewLastCycle = INT_MIN;
3599 for (SUnit &SU : SSD->SUnits) {
3600 if (!SU.isInstr())
3601 continue;
3602 if (!DNP.contains(Ptr: &SU) || stageScheduled(SU: &SU) == 0) {
3603 NewLastCycle = std::max(a: NewLastCycle, b: InstrToCycle[&SU]);
3604 continue;
3605 }
3606
3607 // Put the non-pipelined instruction as early as possible in the schedule
3608 int NewCycle = getFirstCycle();
3609 for (const auto &IE : SSD->getDDG()->getInEdges(SU: &SU))
3610 if (IE.getDistance() == 0)
3611 NewCycle = std::max(a: InstrToCycle[IE.getSrc()], b: NewCycle);
3612
3613 // To preserve previous behavior and prevent regression
3614 // FIXME: Remove if this doesn't have significant impact on performance
3615 for (auto &OE : SSD->getDDG()->getOutEdges(SU: &SU))
3616 if (OE.getDistance() == 1)
3617 NewCycle = std::max(a: InstrToCycle[OE.getDst()], b: NewCycle);
3618
3619 int OldCycle = InstrToCycle[&SU];
3620 if (OldCycle != NewCycle) {
3621 InstrToCycle[&SU] = NewCycle;
3622 auto &OldS = getInstructions(cycle: OldCycle);
3623 llvm::erase(C&: OldS, V: &SU);
3624 getInstructions(cycle: NewCycle).emplace_back(args: &SU);
3625 LLVM_DEBUG(dbgs() << "SU(" << SU.NodeNum
3626 << ") is not pipelined; moving from cycle " << OldCycle
3627 << " to " << NewCycle << " Instr:" << *SU.getInstr());
3628 }
3629
3630 // We traverse the SUs in the order of the original basic block. Computing
3631 // NewCycle in this order normally works fine because all dependencies
3632 // (except for loop-carried dependencies) don't violate the original order.
3633 // However, an artificial dependency (e.g., added by CopyToPhiMutation) can
3634 // break it. That is, there may be exist an artificial dependency from
3635 // bottom to top. In such a case, NewCycle may become too large to be
3636 // scheduled in Stage 0. For example, assume that Inst0 is in DNP in the
3637 // following case:
3638 //
3639 // | Inst0 <-+
3640 // SU order | | artificial dep
3641 // | Inst1 --+
3642 // v
3643 //
3644 // If Inst1 is scheduled at cycle N and is not at Stage 0, then NewCycle of
3645 // Inst0 must be greater than or equal to N so that Inst0 is not be
3646 // scheduled at Stage 0. In such cases, we reject this schedule at this
3647 // time.
3648 // FIXME: The reason for this is the existence of artificial dependencies
3649 // that are contradict to the original SU order. If ignoring artificial
3650 // dependencies does not affect correctness, then it is better to ignore
3651 // them.
3652 if (FirstCycle + InitiationInterval <= NewCycle)
3653 return false;
3654
3655 NewLastCycle = std::max(a: NewLastCycle, b: NewCycle);
3656 }
3657 LastCycle = NewLastCycle;
3658 return true;
3659}
3660
3661// Check if the generated schedule is valid. This function checks if
3662// an instruction that uses a physical register is scheduled in a
3663// different stage than the definition. The pipeliner does not handle
3664// physical register values that may cross a basic block boundary.
3665// Furthermore, if a physical def/use pair is assigned to the same
3666// cycle, orderDependence does not guarantee def/use ordering, so that
3667// case should be considered invalid. (The test checks for both
3668// earlier and same-cycle use to be more robust.)
3669bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
3670 for (SUnit &SU : SSD->SUnits) {
3671 if (!SU.hasPhysRegDefs)
3672 continue;
3673 int StageDef = stageScheduled(SU: &SU);
3674 int CycleDef = InstrToCycle[&SU];
3675 assert(StageDef != -1 && "Instruction should have been scheduled.");
3676 for (auto &OE : SSD->getDDG()->getOutEdges(SU: &SU)) {
3677 SUnit *Dst = OE.getDst();
3678 if (OE.isAssignedRegDep() && !Dst->isBoundaryNode())
3679 if (OE.getReg().isPhysical()) {
3680 if (stageScheduled(SU: Dst) != StageDef)
3681 return false;
3682 if (InstrToCycle[Dst] <= CycleDef)
3683 return false;
3684 }
3685 }
3686 }
3687 return true;
3688}
3689
3690/// A property of the node order in swing-modulo-scheduling is
3691/// that for nodes outside circuits the following holds:
3692/// none of them is scheduled after both a successor and a
3693/// predecessor.
3694/// The method below checks whether the property is met.
3695/// If not, debug information is printed and statistics information updated.
3696/// Note that we do not use an assert statement.
3697/// The reason is that although an invalid node order may prevent
3698/// the pipeliner from finding a pipelined schedule for arbitrary II,
3699/// it does not lead to the generation of incorrect code.
3700void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
3701
3702 // a sorted vector that maps each SUnit to its index in the NodeOrder
3703 typedef std::pair<SUnit *, unsigned> UnitIndex;
3704 std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(x: nullptr, y: 0));
3705
3706 for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
3707 Indices.push_back(x: std::make_pair(x: NodeOrder[i], y&: i));
3708
3709 auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
3710 return std::get<0>(in&: i1) < std::get<0>(in&: i2);
3711 };
3712
3713 // sort, so that we can perform a binary search
3714 llvm::sort(C&: Indices, Comp: CompareKey);
3715
3716 bool Valid = true;
3717 (void)Valid;
3718 // for each SUnit in the NodeOrder, check whether
3719 // it appears after both a successor and a predecessor
3720 // of the SUnit. If this is the case, and the SUnit
3721 // is not part of circuit, then the NodeOrder is not
3722 // valid.
3723 for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
3724 SUnit *SU = NodeOrder[i];
3725 unsigned Index = i;
3726
3727 bool PredBefore = false;
3728 bool SuccBefore = false;
3729
3730 SUnit *Succ;
3731 SUnit *Pred;
3732 (void)Succ;
3733 (void)Pred;
3734
3735 for (const auto &IE : DDG->getInEdges(SU)) {
3736 SUnit *PredSU = IE.getSrc();
3737 unsigned PredIndex = std::get<1>(
3738 in&: *llvm::lower_bound(Range&: Indices, Value: std::make_pair(x&: PredSU, y: 0), C: CompareKey));
3739 if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
3740 PredBefore = true;
3741 Pred = PredSU;
3742 break;
3743 }
3744 }
3745
3746 for (const auto &OE : DDG->getOutEdges(SU)) {
3747 SUnit *SuccSU = OE.getDst();
3748 // Do not process a boundary node, it was not included in NodeOrder,
3749 // hence not in Indices either, call to std::lower_bound() below will
3750 // return Indices.end().
3751 if (SuccSU->isBoundaryNode())
3752 continue;
3753 unsigned SuccIndex = std::get<1>(
3754 in&: *llvm::lower_bound(Range&: Indices, Value: std::make_pair(x&: SuccSU, y: 0), C: CompareKey));
3755 if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
3756 SuccBefore = true;
3757 Succ = SuccSU;
3758 break;
3759 }
3760 }
3761
3762 if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
3763 // instructions in circuits are allowed to be scheduled
3764 // after both a successor and predecessor.
3765 bool InCircuit = llvm::any_of(
3766 Range: Circuits, P: [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
3767 if (InCircuit)
3768 LLVM_DEBUG(dbgs() << "In a circuit, predecessor ");
3769 else {
3770 Valid = false;
3771 NumNodeOrderIssues++;
3772 LLVM_DEBUG(dbgs() << "Predecessor ");
3773 }
3774 LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
3775 << " are scheduled before node " << SU->NodeNum
3776 << "\n");
3777 }
3778 }
3779
3780 LLVM_DEBUG({
3781 if (!Valid)
3782 dbgs() << "Invalid node order found!\n";
3783 });
3784}
3785
3786/// Attempt to fix the degenerate cases when the instruction serialization
3787/// causes the register lifetimes to overlap. For example,
3788/// p' = store_pi(p, b)
3789/// = load p, offset
3790/// In this case p and p' overlap, which means that two registers are needed.
3791/// Instead, this function changes the load to use p' and updates the offset.
3792void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
3793 Register OverlapReg;
3794 Register NewBaseReg;
3795 for (SUnit *SU : Instrs) {
3796 MachineInstr *MI = SU->getInstr();
3797 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3798 const MachineOperand &MO = MI->getOperand(i);
3799 // Look for an instruction that uses p. The instruction occurs in the
3800 // same cycle but occurs later in the serialized order.
3801 if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
3802 // Check that the instruction appears in the InstrChanges structure,
3803 // which contains instructions that can have the offset updated.
3804 DenseMap<SUnit *, std::pair<Register, int64_t>>::iterator It =
3805 InstrChanges.find(Val: SU);
3806 if (It != InstrChanges.end()) {
3807 unsigned BasePos, OffsetPos;
3808 // Update the base register and adjust the offset.
3809 if (TII->getBaseAndOffsetPosition(MI: *MI, BasePos, OffsetPos)) {
3810 MachineInstr *NewMI = MF.CloneMachineInstr(Orig: MI);
3811 NewMI->getOperand(i: BasePos).setReg(NewBaseReg);
3812 int64_t NewOffset =
3813 MI->getOperand(i: OffsetPos).getImm() - It->second.second;
3814 NewMI->getOperand(i: OffsetPos).setImm(NewOffset);
3815 SU->setInstr(NewMI);
3816 MISUnitMap[NewMI] = SU;
3817 NewMIs[MI] = NewMI;
3818 }
3819 }
3820 OverlapReg = Register();
3821 NewBaseReg = Register();
3822 break;
3823 }
3824 // Look for an instruction of the form p' = op(p), which uses and defines
3825 // two virtual registers that get allocated to the same physical register.
3826 unsigned TiedUseIdx = 0;
3827 if (MI->isRegTiedToUseOperand(DefOpIdx: i, UseOpIdx: &TiedUseIdx)) {
3828 // OverlapReg is p in the example above.
3829 OverlapReg = MI->getOperand(i: TiedUseIdx).getReg();
3830 // NewBaseReg is p' in the example above.
3831 NewBaseReg = MI->getOperand(i).getReg();
3832 break;
3833 }
3834 }
3835 }
3836}
3837
3838std::deque<SUnit *>
3839SMSchedule::reorderInstructions(const SwingSchedulerDAG *SSD,
3840 const std::deque<SUnit *> &Instrs) const {
3841 std::deque<SUnit *> NewOrderPhi;
3842 for (SUnit *SU : Instrs) {
3843 if (SU->getInstr()->isPHI())
3844 NewOrderPhi.push_back(x: SU);
3845 }
3846 std::deque<SUnit *> NewOrderI;
3847 for (SUnit *SU : Instrs) {
3848 if (!SU->getInstr()->isPHI())
3849 orderDependence(SSD, SU, Insts&: NewOrderI);
3850 }
3851 llvm::append_range(C&: NewOrderPhi, R&: NewOrderI);
3852 return NewOrderPhi;
3853}
3854
3855/// After the schedule has been formed, call this function to combine
3856/// the instructions from the different stages/cycles. That is, this
3857/// function creates a schedule that represents a single iteration.
3858void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
3859 // Move all instructions to the first stage from later stages.
3860 for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3861 for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
3862 ++stage) {
3863 std::deque<SUnit *> &cycleInstrs =
3864 ScheduledInstrs[cycle + (stage * InitiationInterval)];
3865 for (SUnit *SU : llvm::reverse(C&: cycleInstrs))
3866 ScheduledInstrs[cycle].push_front(x: SU);
3867 }
3868 }
3869
3870 // Erase all the elements in the later stages. Only one iteration should
3871 // remain in the scheduled list, and it contains all the instructions.
3872 for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
3873 ScheduledInstrs.erase(Val: cycle);
3874
3875 // Change the registers in instruction as specified in the InstrChanges
3876 // map. We need to use the new registers to create the correct order.
3877 for (const SUnit &SU : SSD->SUnits)
3878 SSD->applyInstrChange(MI: SU.getInstr(), Schedule&: *this);
3879
3880 // Reorder the instructions in each cycle to fix and improve the
3881 // generated code.
3882 for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
3883 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
3884 cycleInstrs = reorderInstructions(SSD, Instrs: cycleInstrs);
3885 SSD->fixupRegisterOverlaps(Instrs&: cycleInstrs);
3886 }
3887
3888 LLVM_DEBUG(dump(););
3889}
3890
3891void NodeSet::print(raw_ostream &os) const {
3892 os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
3893 << " depth " << MaxDepth << " col " << Colocate << "\n";
3894 for (const auto &I : Nodes)
3895 os << " SU(" << I->NodeNum << ") " << *(I->getInstr());
3896 os << "\n";
3897}
3898
3899#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3900/// Print the schedule information to the given output.
3901void SMSchedule::print(raw_ostream &os) const {
3902 // Iterate over each cycle.
3903 for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3904 // Iterate over each instruction in the cycle.
3905 const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
3906 for (SUnit *CI : cycleInstrs->second) {
3907 os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
3908 os << "(" << CI->NodeNum << ") ";
3909 CI->getInstr()->print(os);
3910 os << "\n";
3911 }
3912 }
3913}
3914
3915/// Utility function used for debugging to print the schedule.
3916LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
3917LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
3918
3919void ResourceManager::dumpMRT() const {
3920 LLVM_DEBUG({
3921 if (UseDFA)
3922 return;
3923 std::stringstream SS;
3924 SS << "MRT:\n";
3925 SS << std::setw(4) << "Slot";
3926 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I)
3927 SS << std::setw(3) << I;
3928 SS << std::setw(7) << "#Mops"
3929 << "\n";
3930 for (int Slot = 0; Slot < InitiationInterval; ++Slot) {
3931 SS << std::setw(4) << Slot;
3932 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I)
3933 SS << std::setw(3) << MRT[Slot][I];
3934 SS << std::setw(7) << NumScheduledMops[Slot] << "\n";
3935 }
3936 dbgs() << SS.str();
3937 });
3938}
3939#endif
3940
3941void ResourceManager::initProcResourceVectors(
3942 const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
3943 unsigned ProcResourceID = 0;
3944
3945 // We currently limit the resource kinds to 64 and below so that we can use
3946 // uint64_t for Masks
3947 assert(SM.getNumProcResourceKinds() < 64 &&
3948 "Too many kinds of resources, unsupported");
3949 // Create a unique bitmask for every processor resource unit.
3950 // Skip resource at index 0, since it always references 'InvalidUnit'.
3951 Masks.resize(N: SM.getNumProcResourceKinds());
3952 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3953 const MCProcResourceDesc &Desc = *SM.getProcResource(ProcResourceIdx: I);
3954 if (Desc.SubUnitsIdxBegin)
3955 continue;
3956 Masks[I] = 1ULL << ProcResourceID;
3957 ProcResourceID++;
3958 }
3959 // Create a unique bitmask for every processor resource group.
3960 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3961 const MCProcResourceDesc &Desc = *SM.getProcResource(ProcResourceIdx: I);
3962 if (!Desc.SubUnitsIdxBegin)
3963 continue;
3964 Masks[I] = 1ULL << ProcResourceID;
3965 for (unsigned U = 0; U < Desc.NumUnits; ++U)
3966 Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
3967 ProcResourceID++;
3968 }
3969 LLVM_DEBUG({
3970 if (SwpShowResMask) {
3971 dbgs() << "ProcResourceDesc:\n";
3972 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3973 const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
3974 dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
3975 ProcResource->Name, I, Masks[I],
3976 ProcResource->NumUnits);
3977 }
3978 dbgs() << " -----------------\n";
3979 }
3980 });
3981}
3982
3983bool ResourceManager::canReserveResources(SUnit &SU, int Cycle) {
3984 LLVM_DEBUG({
3985 if (SwpDebugResource)
3986 dbgs() << "canReserveResources:\n";
3987 });
3988 if (UseDFA)
3989 return DFAResources[positiveModulo(Dividend: Cycle, Divisor: InitiationInterval)]
3990 ->canReserveResources(MID: &SU.getInstr()->getDesc());
3991
3992 const MCSchedClassDesc *SCDesc = DAG->getSchedClass(SU: &SU);
3993 if (!SCDesc->isValid()) {
3994 LLVM_DEBUG({
3995 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3996 dbgs() << "isPseudo:" << SU.getInstr()->isPseudo() << "\n";
3997 });
3998 return true;
3999 }
4000
4001 reserveResources(SCDesc, Cycle);
4002 bool Result = !isOverbooked();
4003 unreserveResources(SCDesc, Cycle);
4004
4005 LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return " << Result << "\n\n");
4006 return Result;
4007}
4008
4009void ResourceManager::reserveResources(SUnit &SU, int Cycle) {
4010 LLVM_DEBUG({
4011 if (SwpDebugResource)
4012 dbgs() << "reserveResources:\n";
4013 });
4014 if (UseDFA)
4015 return DFAResources[positiveModulo(Dividend: Cycle, Divisor: InitiationInterval)]
4016 ->reserveResources(MID: &SU.getInstr()->getDesc());
4017
4018 const MCSchedClassDesc *SCDesc = DAG->getSchedClass(SU: &SU);
4019 if (!SCDesc->isValid()) {
4020 LLVM_DEBUG({
4021 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
4022 dbgs() << "isPseudo:" << SU.getInstr()->isPseudo() << "\n";
4023 });
4024 return;
4025 }
4026
4027 reserveResources(SCDesc, Cycle);
4028
4029 LLVM_DEBUG({
4030 if (SwpDebugResource) {
4031 dumpMRT();
4032 dbgs() << "reserveResources: done!\n\n";
4033 }
4034 });
4035}
4036
4037void ResourceManager::reserveResources(const MCSchedClassDesc *SCDesc,
4038 int Cycle) {
4039 assert(!UseDFA);
4040 for (const MCWriteProcResEntry &PRE : make_range(
4041 x: STI->getWriteProcResBegin(SC: SCDesc), y: STI->getWriteProcResEnd(SC: SCDesc)))
4042 for (int C = Cycle; C < Cycle + PRE.ReleaseAtCycle; ++C)
4043 ++MRT[positiveModulo(Dividend: C, Divisor: InitiationInterval)][PRE.ProcResourceIdx];
4044
4045 for (int C = Cycle; C < Cycle + SCDesc->NumMicroOps; ++C)
4046 ++NumScheduledMops[positiveModulo(Dividend: C, Divisor: InitiationInterval)];
4047}
4048
4049void ResourceManager::unreserveResources(const MCSchedClassDesc *SCDesc,
4050 int Cycle) {
4051 assert(!UseDFA);
4052 for (const MCWriteProcResEntry &PRE : make_range(
4053 x: STI->getWriteProcResBegin(SC: SCDesc), y: STI->getWriteProcResEnd(SC: SCDesc)))
4054 for (int C = Cycle; C < Cycle + PRE.ReleaseAtCycle; ++C)
4055 --MRT[positiveModulo(Dividend: C, Divisor: InitiationInterval)][PRE.ProcResourceIdx];
4056
4057 for (int C = Cycle; C < Cycle + SCDesc->NumMicroOps; ++C)
4058 --NumScheduledMops[positiveModulo(Dividend: C, Divisor: InitiationInterval)];
4059}
4060
4061bool ResourceManager::isOverbooked() const {
4062 assert(!UseDFA);
4063 for (int Slot = 0; Slot < InitiationInterval; ++Slot) {
4064 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
4065 const MCProcResourceDesc *Desc = SM.getProcResource(ProcResourceIdx: I);
4066 if (MRT[Slot][I] > Desc->NumUnits)
4067 return true;
4068 }
4069 if (NumScheduledMops[Slot] > IssueWidth)
4070 return true;
4071 }
4072 return false;
4073}
4074
4075int ResourceManager::calculateResMIIDFA() const {
4076 assert(UseDFA);
4077
4078 // Sort the instructions by the number of available choices for scheduling,
4079 // least to most. Use the number of critical resources as the tie breaker.
4080 FuncUnitSorter FUS = FuncUnitSorter(*ST);
4081 for (SUnit &SU : DAG->SUnits)
4082 FUS.calcCriticalResources(MI&: *SU.getInstr());
4083 PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
4084 FuncUnitOrder(FUS);
4085
4086 for (SUnit &SU : DAG->SUnits)
4087 FuncUnitOrder.push(x: SU.getInstr());
4088
4089 SmallVector<std::unique_ptr<DFAPacketizer>, 8> Resources;
4090 Resources.push_back(
4091 Elt: std::unique_ptr<DFAPacketizer>(TII->CreateTargetScheduleState(*ST)));
4092
4093 while (!FuncUnitOrder.empty()) {
4094 MachineInstr *MI = FuncUnitOrder.top();
4095 FuncUnitOrder.pop();
4096 if (TII->isZeroCost(Opcode: MI->getOpcode()))
4097 continue;
4098
4099 // Attempt to reserve the instruction in an existing DFA. At least one
4100 // DFA is needed for each cycle.
4101 unsigned NumCycles = DAG->getSUnit(MI)->Latency;
4102 unsigned ReservedCycles = 0;
4103 auto *RI = Resources.begin();
4104 auto *RE = Resources.end();
4105 LLVM_DEBUG({
4106 dbgs() << "Trying to reserve resource for " << NumCycles
4107 << " cycles for \n";
4108 MI->dump();
4109 });
4110 for (unsigned C = 0; C < NumCycles; ++C)
4111 while (RI != RE) {
4112 if ((*RI)->canReserveResources(MI&: *MI)) {
4113 (*RI)->reserveResources(MI&: *MI);
4114 ++ReservedCycles;
4115 break;
4116 }
4117 RI++;
4118 }
4119 LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
4120 << ", NumCycles:" << NumCycles << "\n");
4121 // Add new DFAs, if needed, to reserve resources.
4122 for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
4123 LLVM_DEBUG(if (SwpDebugResource) dbgs()
4124 << "NewResource created to reserve resources"
4125 << "\n");
4126 auto *NewResource = TII->CreateTargetScheduleState(*ST);
4127 assert(NewResource->canReserveResources(*MI) && "Reserve error.");
4128 NewResource->reserveResources(MI&: *MI);
4129 Resources.push_back(Elt: std::unique_ptr<DFAPacketizer>(NewResource));
4130 }
4131 }
4132
4133 int Resmii = Resources.size();
4134 LLVM_DEBUG(dbgs() << "Return Res MII:" << Resmii << "\n");
4135 return Resmii;
4136}
4137
4138int ResourceManager::calculateResMII() const {
4139 if (UseDFA)
4140 return calculateResMIIDFA();
4141
4142 // Count each resource consumption and divide it by the number of units.
4143 // ResMII is the max value among them.
4144
4145 int NumMops = 0;
4146 SmallVector<uint64_t> ResourceCount(SM.getNumProcResourceKinds());
4147 for (SUnit &SU : DAG->SUnits) {
4148 if (TII->isZeroCost(Opcode: SU.getInstr()->getOpcode()))
4149 continue;
4150
4151 const MCSchedClassDesc *SCDesc = DAG->getSchedClass(SU: &SU);
4152 if (!SCDesc->isValid())
4153 continue;
4154
4155 LLVM_DEBUG({
4156 if (SwpDebugResource) {
4157 DAG->dumpNode(SU);
4158 dbgs() << " #Mops: " << SCDesc->NumMicroOps << "\n"
4159 << " WriteProcRes: ";
4160 }
4161 });
4162 NumMops += SCDesc->NumMicroOps;
4163 for (const MCWriteProcResEntry &PRE :
4164 make_range(x: STI->getWriteProcResBegin(SC: SCDesc),
4165 y: STI->getWriteProcResEnd(SC: SCDesc))) {
4166 LLVM_DEBUG({
4167 if (SwpDebugResource) {
4168 const MCProcResourceDesc *Desc =
4169 SM.getProcResource(PRE.ProcResourceIdx);
4170 dbgs() << Desc->Name << ": " << PRE.ReleaseAtCycle << ", ";
4171 }
4172 });
4173 ResourceCount[PRE.ProcResourceIdx] += PRE.ReleaseAtCycle;
4174 }
4175 LLVM_DEBUG(if (SwpDebugResource) dbgs() << "\n");
4176 }
4177
4178 int Result = (NumMops + IssueWidth - 1) / IssueWidth;
4179 LLVM_DEBUG({
4180 if (SwpDebugResource)
4181 dbgs() << "#Mops: " << NumMops << ", "
4182 << "IssueWidth: " << IssueWidth << ", "
4183 << "Cycles: " << Result << "\n";
4184 });
4185
4186 LLVM_DEBUG({
4187 if (SwpDebugResource) {
4188 std::stringstream SS;
4189 SS << std::setw(2) << "ID" << std::setw(16) << "Name" << std::setw(10)
4190 << "Units" << std::setw(10) << "Consumed" << std::setw(10) << "Cycles"
4191 << "\n";
4192 dbgs() << SS.str();
4193 }
4194 });
4195 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
4196 const MCProcResourceDesc *Desc = SM.getProcResource(ProcResourceIdx: I);
4197 int Cycles = (ResourceCount[I] + Desc->NumUnits - 1) / Desc->NumUnits;
4198 LLVM_DEBUG({
4199 if (SwpDebugResource) {
4200 std::stringstream SS;
4201 SS << std::setw(2) << I << std::setw(16) << Desc->Name << std::setw(10)
4202 << Desc->NumUnits << std::setw(10) << ResourceCount[I]
4203 << std::setw(10) << Cycles << "\n";
4204 dbgs() << SS.str();
4205 }
4206 });
4207 if (Cycles > Result)
4208 Result = Cycles;
4209 }
4210 return Result;
4211}
4212
4213void ResourceManager::init(int II) {
4214 InitiationInterval = II;
4215 DFAResources.clear();
4216 DFAResources.resize(N: II);
4217 for (auto &I : DFAResources)
4218 I.reset(p: ST->getInstrInfo()->CreateTargetScheduleState(*ST));
4219 MRT.clear();
4220 MRT.resize(N: II, NV: SmallVector<uint64_t>(SM.getNumProcResourceKinds()));
4221 NumScheduledMops.clear();
4222 NumScheduledMops.resize(N: II);
4223}
4224
4225bool SwingSchedulerDDGEdge::ignoreDependence(bool IgnoreAnti) const {
4226 if (Pred.isArtificial() || Dst->isBoundaryNode())
4227 return true;
4228 // Currently, dependence that is an anti-dependences but not a loop-carried is
4229 // also ignored. This behavior is preserved to prevent regression.
4230 // FIXME: Remove if this doesn't have significant impact on performance
4231 return IgnoreAnti && (Pred.getKind() == SDep::Kind::Anti || Distance != 0);
4232}
4233
4234SwingSchedulerDDG::SwingSchedulerDDGEdges &
4235SwingSchedulerDDG::getEdges(const SUnit *SU) {
4236 if (SU == EntrySU)
4237 return EntrySUEdges;
4238 if (SU == ExitSU)
4239 return ExitSUEdges;
4240 return EdgesVec[SU->NodeNum];
4241}
4242
4243const SwingSchedulerDDG::SwingSchedulerDDGEdges &
4244SwingSchedulerDDG::getEdges(const SUnit *SU) const {
4245 if (SU == EntrySU)
4246 return EntrySUEdges;
4247 if (SU == ExitSU)
4248 return ExitSUEdges;
4249 return EdgesVec[SU->NodeNum];
4250}
4251
4252void SwingSchedulerDDG::addEdge(const SUnit *SU,
4253 const SwingSchedulerDDGEdge &Edge) {
4254 assert(!Edge.isValidationOnly() &&
4255 "Validation-only edges are not expected here.");
4256 auto &Edges = getEdges(SU);
4257 if (Edge.getSrc() == SU)
4258 Edges.Succs.push_back(Elt: Edge);
4259 else
4260 Edges.Preds.push_back(Elt: Edge);
4261}
4262
4263void SwingSchedulerDDG::initEdges(SUnit *SU) {
4264 for (const auto &PI : SU->Preds) {
4265 SwingSchedulerDDGEdge Edge(SU, PI, /*IsSucc=*/false,
4266 /*IsValidationOnly=*/false);
4267 addEdge(SU, Edge);
4268 }
4269
4270 for (const auto &SI : SU->Succs) {
4271 SwingSchedulerDDGEdge Edge(SU, SI, /*IsSucc=*/true,
4272 /*IsValidationOnly=*/false);
4273 addEdge(SU, Edge);
4274 }
4275}
4276
4277SwingSchedulerDDG::SwingSchedulerDDG(std::vector<SUnit> &SUnits, SUnit *EntrySU,
4278 SUnit *ExitSU, const LoopCarriedEdges &LCE)
4279 : EntrySU(EntrySU), ExitSU(ExitSU) {
4280 EdgesVec.resize(new_size: SUnits.size());
4281
4282 // Add non-loop-carried edges based on the DAG.
4283 initEdges(SU: EntrySU);
4284 initEdges(SU: ExitSU);
4285 for (auto &SU : SUnits)
4286 initEdges(SU: &SU);
4287
4288 // Add loop-carried edges, which are not represented in the DAG.
4289 for (SUnit &SU : SUnits) {
4290 SUnit *Src = &SU;
4291 if (const LoopCarriedEdges::OrderDep *OD = LCE.getOrderDepOrNull(Key: Src)) {
4292 SDep Base(Src, SDep::Barrier);
4293 Base.setLatency(1);
4294 for (SUnit *Dst : *OD) {
4295 SwingSchedulerDDGEdge Edge(Dst, Base, /*IsSucc=*/false,
4296 /*IsValidationOnly=*/true);
4297 Edge.setDistance(1);
4298 ValidationOnlyEdges.push_back(Elt: Edge);
4299 }
4300 }
4301 }
4302}
4303
4304const SwingSchedulerDDG::EdgesType &
4305SwingSchedulerDDG::getInEdges(const SUnit *SU) const {
4306 return getEdges(SU).Preds;
4307}
4308
4309const SwingSchedulerDDG::EdgesType &
4310SwingSchedulerDDG::getOutEdges(const SUnit *SU) const {
4311 return getEdges(SU).Succs;
4312}
4313
4314/// Check if \p Schedule doesn't violate the validation-only dependencies.
4315bool SwingSchedulerDDG::isValidSchedule(const SMSchedule &Schedule) const {
4316 unsigned II = Schedule.getInitiationInterval();
4317
4318 auto ExpandCycle = [&](SUnit *SU) {
4319 int Stage = Schedule.stageScheduled(SU);
4320 int Cycle = Schedule.cycleScheduled(SU);
4321 return Cycle + (Stage * II);
4322 };
4323
4324 for (const SwingSchedulerDDGEdge &Edge : ValidationOnlyEdges) {
4325 SUnit *Src = Edge.getSrc();
4326 SUnit *Dst = Edge.getDst();
4327 if (!Src->isInstr() || !Dst->isInstr())
4328 continue;
4329 int CycleSrc = ExpandCycle(Src);
4330 int CycleDst = ExpandCycle(Dst);
4331 int MaxLateStart = CycleDst + Edge.getDistance() * II - Edge.getLatency();
4332 if (CycleSrc > MaxLateStart) {
4333 LLVM_DEBUG({
4334 dbgs() << "Validation failed for edge from " << Src->NodeNum << " to "
4335 << Dst->NodeNum << "\n";
4336 });
4337 return false;
4338 }
4339 }
4340 return true;
4341}
4342
4343void LoopCarriedEdges::modifySUnits(std::vector<SUnit> &SUnits,
4344 const TargetInstrInfo *TII) {
4345 for (SUnit &SU : SUnits) {
4346 SUnit *Src = &SU;
4347 if (auto *OrderDep = getOrderDepOrNull(Key: Src)) {
4348 SDep Dep(Src, SDep::Barrier);
4349 Dep.setLatency(1);
4350 for (SUnit *Dst : *OrderDep) {
4351 SUnit *From = Src;
4352 SUnit *To = Dst;
4353 if (From->NodeNum > To->NodeNum)
4354 std::swap(a&: From, b&: To);
4355
4356 // Add a forward edge if the following conditions are met:
4357 //
4358 // - The instruction of the source node (FromMI) may read memory.
4359 // - The instruction of the target node (ToMI) may modify memory, but
4360 // does not read it.
4361 // - Neither instruction is a global barrier.
4362 // - The load appears before the store in the original basic block.
4363 // - There are no barrier or store instructions between the two nodes.
4364 // - The target node is unreachable from the source node in the current
4365 // DAG.
4366 //
4367 // TODO: These conditions are inherited from a previous implementation,
4368 // and some may no longer be necessary. For now, we conservatively
4369 // retain all of them to avoid regressions, but the logic could
4370 // potentially be simplified
4371 MachineInstr *FromMI = From->getInstr();
4372 MachineInstr *ToMI = To->getInstr();
4373 if (FromMI->mayLoad() && !ToMI->mayLoad() && ToMI->mayStore() &&
4374 !TII->isGlobalMemoryObject(MI: FromMI) &&
4375 !TII->isGlobalMemoryObject(MI: ToMI) && !isSuccOrder(SUa: From, SUb: To)) {
4376 SDep Pred = Dep;
4377 Pred.setSUnit(From);
4378 To->addPred(D: Pred);
4379 }
4380 }
4381 }
4382 }
4383}
4384
4385void LoopCarriedEdges::dump(SUnit *SU, const TargetRegisterInfo *TRI,
4386 const MachineRegisterInfo *MRI) const {
4387 const auto *Order = getOrderDepOrNull(Key: SU);
4388
4389 if (!Order)
4390 return;
4391
4392 const auto DumpSU = [](const SUnit *SU) {
4393 std::ostringstream OSS;
4394 OSS << "SU(" << SU->NodeNum << ")";
4395 return OSS.str();
4396 };
4397
4398 dbgs() << " Loop carried edges from " << DumpSU(SU) << "\n"
4399 << " Order\n";
4400 for (SUnit *Dst : *Order)
4401 dbgs() << " " << DumpSU(Dst) << "\n";
4402}
4403