1 //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
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
7 //===----------------------------------------------------------------------===//
9 // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
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
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.
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
30 //===----------------------------------------------------------------------===//
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/MapVector.h"
37 #include "llvm/ADT/PriorityQueue.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/RegisterPressure.h"
63 #include "llvm/CodeGen/ScheduleDAG.h"
64 #include "llvm/CodeGen/ScheduleDAGMutation.h"
65 #include "llvm/CodeGen/TargetOpcodes.h"
66 #include "llvm/CodeGen/TargetRegisterInfo.h"
67 #include "llvm/CodeGen/TargetSubtargetInfo.h"
68 #include "llvm/Config/llvm-config.h"
69 #include "llvm/IR/Attributes.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/MC/LaneBitmask.h"
72 #include "llvm/MC/MCInstrDesc.h"
73 #include "llvm/MC/MCInstrItineraries.h"
74 #include "llvm/MC/MCRegisterInfo.h"
75 #include "llvm/Pass.h"
76 #include "llvm/Support/CommandLine.h"
77 #include "llvm/Support/Compiler.h"
78 #include "llvm/Support/Debug.h"
79 #include "llvm/Support/MathExtras.h"
80 #include "llvm/Support/raw_ostream.h"
96 #define DEBUG_TYPE "pipeliner"
98 STATISTIC(NumTrytoPipeline
, "Number of loops that we attempt to pipeline");
99 STATISTIC(NumPipelined
, "Number of loops software pipelined");
100 STATISTIC(NumNodeOrderIssues
, "Number of node order issues found");
101 STATISTIC(NumFailBranch
, "Pipeliner abort due to unknown branch");
102 STATISTIC(NumFailLoop
, "Pipeliner abort due to unsupported loop");
103 STATISTIC(NumFailPreheader
, "Pipeliner abort due to missing preheader");
104 STATISTIC(NumFailLargeMaxMII
, "Pipeliner abort due to MaxMII too large");
105 STATISTIC(NumFailZeroMII
, "Pipeliner abort due to zero MII");
106 STATISTIC(NumFailNoSchedule
, "Pipeliner abort due to no schedule found");
107 STATISTIC(NumFailZeroStage
, "Pipeliner abort due to zero stage");
108 STATISTIC(NumFailLargeMaxStage
, "Pipeliner abort due to too many stages");
110 /// A command line option to turn software pipelining on or off.
111 static cl::opt
<bool> EnableSWP("enable-pipeliner", cl::Hidden
, cl::init(true),
112 cl::desc("Enable Software Pipelining"));
114 /// A command line option to enable SWP at -Os.
115 static cl::opt
<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
116 cl::desc("Enable SWP at Os."), cl::Hidden
,
119 /// A command line argument to limit minimum initial interval for pipelining.
120 static cl::opt
<int> SwpMaxMii("pipeliner-max-mii",
121 cl::desc("Size limit for the MII."),
122 cl::Hidden
, cl::init(27));
124 /// A command line argument to limit the number of stages in the pipeline.
126 SwpMaxStages("pipeliner-max-stages",
127 cl::desc("Maximum stages allowed in the generated scheduled."),
128 cl::Hidden
, cl::init(3));
130 /// A command line option to disable the pruning of chain dependences due to
131 /// an unrelated Phi.
133 SwpPruneDeps("pipeliner-prune-deps",
134 cl::desc("Prune dependences between unrelated Phi nodes."),
135 cl::Hidden
, cl::init(true));
137 /// A command line option to disable the pruning of loop carried order
140 SwpPruneLoopCarried("pipeliner-prune-loop-carried",
141 cl::desc("Prune loop carried order dependences."),
142 cl::Hidden
, cl::init(true));
145 static cl::opt
<int> SwpLoopLimit("pipeliner-max", cl::Hidden
, cl::init(-1));
148 static cl::opt
<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
150 cl::desc("Ignore RecMII"));
152 static cl::opt
<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden
,
154 static cl::opt
<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden
,
157 static cl::opt
<bool> EmitTestAnnotations(
158 "pipeliner-annotate-for-testing", cl::Hidden
, cl::init(false),
159 cl::desc("Instead of emitting the pipelined code, annotate instructions "
160 "with the generated schedule for feeding into the "
161 "-modulo-schedule-test pass"));
163 static cl::opt
<bool> ExperimentalCodeGen(
164 "pipeliner-experimental-cg", cl::Hidden
, cl::init(false),
166 "Use the experimental peeling code generator for software pipelining"));
170 // A command line option to enable the CopyToPhi DAG mutation.
171 cl::opt
<bool> SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden
,
173 cl::desc("Enable CopyToPhi DAG Mutation"));
175 } // end namespace llvm
177 unsigned SwingSchedulerDAG::Circuits::MaxPaths
= 5;
178 char MachinePipeliner::ID
= 0;
180 int MachinePipeliner::NumTries
= 0;
182 char &llvm::MachinePipelinerID
= MachinePipeliner::ID
;
184 INITIALIZE_PASS_BEGIN(MachinePipeliner
, DEBUG_TYPE
,
185 "Modulo Software Pipelining", false, false)
186 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass
)
187 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo
)
188 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
189 INITIALIZE_PASS_DEPENDENCY(LiveIntervals
)
190 INITIALIZE_PASS_END(MachinePipeliner
, DEBUG_TYPE
,
191 "Modulo Software Pipelining", false, false)
193 /// The "main" function for implementing Swing Modulo Scheduling.
194 bool MachinePipeliner::runOnMachineFunction(MachineFunction
&mf
) {
195 if (skipFunction(mf
.getFunction()))
201 if (mf
.getFunction().getAttributes().hasFnAttr(Attribute::OptimizeForSize
) &&
202 !EnableSWPOptSize
.getPosition())
205 if (!mf
.getSubtarget().enableMachinePipeliner())
208 // Cannot pipeline loops without instruction itineraries if we are using
209 // DFA for the pipeliner.
210 if (mf
.getSubtarget().useDFAforSMS() &&
211 (!mf
.getSubtarget().getInstrItineraryData() ||
212 mf
.getSubtarget().getInstrItineraryData()->isEmpty()))
216 MLI
= &getAnalysis
<MachineLoopInfo
>();
217 MDT
= &getAnalysis
<MachineDominatorTree
>();
218 ORE
= &getAnalysis
<MachineOptimizationRemarkEmitterPass
>().getORE();
219 TII
= MF
->getSubtarget().getInstrInfo();
220 RegClassInfo
.runOnMachineFunction(*MF
);
222 for (const auto &L
: *MLI
)
228 /// Attempt to perform the SMS algorithm on the specified loop. This function is
229 /// the main entry point for the algorithm. The function identifies candidate
230 /// loops, calculates the minimum initiation interval, and attempts to schedule
232 bool MachinePipeliner::scheduleLoop(MachineLoop
&L
) {
233 bool Changed
= false;
234 for (const auto &InnerLoop
: L
)
235 Changed
|= scheduleLoop(*InnerLoop
);
238 // Stop trying after reaching the limit (if any).
239 int Limit
= SwpLoopLimit
;
241 if (NumTries
>= SwpLoopLimit
)
247 setPragmaPipelineOptions(L
);
248 if (!canPipelineLoop(L
)) {
249 LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
251 return MachineOptimizationRemarkMissed(DEBUG_TYPE
, "canPipelineLoop",
252 L
.getStartLoc(), L
.getHeader())
253 << "Failed to pipeline loop";
256 LI
.LoopPipelinerInfo
.reset();
262 Changed
= swingModuloScheduler(L
);
264 LI
.LoopPipelinerInfo
.reset();
268 void MachinePipeliner::setPragmaPipelineOptions(MachineLoop
&L
) {
269 // Reset the pragma for the next loop in iteration.
270 disabledByPragma
= false;
273 MachineBasicBlock
*LBLK
= L
.getTopBlock();
278 const BasicBlock
*BBLK
= LBLK
->getBasicBlock();
282 const Instruction
*TI
= BBLK
->getTerminator();
286 MDNode
*LoopID
= TI
->getMetadata(LLVMContext::MD_loop
);
287 if (LoopID
== nullptr)
290 assert(LoopID
->getNumOperands() > 0 && "requires atleast one operand");
291 assert(LoopID
->getOperand(0) == LoopID
&& "invalid loop");
293 for (unsigned i
= 1, e
= LoopID
->getNumOperands(); i
< e
; ++i
) {
294 MDNode
*MD
= dyn_cast
<MDNode
>(LoopID
->getOperand(i
));
299 MDString
*S
= dyn_cast
<MDString
>(MD
->getOperand(0));
304 if (S
->getString() == "llvm.loop.pipeline.initiationinterval") {
305 assert(MD
->getNumOperands() == 2 &&
306 "Pipeline initiation interval hint metadata should have two operands.");
308 mdconst::extract
<ConstantInt
>(MD
->getOperand(1))->getZExtValue();
309 assert(II_setByPragma
>= 1 && "Pipeline initiation interval must be positive.");
310 } else if (S
->getString() == "llvm.loop.pipeline.disable") {
311 disabledByPragma
= true;
316 /// Return true if the loop can be software pipelined. The algorithm is
317 /// restricted to loops with a single basic block. Make sure that the
318 /// branch in the loop can be analyzed.
319 bool MachinePipeliner::canPipelineLoop(MachineLoop
&L
) {
320 if (L
.getNumBlocks() != 1) {
322 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE
, "canPipelineLoop",
323 L
.getStartLoc(), L
.getHeader())
324 << "Not a single basic block: "
325 << ore::NV("NumBlocks", L
.getNumBlocks());
330 if (disabledByPragma
) {
332 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE
, "canPipelineLoop",
333 L
.getStartLoc(), L
.getHeader())
334 << "Disabled by Pragma.";
339 // Check if the branch can't be understood because we can't do pipelining
340 // if that's the case.
344 if (TII
->analyzeBranch(*L
.getHeader(), LI
.TBB
, LI
.FBB
, LI
.BrCond
)) {
345 LLVM_DEBUG(dbgs() << "Unable to analyzeBranch, can NOT pipeline Loop\n");
348 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE
, "canPipelineLoop",
349 L
.getStartLoc(), L
.getHeader())
350 << "The branch can't be understood";
355 LI
.LoopInductionVar
= nullptr;
356 LI
.LoopCompare
= nullptr;
357 LI
.LoopPipelinerInfo
= TII
->analyzeLoopForPipelining(L
.getTopBlock());
358 if (!LI
.LoopPipelinerInfo
) {
359 LLVM_DEBUG(dbgs() << "Unable to analyzeLoop, can NOT pipeline Loop\n");
362 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE
, "canPipelineLoop",
363 L
.getStartLoc(), L
.getHeader())
364 << "The loop structure is not supported";
369 if (!L
.getLoopPreheader()) {
370 LLVM_DEBUG(dbgs() << "Preheader not found, can NOT pipeline Loop\n");
373 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE
, "canPipelineLoop",
374 L
.getStartLoc(), L
.getHeader())
375 << "No loop preheader found";
380 // Remove any subregisters from inputs to phi nodes.
381 preprocessPhiNodes(*L
.getHeader());
385 void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock
&B
) {
386 MachineRegisterInfo
&MRI
= MF
->getRegInfo();
387 SlotIndexes
&Slots
= *getAnalysis
<LiveIntervals
>().getSlotIndexes();
389 for (MachineInstr
&PI
: B
.phis()) {
390 MachineOperand
&DefOp
= PI
.getOperand(0);
391 assert(DefOp
.getSubReg() == 0);
392 auto *RC
= MRI
.getRegClass(DefOp
.getReg());
394 for (unsigned i
= 1, n
= PI
.getNumOperands(); i
!= n
; i
+= 2) {
395 MachineOperand
&RegOp
= PI
.getOperand(i
);
396 if (RegOp
.getSubReg() == 0)
399 // If the operand uses a subregister, replace it with a new register
400 // without subregisters, and generate a copy to the new register.
401 Register NewReg
= MRI
.createVirtualRegister(RC
);
402 MachineBasicBlock
&PredB
= *PI
.getOperand(i
+1).getMBB();
403 MachineBasicBlock::iterator At
= PredB
.getFirstTerminator();
404 const DebugLoc
&DL
= PredB
.findDebugLoc(At
);
405 auto Copy
= BuildMI(PredB
, At
, DL
, TII
->get(TargetOpcode::COPY
), NewReg
)
406 .addReg(RegOp
.getReg(), getRegState(RegOp
),
408 Slots
.insertMachineInstrInMaps(*Copy
);
409 RegOp
.setReg(NewReg
);
415 /// The SMS algorithm consists of the following main steps:
416 /// 1. Computation and analysis of the dependence graph.
417 /// 2. Ordering of the nodes (instructions).
418 /// 3. Attempt to Schedule the loop.
419 bool MachinePipeliner::swingModuloScheduler(MachineLoop
&L
) {
420 assert(L
.getBlocks().size() == 1 && "SMS works on single blocks only.");
422 SwingSchedulerDAG
SMS(*this, L
, getAnalysis
<LiveIntervals
>(), RegClassInfo
,
423 II_setByPragma
, LI
.LoopPipelinerInfo
.get());
425 MachineBasicBlock
*MBB
= L
.getHeader();
426 // The kernel should not include any terminator instructions. These
427 // will be added back later.
430 // Compute the number of 'real' instructions in the basic block by
431 // ignoring terminators.
432 unsigned size
= MBB
->size();
433 for (MachineBasicBlock::iterator I
= MBB
->getFirstTerminator(),
434 E
= MBB
->instr_end();
438 SMS
.enterRegion(MBB
, MBB
->begin(), MBB
->getFirstTerminator(), size
);
443 return SMS
.hasNewSchedule();
446 void MachinePipeliner::getAnalysisUsage(AnalysisUsage
&AU
) const {
447 AU
.addRequired
<AAResultsWrapperPass
>();
448 AU
.addPreserved
<AAResultsWrapperPass
>();
449 AU
.addRequired
<MachineLoopInfo
>();
450 AU
.addRequired
<MachineDominatorTree
>();
451 AU
.addRequired
<LiveIntervals
>();
452 AU
.addRequired
<MachineOptimizationRemarkEmitterPass
>();
453 MachineFunctionPass::getAnalysisUsage(AU
);
456 void SwingSchedulerDAG::setMII(unsigned ResMII
, unsigned RecMII
) {
457 if (II_setByPragma
> 0)
458 MII
= II_setByPragma
;
460 MII
= std::max(ResMII
, RecMII
);
463 void SwingSchedulerDAG::setMAX_II() {
464 if (II_setByPragma
> 0)
465 MAX_II
= II_setByPragma
;
470 /// We override the schedule function in ScheduleDAGInstrs to implement the
471 /// scheduling part of the Swing Modulo Scheduling algorithm.
472 void SwingSchedulerDAG::schedule() {
473 AliasAnalysis
*AA
= &Pass
.getAnalysis
<AAResultsWrapperPass
>().getAAResults();
475 addLoopCarriedDependences(AA
);
476 updatePhiDependences();
477 Topo
.InitDAGTopologicalSorting();
482 NodeSetType NodeSets
;
483 findCircuits(NodeSets
);
484 NodeSetType Circuits
= NodeSets
;
486 // Calculate the MII.
487 unsigned ResMII
= calculateResMII();
488 unsigned RecMII
= calculateRecMII(NodeSets
);
492 // This flag is used for testing and can cause correctness problems.
496 setMII(ResMII
, RecMII
);
499 LLVM_DEBUG(dbgs() << "MII = " << MII
<< " MAX_II = " << MAX_II
500 << " (rec=" << RecMII
<< ", res=" << ResMII
<< ")\n");
502 // Can't schedule a loop without a valid MII.
504 LLVM_DEBUG(dbgs() << "Invalid Minimal Initiation Interval: 0\n");
506 Pass
.ORE
->emit([&]() {
507 return MachineOptimizationRemarkAnalysis(
508 DEBUG_TYPE
, "schedule", Loop
.getStartLoc(), Loop
.getHeader())
509 << "Invalid Minimal Initiation Interval: 0";
514 // Don't pipeline large loops.
515 if (SwpMaxMii
!= -1 && (int)MII
> SwpMaxMii
) {
516 LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
517 << ", we don't pipeline large loops\n");
518 NumFailLargeMaxMII
++;
519 Pass
.ORE
->emit([&]() {
520 return MachineOptimizationRemarkAnalysis(
521 DEBUG_TYPE
, "schedule", Loop
.getStartLoc(), Loop
.getHeader())
522 << "Minimal Initiation Interval too large: "
523 << ore::NV("MII", (int)MII
) << " > "
524 << ore::NV("SwpMaxMii", SwpMaxMii
) << "."
525 << "Refer to -pipeliner-max-mii.";
530 computeNodeFunctions(NodeSets
);
532 registerPressureFilter(NodeSets
);
534 colocateNodeSets(NodeSets
);
536 checkNodeSets(NodeSets
);
539 for (auto &I
: NodeSets
) {
540 dbgs() << " Rec NodeSet ";
545 llvm::stable_sort(NodeSets
, std::greater
<NodeSet
>());
547 groupRemainingNodes(NodeSets
);
549 removeDuplicateNodes(NodeSets
);
552 for (auto &I
: NodeSets
) {
553 dbgs() << " NodeSet ";
558 computeNodeOrder(NodeSets
);
560 // check for node order issues
561 checkValidNodeOrder(Circuits
);
563 SMSchedule
Schedule(Pass
.MF
);
564 Scheduled
= schedulePipeline(Schedule
);
567 LLVM_DEBUG(dbgs() << "No schedule found, return\n");
569 Pass
.ORE
->emit([&]() {
570 return MachineOptimizationRemarkAnalysis(
571 DEBUG_TYPE
, "schedule", Loop
.getStartLoc(), Loop
.getHeader())
572 << "Unable to find schedule";
577 unsigned numStages
= Schedule
.getMaxStageCount();
578 // No need to generate pipeline if there are no overlapped iterations.
579 if (numStages
== 0) {
580 LLVM_DEBUG(dbgs() << "No overlapped iterations, skip.\n");
582 Pass
.ORE
->emit([&]() {
583 return MachineOptimizationRemarkAnalysis(
584 DEBUG_TYPE
, "schedule", Loop
.getStartLoc(), Loop
.getHeader())
585 << "No need to pipeline - no overlapped iterations in schedule.";
589 // Check that the maximum stage count is less than user-defined limit.
590 if (SwpMaxStages
> -1 && (int)numStages
> SwpMaxStages
) {
591 LLVM_DEBUG(dbgs() << "numStages:" << numStages
<< ">" << SwpMaxStages
592 << " : too many stages, abort\n");
593 NumFailLargeMaxStage
++;
594 Pass
.ORE
->emit([&]() {
595 return MachineOptimizationRemarkAnalysis(
596 DEBUG_TYPE
, "schedule", Loop
.getStartLoc(), Loop
.getHeader())
597 << "Too many stages in schedule: "
598 << ore::NV("numStages", (int)numStages
) << " > "
599 << ore::NV("SwpMaxStages", SwpMaxStages
)
600 << ". Refer to -pipeliner-max-stages.";
605 Pass
.ORE
->emit([&]() {
606 return MachineOptimizationRemark(DEBUG_TYPE
, "schedule", Loop
.getStartLoc(),
608 << "Pipelined succesfully!";
611 // Generate the schedule as a ModuloSchedule.
612 DenseMap
<MachineInstr
*, int> Cycles
, Stages
;
613 std::vector
<MachineInstr
*> OrderedInsts
;
614 for (int Cycle
= Schedule
.getFirstCycle(); Cycle
<= Schedule
.getFinalCycle();
616 for (SUnit
*SU
: Schedule
.getInstructions(Cycle
)) {
617 OrderedInsts
.push_back(SU
->getInstr());
618 Cycles
[SU
->getInstr()] = Cycle
;
619 Stages
[SU
->getInstr()] = Schedule
.stageScheduled(SU
);
622 DenseMap
<MachineInstr
*, std::pair
<unsigned, int64_t>> NewInstrChanges
;
623 for (auto &KV
: NewMIs
) {
624 Cycles
[KV
.first
] = Cycles
[KV
.second
];
625 Stages
[KV
.first
] = Stages
[KV
.second
];
626 NewInstrChanges
[KV
.first
] = InstrChanges
[getSUnit(KV
.first
)];
629 ModuloSchedule
MS(MF
, &Loop
, std::move(OrderedInsts
), std::move(Cycles
),
631 if (EmitTestAnnotations
) {
632 assert(NewInstrChanges
.empty() &&
633 "Cannot serialize a schedule with InstrChanges!");
634 ModuloScheduleTestAnnotater
MSTI(MF
, MS
);
638 // The experimental code generator can't work if there are InstChanges.
639 if (ExperimentalCodeGen
&& NewInstrChanges
.empty()) {
640 PeelingModuloScheduleExpander
MSE(MF
, MS
, &LIS
);
643 ModuloScheduleExpander
MSE(MF
, MS
, LIS
, std::move(NewInstrChanges
));
650 /// Clean up after the software pipeliner runs.
651 void SwingSchedulerDAG::finishBlock() {
652 for (auto &KV
: NewMIs
)
653 MF
.deleteMachineInstr(KV
.second
);
656 // Call the superclass.
657 ScheduleDAGInstrs::finishBlock();
660 /// Return the register values for the operands of a Phi instruction.
661 /// This function assume the instruction is a Phi.
662 static void getPhiRegs(MachineInstr
&Phi
, MachineBasicBlock
*Loop
,
663 unsigned &InitVal
, unsigned &LoopVal
) {
664 assert(Phi
.isPHI() && "Expecting a Phi.");
668 for (unsigned i
= 1, e
= Phi
.getNumOperands(); i
!= e
; i
+= 2)
669 if (Phi
.getOperand(i
+ 1).getMBB() != Loop
)
670 InitVal
= Phi
.getOperand(i
).getReg();
672 LoopVal
= Phi
.getOperand(i
).getReg();
674 assert(InitVal
!= 0 && LoopVal
!= 0 && "Unexpected Phi structure.");
677 /// Return the Phi register value that comes the loop block.
678 static unsigned getLoopPhiReg(MachineInstr
&Phi
, MachineBasicBlock
*LoopBB
) {
679 for (unsigned i
= 1, e
= Phi
.getNumOperands(); i
!= e
; i
+= 2)
680 if (Phi
.getOperand(i
+ 1).getMBB() == LoopBB
)
681 return Phi
.getOperand(i
).getReg();
685 /// Return true if SUb can be reached from SUa following the chain edges.
686 static bool isSuccOrder(SUnit
*SUa
, SUnit
*SUb
) {
687 SmallPtrSet
<SUnit
*, 8> Visited
;
688 SmallVector
<SUnit
*, 8> Worklist
;
689 Worklist
.push_back(SUa
);
690 while (!Worklist
.empty()) {
691 const SUnit
*SU
= Worklist
.pop_back_val();
692 for (const auto &SI
: SU
->Succs
) {
693 SUnit
*SuccSU
= SI
.getSUnit();
694 if (SI
.getKind() == SDep::Order
) {
695 if (Visited
.count(SuccSU
))
699 Worklist
.push_back(SuccSU
);
700 Visited
.insert(SuccSU
);
707 /// Return true if the instruction causes a chain between memory
708 /// references before and after it.
709 static bool isDependenceBarrier(MachineInstr
&MI
) {
710 return MI
.isCall() || MI
.mayRaiseFPException() ||
711 MI
.hasUnmodeledSideEffects() ||
712 (MI
.hasOrderedMemoryRef() &&
713 (!MI
.mayLoad() || !MI
.isDereferenceableInvariantLoad()));
716 /// Return the underlying objects for the memory references of an instruction.
717 /// This function calls the code in ValueTracking, but first checks that the
718 /// instruction has a memory operand.
719 static void getUnderlyingObjects(const MachineInstr
*MI
,
720 SmallVectorImpl
<const Value
*> &Objs
) {
721 if (!MI
->hasOneMemOperand())
723 MachineMemOperand
*MM
= *MI
->memoperands_begin();
726 getUnderlyingObjects(MM
->getValue(), Objs
);
727 for (const Value
*V
: Objs
) {
728 if (!isIdentifiedObject(V
)) {
736 /// Add a chain edge between a load and store if the store can be an
737 /// alias of the load on a subsequent iteration, i.e., a loop carried
738 /// dependence. This code is very similar to the code in ScheduleDAGInstrs
739 /// but that code doesn't create loop carried dependences.
740 void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis
*AA
) {
741 MapVector
<const Value
*, SmallVector
<SUnit
*, 4>> PendingLoads
;
742 Value
*UnknownValue
=
743 UndefValue::get(Type::getVoidTy(MF
.getFunction().getContext()));
744 for (auto &SU
: SUnits
) {
745 MachineInstr
&MI
= *SU
.getInstr();
746 if (isDependenceBarrier(MI
))
747 PendingLoads
.clear();
748 else if (MI
.mayLoad()) {
749 SmallVector
<const Value
*, 4> Objs
;
750 ::getUnderlyingObjects(&MI
, Objs
);
752 Objs
.push_back(UnknownValue
);
753 for (const auto *V
: Objs
) {
754 SmallVector
<SUnit
*, 4> &SUs
= PendingLoads
[V
];
757 } else if (MI
.mayStore()) {
758 SmallVector
<const Value
*, 4> Objs
;
759 ::getUnderlyingObjects(&MI
, Objs
);
761 Objs
.push_back(UnknownValue
);
762 for (const auto *V
: Objs
) {
763 MapVector
<const Value
*, SmallVector
<SUnit
*, 4>>::iterator I
=
764 PendingLoads
.find(V
);
765 if (I
== PendingLoads
.end())
767 for (auto *Load
: I
->second
) {
768 if (isSuccOrder(Load
, &SU
))
770 MachineInstr
&LdMI
= *Load
->getInstr();
771 // First, perform the cheaper check that compares the base register.
772 // If they are the same and the load offset is less than the store
773 // offset, then mark the dependence as loop carried potentially.
774 const MachineOperand
*BaseOp1
, *BaseOp2
;
775 int64_t Offset1
, Offset2
;
776 bool Offset1IsScalable
, Offset2IsScalable
;
777 if (TII
->getMemOperandWithOffset(LdMI
, BaseOp1
, Offset1
,
778 Offset1IsScalable
, TRI
) &&
779 TII
->getMemOperandWithOffset(MI
, BaseOp2
, Offset2
,
780 Offset2IsScalable
, TRI
)) {
781 if (BaseOp1
->isIdenticalTo(*BaseOp2
) &&
782 Offset1IsScalable
== Offset2IsScalable
&&
783 (int)Offset1
< (int)Offset2
) {
784 assert(TII
->areMemAccessesTriviallyDisjoint(LdMI
, MI
) &&
785 "What happened to the chain edge?");
786 SDep
Dep(Load
, SDep::Barrier
);
792 // Second, the more expensive check that uses alias analysis on the
793 // base registers. If they alias, and the load offset is less than
794 // the store offset, the mark the dependence as loop carried.
796 SDep
Dep(Load
, SDep::Barrier
);
801 MachineMemOperand
*MMO1
= *LdMI
.memoperands_begin();
802 MachineMemOperand
*MMO2
= *MI
.memoperands_begin();
803 if (!MMO1
->getValue() || !MMO2
->getValue()) {
804 SDep
Dep(Load
, SDep::Barrier
);
809 if (MMO1
->getValue() == MMO2
->getValue() &&
810 MMO1
->getOffset() <= MMO2
->getOffset()) {
811 SDep
Dep(Load
, SDep::Barrier
);
817 MemoryLocation::getAfter(MMO1
->getValue(), MMO1
->getAAInfo()),
818 MemoryLocation::getAfter(MMO2
->getValue(),
819 MMO2
->getAAInfo()))) {
820 SDep
Dep(Load
, SDep::Barrier
);
830 /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
831 /// processes dependences for PHIs. This function adds true dependences
832 /// from a PHI to a use, and a loop carried dependence from the use to the
833 /// PHI. The loop carried dependence is represented as an anti dependence
834 /// edge. This function also removes chain dependences between unrelated
836 void SwingSchedulerDAG::updatePhiDependences() {
837 SmallVector
<SDep
, 4> RemoveDeps
;
838 const TargetSubtargetInfo
&ST
= MF
.getSubtarget
<TargetSubtargetInfo
>();
840 // Iterate over each DAG node.
841 for (SUnit
&I
: SUnits
) {
843 // Set to true if the instruction has an operand defined by a Phi.
844 unsigned HasPhiUse
= 0;
845 unsigned HasPhiDef
= 0;
846 MachineInstr
*MI
= I
.getInstr();
847 // Iterate over each operand, and we process the definitions.
848 for (MachineInstr::mop_iterator MOI
= MI
->operands_begin(),
849 MOE
= MI
->operands_end();
853 Register Reg
= MOI
->getReg();
855 // If the register is used by a Phi, then create an anti dependence.
856 for (MachineRegisterInfo::use_instr_iterator
857 UI
= MRI
.use_instr_begin(Reg
),
858 UE
= MRI
.use_instr_end();
860 MachineInstr
*UseMI
= &*UI
;
861 SUnit
*SU
= getSUnit(UseMI
);
862 if (SU
!= nullptr && UseMI
->isPHI()) {
864 SDep
Dep(SU
, SDep::Anti
, Reg
);
869 // Add a chain edge to a dependent Phi that isn't an existing
871 if (SU
->NodeNum
< I
.NodeNum
&& !I
.isPred(SU
))
872 I
.addPred(SDep(SU
, SDep::Barrier
));
876 } else if (MOI
->isUse()) {
877 // If the register is defined by a Phi, then create a true dependence.
878 MachineInstr
*DefMI
= MRI
.getUniqueVRegDef(Reg
);
879 if (DefMI
== nullptr)
881 SUnit
*SU
= getSUnit(DefMI
);
882 if (SU
!= nullptr && DefMI
->isPHI()) {
884 SDep
Dep(SU
, SDep::Data
, Reg
);
886 ST
.adjustSchedDependency(SU
, 0, &I
, MI
->getOperandNo(MOI
), Dep
);
890 // Add a chain edge to a dependent Phi that isn't an existing
892 if (SU
->NodeNum
< I
.NodeNum
&& !I
.isPred(SU
))
893 I
.addPred(SDep(SU
, SDep::Barrier
));
898 // Remove order dependences from an unrelated Phi.
901 for (auto &PI
: I
.Preds
) {
902 MachineInstr
*PMI
= PI
.getSUnit()->getInstr();
903 if (PMI
->isPHI() && PI
.getKind() == SDep::Order
) {
904 if (I
.getInstr()->isPHI()) {
905 if (PMI
->getOperand(0).getReg() == HasPhiUse
)
907 if (getLoopPhiReg(*PMI
, PMI
->getParent()) == HasPhiDef
)
910 RemoveDeps
.push_back(PI
);
913 for (int i
= 0, e
= RemoveDeps
.size(); i
!= e
; ++i
)
914 I
.removePred(RemoveDeps
[i
]);
918 /// Iterate over each DAG node and see if we can change any dependences
919 /// in order to reduce the recurrence MII.
920 void SwingSchedulerDAG::changeDependences() {
921 // See if an instruction can use a value from the previous iteration.
922 // If so, we update the base and offset of the instruction and change
924 for (SUnit
&I
: SUnits
) {
925 unsigned BasePos
= 0, OffsetPos
= 0, NewBase
= 0;
926 int64_t NewOffset
= 0;
927 if (!canUseLastOffsetValue(I
.getInstr(), BasePos
, OffsetPos
, NewBase
,
931 // Get the MI and SUnit for the instruction that defines the original base.
932 Register OrigBase
= I
.getInstr()->getOperand(BasePos
).getReg();
933 MachineInstr
*DefMI
= MRI
.getUniqueVRegDef(OrigBase
);
936 SUnit
*DefSU
= getSUnit(DefMI
);
939 // Get the MI and SUnit for the instruction that defins the new base.
940 MachineInstr
*LastMI
= MRI
.getUniqueVRegDef(NewBase
);
943 SUnit
*LastSU
= getSUnit(LastMI
);
947 if (Topo
.IsReachable(&I
, LastSU
))
950 // Remove the dependence. The value now depends on a prior iteration.
951 SmallVector
<SDep
, 4> Deps
;
952 for (const SDep
&P
: I
.Preds
)
953 if (P
.getSUnit() == DefSU
)
955 for (int i
= 0, e
= Deps
.size(); i
!= e
; i
++) {
956 Topo
.RemovePred(&I
, Deps
[i
].getSUnit());
957 I
.removePred(Deps
[i
]);
959 // Remove the chain dependence between the instructions.
961 for (auto &P
: LastSU
->Preds
)
962 if (P
.getSUnit() == &I
&& P
.getKind() == SDep::Order
)
964 for (int i
= 0, e
= Deps
.size(); i
!= e
; i
++) {
965 Topo
.RemovePred(LastSU
, Deps
[i
].getSUnit());
966 LastSU
->removePred(Deps
[i
]);
969 // Add a dependence between the new instruction and the instruction
970 // that defines the new base.
971 SDep
Dep(&I
, SDep::Anti
, NewBase
);
972 Topo
.AddPred(LastSU
, &I
);
973 LastSU
->addPred(Dep
);
975 // Remember the base and offset information so that we can update the
976 // instruction during code generation.
977 InstrChanges
[&I
] = std::make_pair(NewBase
, NewOffset
);
983 // FuncUnitSorter - Comparison operator used to sort instructions by
984 // the number of functional unit choices.
985 struct FuncUnitSorter
{
986 const InstrItineraryData
*InstrItins
;
987 const MCSubtargetInfo
*STI
;
988 DenseMap
<InstrStage::FuncUnits
, unsigned> Resources
;
990 FuncUnitSorter(const TargetSubtargetInfo
&TSI
)
991 : InstrItins(TSI
.getInstrItineraryData()), STI(&TSI
) {}
993 // Compute the number of functional unit alternatives needed
994 // at each stage, and take the minimum value. We prioritize the
995 // instructions by the least number of choices first.
996 unsigned minFuncUnits(const MachineInstr
*Inst
,
997 InstrStage::FuncUnits
&F
) const {
998 unsigned SchedClass
= Inst
->getDesc().getSchedClass();
999 unsigned min
= UINT_MAX
;
1000 if (InstrItins
&& !InstrItins
->isEmpty()) {
1001 for (const InstrStage
&IS
:
1002 make_range(InstrItins
->beginStage(SchedClass
),
1003 InstrItins
->endStage(SchedClass
))) {
1004 InstrStage::FuncUnits funcUnits
= IS
.getUnits();
1005 unsigned numAlternatives
= countPopulation(funcUnits
);
1006 if (numAlternatives
< min
) {
1007 min
= numAlternatives
;
1013 if (STI
&& STI
->getSchedModel().hasInstrSchedModel()) {
1014 const MCSchedClassDesc
*SCDesc
=
1015 STI
->getSchedModel().getSchedClassDesc(SchedClass
);
1016 if (!SCDesc
->isValid())
1017 // No valid Schedule Class Desc for schedClass, should be
1018 // Pseudo/PostRAPseudo
1021 for (const MCWriteProcResEntry
&PRE
:
1022 make_range(STI
->getWriteProcResBegin(SCDesc
),
1023 STI
->getWriteProcResEnd(SCDesc
))) {
1026 const MCProcResourceDesc
*ProcResource
=
1027 STI
->getSchedModel().getProcResource(PRE
.ProcResourceIdx
);
1028 unsigned NumUnits
= ProcResource
->NumUnits
;
1029 if (NumUnits
< min
) {
1031 F
= PRE
.ProcResourceIdx
;
1036 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1039 // Compute the critical resources needed by the instruction. This
1040 // function records the functional units needed by instructions that
1041 // must use only one functional unit. We use this as a tie breaker
1042 // for computing the resource MII. The instrutions that require
1043 // the same, highly used, functional unit have high priority.
1044 void calcCriticalResources(MachineInstr
&MI
) {
1045 unsigned SchedClass
= MI
.getDesc().getSchedClass();
1046 if (InstrItins
&& !InstrItins
->isEmpty()) {
1047 for (const InstrStage
&IS
:
1048 make_range(InstrItins
->beginStage(SchedClass
),
1049 InstrItins
->endStage(SchedClass
))) {
1050 InstrStage::FuncUnits FuncUnits
= IS
.getUnits();
1051 if (countPopulation(FuncUnits
) == 1)
1052 Resources
[FuncUnits
]++;
1056 if (STI
&& STI
->getSchedModel().hasInstrSchedModel()) {
1057 const MCSchedClassDesc
*SCDesc
=
1058 STI
->getSchedModel().getSchedClassDesc(SchedClass
);
1059 if (!SCDesc
->isValid())
1060 // No valid Schedule Class Desc for schedClass, should be
1061 // Pseudo/PostRAPseudo
1064 for (const MCWriteProcResEntry
&PRE
:
1065 make_range(STI
->getWriteProcResBegin(SCDesc
),
1066 STI
->getWriteProcResEnd(SCDesc
))) {
1069 Resources
[PRE
.ProcResourceIdx
]++;
1073 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1076 /// Return true if IS1 has less priority than IS2.
1077 bool operator()(const MachineInstr
*IS1
, const MachineInstr
*IS2
) const {
1078 InstrStage::FuncUnits F1
= 0, F2
= 0;
1079 unsigned MFUs1
= minFuncUnits(IS1
, F1
);
1080 unsigned MFUs2
= minFuncUnits(IS2
, F2
);
1082 return Resources
.lookup(F1
) < Resources
.lookup(F2
);
1083 return MFUs1
> MFUs2
;
1087 } // end anonymous namespace
1089 /// Calculate the resource constrained minimum initiation interval for the
1090 /// specified loop. We use the DFA to model the resources needed for
1091 /// each instruction, and we ignore dependences. A different DFA is created
1092 /// for each cycle that is required. When adding a new instruction, we attempt
1093 /// to add it to each existing DFA, until a legal space is found. If the
1094 /// instruction cannot be reserved in an existing DFA, we create a new one.
1095 unsigned SwingSchedulerDAG::calculateResMII() {
1097 LLVM_DEBUG(dbgs() << "calculateResMII:\n");
1098 SmallVector
<ResourceManager
*, 8> Resources
;
1099 MachineBasicBlock
*MBB
= Loop
.getHeader();
1100 Resources
.push_back(new ResourceManager(&MF
.getSubtarget()));
1102 // Sort the instructions by the number of available choices for scheduling,
1103 // least to most. Use the number of critical resources as the tie breaker.
1104 FuncUnitSorter FUS
= FuncUnitSorter(MF
.getSubtarget());
1105 for (MachineInstr
&MI
:
1106 llvm::make_range(MBB
->getFirstNonPHI(), MBB
->getFirstTerminator()))
1107 FUS
.calcCriticalResources(MI
);
1108 PriorityQueue
<MachineInstr
*, std::vector
<MachineInstr
*>, FuncUnitSorter
>
1111 for (MachineInstr
&MI
:
1112 llvm::make_range(MBB
->getFirstNonPHI(), MBB
->getFirstTerminator()))
1113 FuncUnitOrder
.push(&MI
);
1115 while (!FuncUnitOrder
.empty()) {
1116 MachineInstr
*MI
= FuncUnitOrder
.top();
1117 FuncUnitOrder
.pop();
1118 if (TII
->isZeroCost(MI
->getOpcode()))
1120 // Attempt to reserve the instruction in an existing DFA. At least one
1121 // DFA is needed for each cycle.
1122 unsigned NumCycles
= getSUnit(MI
)->Latency
;
1123 unsigned ReservedCycles
= 0;
1124 SmallVectorImpl
<ResourceManager
*>::iterator RI
= Resources
.begin();
1125 SmallVectorImpl
<ResourceManager
*>::iterator RE
= Resources
.end();
1127 dbgs() << "Trying to reserve resource for " << NumCycles
1128 << " cycles for \n";
1131 for (unsigned C
= 0; C
< NumCycles
; ++C
)
1133 if ((*RI
)->canReserveResources(*MI
)) {
1134 (*RI
)->reserveResources(*MI
);
1140 LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
1141 << ", NumCycles:" << NumCycles
<< "\n");
1142 // Add new DFAs, if needed, to reserve resources.
1143 for (unsigned C
= ReservedCycles
; C
< NumCycles
; ++C
) {
1144 LLVM_DEBUG(if (SwpDebugResource
) dbgs()
1145 << "NewResource created to reserve resources"
1147 ResourceManager
*NewResource
= new ResourceManager(&MF
.getSubtarget());
1148 assert(NewResource
->canReserveResources(*MI
) && "Reserve error.");
1149 NewResource
->reserveResources(*MI
);
1150 Resources
.push_back(NewResource
);
1153 int Resmii
= Resources
.size();
1154 LLVM_DEBUG(dbgs() << "Return Res MII:" << Resmii
<< "\n");
1155 // Delete the memory for each of the DFAs that were created earlier.
1156 for (ResourceManager
*RI
: Resources
) {
1157 ResourceManager
*D
= RI
;
1164 /// Calculate the recurrence-constrainted minimum initiation interval.
1165 /// Iterate over each circuit. Compute the delay(c) and distance(c)
1166 /// for each circuit. The II needs to satisfy the inequality
1167 /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
1168 /// II that satisfies the inequality, and the RecMII is the maximum
1169 /// of those values.
1170 unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType
&NodeSets
) {
1171 unsigned RecMII
= 0;
1173 for (NodeSet
&Nodes
: NodeSets
) {
1177 unsigned Delay
= Nodes
.getLatency();
1178 unsigned Distance
= 1;
1180 // ii = ceil(delay / distance)
1181 unsigned CurMII
= (Delay
+ Distance
- 1) / Distance
;
1182 Nodes
.setRecMII(CurMII
);
1183 if (CurMII
> RecMII
)
1190 /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1191 /// but we do this to find the circuits, and then change them back.
1192 static void swapAntiDependences(std::vector
<SUnit
> &SUnits
) {
1193 SmallVector
<std::pair
<SUnit
*, SDep
>, 8> DepsAdded
;
1194 for (SUnit
&SU
: SUnits
) {
1195 for (SDep
&Pred
: SU
.Preds
)
1196 if (Pred
.getKind() == SDep::Anti
)
1197 DepsAdded
.push_back(std::make_pair(&SU
, Pred
));
1199 for (std::pair
<SUnit
*, SDep
> &P
: DepsAdded
) {
1200 // Remove this anti dependency and add one in the reverse direction.
1201 SUnit
*SU
= P
.first
;
1203 SUnit
*TargetSU
= D
.getSUnit();
1204 unsigned Reg
= D
.getReg();
1205 unsigned Lat
= D
.getLatency();
1207 SDep
Dep(SU
, SDep::Anti
, Reg
);
1208 Dep
.setLatency(Lat
);
1209 TargetSU
->addPred(Dep
);
1213 /// Create the adjacency structure of the nodes in the graph.
1214 void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1215 SwingSchedulerDAG
*DAG
) {
1216 BitVector
Added(SUnits
.size());
1217 DenseMap
<int, int> OutputDeps
;
1218 for (int i
= 0, e
= SUnits
.size(); i
!= e
; ++i
) {
1220 // Add any successor to the adjacency matrix and exclude duplicates.
1221 for (auto &SI
: SUnits
[i
].Succs
) {
1222 // Only create a back-edge on the first and last nodes of a dependence
1223 // chain. This records any chains and adds them later.
1224 if (SI
.getKind() == SDep::Output
) {
1225 int N
= SI
.getSUnit()->NodeNum
;
1227 auto Dep
= OutputDeps
.find(BackEdge
);
1228 if (Dep
!= OutputDeps
.end()) {
1229 BackEdge
= Dep
->second
;
1230 OutputDeps
.erase(Dep
);
1232 OutputDeps
[N
] = BackEdge
;
1234 // Do not process a boundary node, an artificial node.
1235 // A back-edge is processed only if it goes to a Phi.
1236 if (SI
.getSUnit()->isBoundaryNode() || SI
.isArtificial() ||
1237 (SI
.getKind() == SDep::Anti
&& !SI
.getSUnit()->getInstr()->isPHI()))
1239 int N
= SI
.getSUnit()->NodeNum
;
1240 if (!Added
.test(N
)) {
1241 AdjK
[i
].push_back(N
);
1245 // A chain edge between a store and a load is treated as a back-edge in the
1246 // adjacency matrix.
1247 for (auto &PI
: SUnits
[i
].Preds
) {
1248 if (!SUnits
[i
].getInstr()->mayStore() ||
1249 !DAG
->isLoopCarriedDep(&SUnits
[i
], PI
, false))
1251 if (PI
.getKind() == SDep::Order
&& PI
.getSUnit()->getInstr()->mayLoad()) {
1252 int N
= PI
.getSUnit()->NodeNum
;
1253 if (!Added
.test(N
)) {
1254 AdjK
[i
].push_back(N
);
1260 // Add back-edges in the adjacency matrix for the output dependences.
1261 for (auto &OD
: OutputDeps
)
1262 if (!Added
.test(OD
.second
)) {
1263 AdjK
[OD
.first
].push_back(OD
.second
);
1264 Added
.set(OD
.second
);
1268 /// Identify an elementary circuit in the dependence graph starting at the
1270 bool SwingSchedulerDAG::Circuits::circuit(int V
, int S
, NodeSetType
&NodeSets
,
1272 SUnit
*SV
= &SUnits
[V
];
1277 for (auto W
: AdjK
[V
]) {
1278 if (NumPaths
> MaxPaths
)
1284 NodeSets
.push_back(NodeSet(Stack
.begin(), Stack
.end()));
1288 } else if (!Blocked
.test(W
)) {
1289 if (circuit(W
, S
, NodeSets
,
1290 Node2Idx
->at(W
) < Node2Idx
->at(V
) ? true : HasBackedge
))
1298 for (auto W
: AdjK
[V
]) {
1308 /// Unblock a node in the circuit finding algorithm.
1309 void SwingSchedulerDAG::Circuits::unblock(int U
) {
1311 SmallPtrSet
<SUnit
*, 4> &BU
= B
[U
];
1312 while (!BU
.empty()) {
1313 SmallPtrSet
<SUnit
*, 4>::iterator SI
= BU
.begin();
1314 assert(SI
!= BU
.end() && "Invalid B set.");
1317 if (Blocked
.test(W
->NodeNum
))
1318 unblock(W
->NodeNum
);
1322 /// Identify all the elementary circuits in the dependence graph using
1323 /// Johnson's circuit algorithm.
1324 void SwingSchedulerDAG::findCircuits(NodeSetType
&NodeSets
) {
1325 // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1326 // but we do this to find the circuits, and then change them back.
1327 swapAntiDependences(SUnits
);
1329 Circuits
Cir(SUnits
, Topo
);
1330 // Create the adjacency structure.
1331 Cir
.createAdjacencyStructure(this);
1332 for (int i
= 0, e
= SUnits
.size(); i
!= e
; ++i
) {
1334 Cir
.circuit(i
, i
, NodeSets
);
1337 // Change the dependences back so that we've created a DAG again.
1338 swapAntiDependences(SUnits
);
1341 // Create artificial dependencies between the source of COPY/REG_SEQUENCE that
1342 // is loop-carried to the USE in next iteration. This will help pipeliner avoid
1343 // additional copies that are needed across iterations. An artificial dependence
1344 // edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
1346 // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
1347 // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
1348 // PHI-------True-Dep------> USEOfPhi
1350 // The mutation creates
1351 // USEOfPHI -------Artificial-Dep---> SRCOfCopy
1353 // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
1354 // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
1355 // late to avoid additional copies across iterations. The possible scheduling
1357 // USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE.
1359 void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs
*DAG
) {
1360 for (SUnit
&SU
: DAG
->SUnits
) {
1361 // Find the COPY/REG_SEQUENCE instruction.
1362 if (!SU
.getInstr()->isCopy() && !SU
.getInstr()->isRegSequence())
1365 // Record the loop carried PHIs.
1366 SmallVector
<SUnit
*, 4> PHISUs
;
1367 // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
1368 SmallVector
<SUnit
*, 4> SrcSUs
;
1370 for (auto &Dep
: SU
.Preds
) {
1371 SUnit
*TmpSU
= Dep
.getSUnit();
1372 MachineInstr
*TmpMI
= TmpSU
->getInstr();
1373 SDep::Kind DepKind
= Dep
.getKind();
1374 // Save the loop carried PHI.
1375 if (DepKind
== SDep::Anti
&& TmpMI
->isPHI())
1376 PHISUs
.push_back(TmpSU
);
1377 // Save the source of COPY/REG_SEQUENCE.
1378 // If the source has no pre-decessors, we will end up creating cycles.
1379 else if (DepKind
== SDep::Data
&& !TmpMI
->isPHI() && TmpSU
->NumPreds
> 0)
1380 SrcSUs
.push_back(TmpSU
);
1383 if (PHISUs
.size() == 0 || SrcSUs
.size() == 0)
1386 // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
1387 // SUnit to the container.
1388 SmallVector
<SUnit
*, 8> UseSUs
;
1389 // Do not use iterator based loop here as we are updating the container.
1390 for (size_t Index
= 0; Index
< PHISUs
.size(); ++Index
) {
1391 for (auto &Dep
: PHISUs
[Index
]->Succs
) {
1392 if (Dep
.getKind() != SDep::Data
)
1395 SUnit
*TmpSU
= Dep
.getSUnit();
1396 MachineInstr
*TmpMI
= TmpSU
->getInstr();
1397 if (TmpMI
->isPHI() || TmpMI
->isRegSequence()) {
1398 PHISUs
.push_back(TmpSU
);
1401 UseSUs
.push_back(TmpSU
);
1405 if (UseSUs
.size() == 0)
1408 SwingSchedulerDAG
*SDAG
= cast
<SwingSchedulerDAG
>(DAG
);
1409 // Add the artificial dependencies if it does not form a cycle.
1410 for (auto *I
: UseSUs
) {
1411 for (auto *Src
: SrcSUs
) {
1412 if (!SDAG
->Topo
.IsReachable(I
, Src
) && Src
!= I
) {
1413 Src
->addPred(SDep(I
, SDep::Artificial
));
1414 SDAG
->Topo
.AddPred(Src
, I
);
1421 /// Return true for DAG nodes that we ignore when computing the cost functions.
1422 /// We ignore the back-edge recurrence in order to avoid unbounded recursion
1423 /// in the calculation of the ASAP, ALAP, etc functions.
1424 static bool ignoreDependence(const SDep
&D
, bool isPred
) {
1425 if (D
.isArtificial() || D
.getSUnit()->isBoundaryNode())
1427 return D
.getKind() == SDep::Anti
&& isPred
;
1430 /// Compute several functions need to order the nodes for scheduling.
1431 /// ASAP - Earliest time to schedule a node.
1432 /// ALAP - Latest time to schedule a node.
1433 /// MOV - Mobility function, difference between ALAP and ASAP.
1434 /// D - Depth of each node.
1435 /// H - Height of each node.
1436 void SwingSchedulerDAG::computeNodeFunctions(NodeSetType
&NodeSets
) {
1437 ScheduleInfo
.resize(SUnits
.size());
1440 for (int I
: Topo
) {
1441 const SUnit
&SU
= SUnits
[I
];
1447 // Compute ASAP and ZeroLatencyDepth.
1448 for (int I
: Topo
) {
1450 int zeroLatencyDepth
= 0;
1451 SUnit
*SU
= &SUnits
[I
];
1452 for (const SDep
&P
: SU
->Preds
) {
1453 SUnit
*pred
= P
.getSUnit();
1454 if (P
.getLatency() == 0)
1456 std::max(zeroLatencyDepth
, getZeroLatencyDepth(pred
) + 1);
1457 if (ignoreDependence(P
, true))
1459 asap
= std::max(asap
, (int)(getASAP(pred
) + P
.getLatency() -
1460 getDistance(pred
, SU
, P
) * MII
));
1462 maxASAP
= std::max(maxASAP
, asap
);
1463 ScheduleInfo
[I
].ASAP
= asap
;
1464 ScheduleInfo
[I
].ZeroLatencyDepth
= zeroLatencyDepth
;
1467 // Compute ALAP, ZeroLatencyHeight, and MOV.
1468 for (int I
: llvm::reverse(Topo
)) {
1470 int zeroLatencyHeight
= 0;
1471 SUnit
*SU
= &SUnits
[I
];
1472 for (const SDep
&S
: SU
->Succs
) {
1473 SUnit
*succ
= S
.getSUnit();
1474 if (succ
->isBoundaryNode())
1476 if (S
.getLatency() == 0)
1478 std::max(zeroLatencyHeight
, getZeroLatencyHeight(succ
) + 1);
1479 if (ignoreDependence(S
, true))
1481 alap
= std::min(alap
, (int)(getALAP(succ
) - S
.getLatency() +
1482 getDistance(SU
, succ
, S
) * MII
));
1485 ScheduleInfo
[I
].ALAP
= alap
;
1486 ScheduleInfo
[I
].ZeroLatencyHeight
= zeroLatencyHeight
;
1489 // After computing the node functions, compute the summary for each node set.
1490 for (NodeSet
&I
: NodeSets
)
1491 I
.computeNodeSetInfo(this);
1494 for (unsigned i
= 0; i
< SUnits
.size(); i
++) {
1495 dbgs() << "\tNode " << i
<< ":\n";
1496 dbgs() << "\t ASAP = " << getASAP(&SUnits
[i
]) << "\n";
1497 dbgs() << "\t ALAP = " << getALAP(&SUnits
[i
]) << "\n";
1498 dbgs() << "\t MOV = " << getMOV(&SUnits
[i
]) << "\n";
1499 dbgs() << "\t D = " << getDepth(&SUnits
[i
]) << "\n";
1500 dbgs() << "\t H = " << getHeight(&SUnits
[i
]) << "\n";
1501 dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits
[i
]) << "\n";
1502 dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits
[i
]) << "\n";
1507 /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1508 /// as the predecessors of the elements of NodeOrder that are not also in
1510 static bool pred_L(SetVector
<SUnit
*> &NodeOrder
,
1511 SmallSetVector
<SUnit
*, 8> &Preds
,
1512 const NodeSet
*S
= nullptr) {
1514 for (const SUnit
*SU
: NodeOrder
) {
1515 for (const SDep
&Pred
: SU
->Preds
) {
1516 if (S
&& S
->count(Pred
.getSUnit()) == 0)
1518 if (ignoreDependence(Pred
, true))
1520 if (NodeOrder
.count(Pred
.getSUnit()) == 0)
1521 Preds
.insert(Pred
.getSUnit());
1523 // Back-edges are predecessors with an anti-dependence.
1524 for (const SDep
&Succ
: SU
->Succs
) {
1525 if (Succ
.getKind() != SDep::Anti
)
1527 if (S
&& S
->count(Succ
.getSUnit()) == 0)
1529 if (NodeOrder
.count(Succ
.getSUnit()) == 0)
1530 Preds
.insert(Succ
.getSUnit());
1533 return !Preds
.empty();
1536 /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1537 /// as the successors of the elements of NodeOrder that are not also in
1539 static bool succ_L(SetVector
<SUnit
*> &NodeOrder
,
1540 SmallSetVector
<SUnit
*, 8> &Succs
,
1541 const NodeSet
*S
= nullptr) {
1543 for (const SUnit
*SU
: NodeOrder
) {
1544 for (const SDep
&Succ
: SU
->Succs
) {
1545 if (S
&& S
->count(Succ
.getSUnit()) == 0)
1547 if (ignoreDependence(Succ
, false))
1549 if (NodeOrder
.count(Succ
.getSUnit()) == 0)
1550 Succs
.insert(Succ
.getSUnit());
1552 for (const SDep
&Pred
: SU
->Preds
) {
1553 if (Pred
.getKind() != SDep::Anti
)
1555 if (S
&& S
->count(Pred
.getSUnit()) == 0)
1557 if (NodeOrder
.count(Pred
.getSUnit()) == 0)
1558 Succs
.insert(Pred
.getSUnit());
1561 return !Succs
.empty();
1564 /// Return true if there is a path from the specified node to any of the nodes
1565 /// in DestNodes. Keep track and return the nodes in any path.
1566 static bool computePath(SUnit
*Cur
, SetVector
<SUnit
*> &Path
,
1567 SetVector
<SUnit
*> &DestNodes
,
1568 SetVector
<SUnit
*> &Exclude
,
1569 SmallPtrSet
<SUnit
*, 8> &Visited
) {
1570 if (Cur
->isBoundaryNode())
1572 if (Exclude
.contains(Cur
))
1574 if (DestNodes
.contains(Cur
))
1576 if (!Visited
.insert(Cur
).second
)
1577 return Path
.contains(Cur
);
1578 bool FoundPath
= false;
1579 for (auto &SI
: Cur
->Succs
)
1580 if (!ignoreDependence(SI
, false))
1582 computePath(SI
.getSUnit(), Path
, DestNodes
, Exclude
, Visited
);
1583 for (auto &PI
: Cur
->Preds
)
1584 if (PI
.getKind() == SDep::Anti
)
1586 computePath(PI
.getSUnit(), Path
, DestNodes
, Exclude
, Visited
);
1592 /// Compute the live-out registers for the instructions in a node-set.
1593 /// The live-out registers are those that are defined in the node-set,
1594 /// but not used. Except for use operands of Phis.
1595 static void computeLiveOuts(MachineFunction
&MF
, RegPressureTracker
&RPTracker
,
1597 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
1598 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
1599 SmallVector
<RegisterMaskPair
, 8> LiveOutRegs
;
1600 SmallSet
<unsigned, 4> Uses
;
1601 for (SUnit
*SU
: NS
) {
1602 const MachineInstr
*MI
= SU
->getInstr();
1605 for (const MachineOperand
&MO
: MI
->operands())
1606 if (MO
.isReg() && MO
.isUse()) {
1607 Register Reg
= MO
.getReg();
1608 if (Register::isVirtualRegister(Reg
))
1610 else if (MRI
.isAllocatable(Reg
))
1611 for (MCRegUnitIterator
Units(Reg
.asMCReg(), TRI
); Units
.isValid();
1613 Uses
.insert(*Units
);
1616 for (SUnit
*SU
: NS
)
1617 for (const MachineOperand
&MO
: SU
->getInstr()->operands())
1618 if (MO
.isReg() && MO
.isDef() && !MO
.isDead()) {
1619 Register Reg
= MO
.getReg();
1620 if (Register::isVirtualRegister(Reg
)) {
1621 if (!Uses
.count(Reg
))
1622 LiveOutRegs
.push_back(RegisterMaskPair(Reg
,
1623 LaneBitmask::getNone()));
1624 } else if (MRI
.isAllocatable(Reg
)) {
1625 for (MCRegUnitIterator
Units(Reg
.asMCReg(), TRI
); Units
.isValid();
1627 if (!Uses
.count(*Units
))
1628 LiveOutRegs
.push_back(RegisterMaskPair(*Units
,
1629 LaneBitmask::getNone()));
1632 RPTracker
.addLiveRegs(LiveOutRegs
);
1635 /// A heuristic to filter nodes in recurrent node-sets if the register
1636 /// pressure of a set is too high.
1637 void SwingSchedulerDAG::registerPressureFilter(NodeSetType
&NodeSets
) {
1638 for (auto &NS
: NodeSets
) {
1639 // Skip small node-sets since they won't cause register pressure problems.
1642 IntervalPressure RecRegPressure
;
1643 RegPressureTracker
RecRPTracker(RecRegPressure
);
1644 RecRPTracker
.init(&MF
, &RegClassInfo
, &LIS
, BB
, BB
->end(), false, true);
1645 computeLiveOuts(MF
, RecRPTracker
, NS
);
1646 RecRPTracker
.closeBottom();
1648 std::vector
<SUnit
*> SUnits(NS
.begin(), NS
.end());
1649 llvm::sort(SUnits
, [](const SUnit
*A
, const SUnit
*B
) {
1650 return A
->NodeNum
> B
->NodeNum
;
1653 for (auto &SU
: SUnits
) {
1654 // Since we're computing the register pressure for a subset of the
1655 // instructions in a block, we need to set the tracker for each
1656 // instruction in the node-set. The tracker is set to the instruction
1657 // just after the one we're interested in.
1658 MachineBasicBlock::const_iterator CurInstI
= SU
->getInstr();
1659 RecRPTracker
.setPos(std::next(CurInstI
));
1661 RegPressureDelta RPDelta
;
1662 ArrayRef
<PressureChange
> CriticalPSets
;
1663 RecRPTracker
.getMaxUpwardPressureDelta(SU
->getInstr(), nullptr, RPDelta
,
1665 RecRegPressure
.MaxSetPressure
);
1666 if (RPDelta
.Excess
.isValid()) {
1668 dbgs() << "Excess register pressure: SU(" << SU
->NodeNum
<< ") "
1669 << TRI
->getRegPressureSetName(RPDelta
.Excess
.getPSet())
1670 << ":" << RPDelta
.Excess
.getUnitInc() << "\n");
1671 NS
.setExceedPressure(SU
);
1674 RecRPTracker
.recede();
1679 /// A heuristic to colocate node sets that have the same set of
1681 void SwingSchedulerDAG::colocateNodeSets(NodeSetType
&NodeSets
) {
1682 unsigned Colocate
= 0;
1683 for (int i
= 0, e
= NodeSets
.size(); i
< e
; ++i
) {
1684 NodeSet
&N1
= NodeSets
[i
];
1685 SmallSetVector
<SUnit
*, 8> S1
;
1686 if (N1
.empty() || !succ_L(N1
, S1
))
1688 for (int j
= i
+ 1; j
< e
; ++j
) {
1689 NodeSet
&N2
= NodeSets
[j
];
1690 if (N1
.compareRecMII(N2
) != 0)
1692 SmallSetVector
<SUnit
*, 8> S2
;
1693 if (N2
.empty() || !succ_L(N2
, S2
))
1695 if (llvm::set_is_subset(S1
, S2
) && S1
.size() == S2
.size()) {
1696 N1
.setColocate(++Colocate
);
1697 N2
.setColocate(Colocate
);
1704 /// Check if the existing node-sets are profitable. If not, then ignore the
1705 /// recurrent node-sets, and attempt to schedule all nodes together. This is
1706 /// a heuristic. If the MII is large and all the recurrent node-sets are small,
1707 /// then it's best to try to schedule all instructions together instead of
1708 /// starting with the recurrent node-sets.
1709 void SwingSchedulerDAG::checkNodeSets(NodeSetType
&NodeSets
) {
1710 // Look for loops with a large MII.
1713 // Check if the node-set contains only a simple add recurrence.
1714 for (auto &NS
: NodeSets
) {
1715 if (NS
.getRecMII() > 2)
1717 if (NS
.getMaxDepth() > MII
)
1721 LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
1724 /// Add the nodes that do not belong to a recurrence set into groups
1725 /// based upon connected components.
1726 void SwingSchedulerDAG::groupRemainingNodes(NodeSetType
&NodeSets
) {
1727 SetVector
<SUnit
*> NodesAdded
;
1728 SmallPtrSet
<SUnit
*, 8> Visited
;
1729 // Add the nodes that are on a path between the previous node sets and
1730 // the current node set.
1731 for (NodeSet
&I
: NodeSets
) {
1732 SmallSetVector
<SUnit
*, 8> N
;
1733 // Add the nodes from the current node set to the previous node set.
1735 SetVector
<SUnit
*> Path
;
1736 for (SUnit
*NI
: N
) {
1738 computePath(NI
, Path
, NodesAdded
, I
, Visited
);
1741 I
.insert(Path
.begin(), Path
.end());
1743 // Add the nodes from the previous node set to the current node set.
1745 if (succ_L(NodesAdded
, N
)) {
1746 SetVector
<SUnit
*> Path
;
1747 for (SUnit
*NI
: N
) {
1749 computePath(NI
, Path
, I
, NodesAdded
, Visited
);
1752 I
.insert(Path
.begin(), Path
.end());
1754 NodesAdded
.insert(I
.begin(), I
.end());
1757 // Create a new node set with the connected nodes of any successor of a node
1758 // in a recurrent set.
1760 SmallSetVector
<SUnit
*, 8> N
;
1761 if (succ_L(NodesAdded
, N
))
1763 addConnectedNodes(I
, NewSet
, NodesAdded
);
1764 if (!NewSet
.empty())
1765 NodeSets
.push_back(NewSet
);
1767 // Create a new node set with the connected nodes of any predecessor of a node
1768 // in a recurrent set.
1770 if (pred_L(NodesAdded
, N
))
1772 addConnectedNodes(I
, NewSet
, NodesAdded
);
1773 if (!NewSet
.empty())
1774 NodeSets
.push_back(NewSet
);
1776 // Create new nodes sets with the connected nodes any remaining node that
1777 // has no predecessor.
1778 for (SUnit
&SU
: SUnits
) {
1779 if (NodesAdded
.count(&SU
) == 0) {
1781 addConnectedNodes(&SU
, NewSet
, NodesAdded
);
1782 if (!NewSet
.empty())
1783 NodeSets
.push_back(NewSet
);
1788 /// Add the node to the set, and add all of its connected nodes to the set.
1789 void SwingSchedulerDAG::addConnectedNodes(SUnit
*SU
, NodeSet
&NewSet
,
1790 SetVector
<SUnit
*> &NodesAdded
) {
1792 NodesAdded
.insert(SU
);
1793 for (auto &SI
: SU
->Succs
) {
1794 SUnit
*Successor
= SI
.getSUnit();
1795 if (!SI
.isArtificial() && !Successor
->isBoundaryNode() &&
1796 NodesAdded
.count(Successor
) == 0)
1797 addConnectedNodes(Successor
, NewSet
, NodesAdded
);
1799 for (auto &PI
: SU
->Preds
) {
1800 SUnit
*Predecessor
= PI
.getSUnit();
1801 if (!PI
.isArtificial() && NodesAdded
.count(Predecessor
) == 0)
1802 addConnectedNodes(Predecessor
, NewSet
, NodesAdded
);
1806 /// Return true if Set1 contains elements in Set2. The elements in common
1807 /// are returned in a different container.
1808 static bool isIntersect(SmallSetVector
<SUnit
*, 8> &Set1
, const NodeSet
&Set2
,
1809 SmallSetVector
<SUnit
*, 8> &Result
) {
1811 for (SUnit
*SU
: Set1
) {
1812 if (Set2
.count(SU
) != 0)
1815 return !Result
.empty();
1818 /// Merge the recurrence node sets that have the same initial node.
1819 void SwingSchedulerDAG::fuseRecs(NodeSetType
&NodeSets
) {
1820 for (NodeSetType::iterator I
= NodeSets
.begin(), E
= NodeSets
.end(); I
!= E
;
1823 for (NodeSetType::iterator J
= I
+ 1; J
!= E
;) {
1825 if (NI
.getNode(0)->NodeNum
== NJ
.getNode(0)->NodeNum
) {
1826 if (NJ
.compareRecMII(NI
) > 0)
1827 NI
.setRecMII(NJ
.getRecMII());
1828 for (SUnit
*SU
: *J
)
1839 /// Remove nodes that have been scheduled in previous NodeSets.
1840 void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType
&NodeSets
) {
1841 for (NodeSetType::iterator I
= NodeSets
.begin(), E
= NodeSets
.end(); I
!= E
;
1843 for (NodeSetType::iterator J
= I
+ 1; J
!= E
;) {
1844 J
->remove_if([&](SUnit
*SUJ
) { return I
->count(SUJ
); });
1855 /// Compute an ordered list of the dependence graph nodes, which
1856 /// indicates the order that the nodes will be scheduled. This is a
1857 /// two-level algorithm. First, a partial order is created, which
1858 /// consists of a list of sets ordered from highest to lowest priority.
1859 void SwingSchedulerDAG::computeNodeOrder(NodeSetType
&NodeSets
) {
1860 SmallSetVector
<SUnit
*, 8> R
;
1863 for (auto &Nodes
: NodeSets
) {
1864 LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes
.size() << "\n");
1866 SmallSetVector
<SUnit
*, 8> N
;
1867 if (pred_L(NodeOrder
, N
) && llvm::set_is_subset(N
, Nodes
)) {
1868 R
.insert(N
.begin(), N
.end());
1870 LLVM_DEBUG(dbgs() << " Bottom up (preds) ");
1871 } else if (succ_L(NodeOrder
, N
) && llvm::set_is_subset(N
, Nodes
)) {
1872 R
.insert(N
.begin(), N
.end());
1874 LLVM_DEBUG(dbgs() << " Top down (succs) ");
1875 } else if (isIntersect(N
, Nodes
, R
)) {
1876 // If some of the successors are in the existing node-set, then use the
1877 // top-down ordering.
1879 LLVM_DEBUG(dbgs() << " Top down (intersect) ");
1880 } else if (NodeSets
.size() == 1) {
1881 for (const auto &N
: Nodes
)
1882 if (N
->Succs
.size() == 0)
1885 LLVM_DEBUG(dbgs() << " Bottom up (all) ");
1887 // Find the node with the highest ASAP.
1888 SUnit
*maxASAP
= nullptr;
1889 for (SUnit
*SU
: Nodes
) {
1890 if (maxASAP
== nullptr || getASAP(SU
) > getASAP(maxASAP
) ||
1891 (getASAP(SU
) == getASAP(maxASAP
) && SU
->NodeNum
> maxASAP
->NodeNum
))
1896 LLVM_DEBUG(dbgs() << " Bottom up (default) ");
1899 while (!R
.empty()) {
1900 if (Order
== TopDown
) {
1901 // Choose the node with the maximum height. If more than one, choose
1902 // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
1903 // choose the node with the lowest MOV.
1904 while (!R
.empty()) {
1905 SUnit
*maxHeight
= nullptr;
1906 for (SUnit
*I
: R
) {
1907 if (maxHeight
== nullptr || getHeight(I
) > getHeight(maxHeight
))
1909 else if (getHeight(I
) == getHeight(maxHeight
) &&
1910 getZeroLatencyHeight(I
) > getZeroLatencyHeight(maxHeight
))
1912 else if (getHeight(I
) == getHeight(maxHeight
) &&
1913 getZeroLatencyHeight(I
) ==
1914 getZeroLatencyHeight(maxHeight
) &&
1915 getMOV(I
) < getMOV(maxHeight
))
1918 NodeOrder
.insert(maxHeight
);
1919 LLVM_DEBUG(dbgs() << maxHeight
->NodeNum
<< " ");
1920 R
.remove(maxHeight
);
1921 for (const auto &I
: maxHeight
->Succs
) {
1922 if (Nodes
.count(I
.getSUnit()) == 0)
1924 if (NodeOrder
.contains(I
.getSUnit()))
1926 if (ignoreDependence(I
, false))
1928 R
.insert(I
.getSUnit());
1930 // Back-edges are predecessors with an anti-dependence.
1931 for (const auto &I
: maxHeight
->Preds
) {
1932 if (I
.getKind() != SDep::Anti
)
1934 if (Nodes
.count(I
.getSUnit()) == 0)
1936 if (NodeOrder
.contains(I
.getSUnit()))
1938 R
.insert(I
.getSUnit());
1942 LLVM_DEBUG(dbgs() << "\n Switching order to bottom up ");
1943 SmallSetVector
<SUnit
*, 8> N
;
1944 if (pred_L(NodeOrder
, N
, &Nodes
))
1945 R
.insert(N
.begin(), N
.end());
1947 // Choose the node with the maximum depth. If more than one, choose
1948 // the node with the maximum ZeroLatencyDepth. If still more than one,
1949 // choose the node with the lowest MOV.
1950 while (!R
.empty()) {
1951 SUnit
*maxDepth
= nullptr;
1952 for (SUnit
*I
: R
) {
1953 if (maxDepth
== nullptr || getDepth(I
) > getDepth(maxDepth
))
1955 else if (getDepth(I
) == getDepth(maxDepth
) &&
1956 getZeroLatencyDepth(I
) > getZeroLatencyDepth(maxDepth
))
1958 else if (getDepth(I
) == getDepth(maxDepth
) &&
1959 getZeroLatencyDepth(I
) == getZeroLatencyDepth(maxDepth
) &&
1960 getMOV(I
) < getMOV(maxDepth
))
1963 NodeOrder
.insert(maxDepth
);
1964 LLVM_DEBUG(dbgs() << maxDepth
->NodeNum
<< " ");
1966 if (Nodes
.isExceedSU(maxDepth
)) {
1969 R
.insert(Nodes
.getNode(0));
1972 for (const auto &I
: maxDepth
->Preds
) {
1973 if (Nodes
.count(I
.getSUnit()) == 0)
1975 if (NodeOrder
.contains(I
.getSUnit()))
1977 R
.insert(I
.getSUnit());
1979 // Back-edges are predecessors with an anti-dependence.
1980 for (const auto &I
: maxDepth
->Succs
) {
1981 if (I
.getKind() != SDep::Anti
)
1983 if (Nodes
.count(I
.getSUnit()) == 0)
1985 if (NodeOrder
.contains(I
.getSUnit()))
1987 R
.insert(I
.getSUnit());
1991 LLVM_DEBUG(dbgs() << "\n Switching order to top down ");
1992 SmallSetVector
<SUnit
*, 8> N
;
1993 if (succ_L(NodeOrder
, N
, &Nodes
))
1994 R
.insert(N
.begin(), N
.end());
1997 LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
2001 dbgs() << "Node order: ";
2002 for (SUnit
*I
: NodeOrder
)
2003 dbgs() << " " << I
->NodeNum
<< " ";
2008 /// Process the nodes in the computed order and create the pipelined schedule
2009 /// of the instructions, if possible. Return true if a schedule is found.
2010 bool SwingSchedulerDAG::schedulePipeline(SMSchedule
&Schedule
) {
2012 if (NodeOrder
.empty()){
2013 LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
2017 bool scheduleFound
= false;
2018 // Keep increasing II until a valid schedule is found.
2019 for (unsigned II
= MII
; II
<= MAX_II
&& !scheduleFound
; ++II
) {
2021 Schedule
.setInitiationInterval(II
);
2022 LLVM_DEBUG(dbgs() << "Try to schedule with " << II
<< "\n");
2024 SetVector
<SUnit
*>::iterator NI
= NodeOrder
.begin();
2025 SetVector
<SUnit
*>::iterator NE
= NodeOrder
.end();
2029 // Compute the schedule time for the instruction, which is based
2030 // upon the scheduled time for any predecessors/successors.
2031 int EarlyStart
= INT_MIN
;
2032 int LateStart
= INT_MAX
;
2033 // These values are set when the size of the schedule window is limited
2034 // due to chain dependences.
2035 int SchedEnd
= INT_MAX
;
2036 int SchedStart
= INT_MIN
;
2037 Schedule
.computeStart(SU
, &EarlyStart
, &LateStart
, &SchedEnd
, &SchedStart
,
2041 dbgs() << "Inst (" << SU
->NodeNum
<< ") ";
2042 SU
->getInstr()->dump();
2046 dbgs() << format("\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart
,
2047 LateStart
, SchedEnd
, SchedStart
);
2050 if (EarlyStart
> LateStart
|| SchedEnd
< EarlyStart
||
2051 SchedStart
> LateStart
)
2052 scheduleFound
= false;
2053 else if (EarlyStart
!= INT_MIN
&& LateStart
== INT_MAX
) {
2054 SchedEnd
= std::min(SchedEnd
, EarlyStart
+ (int)II
- 1);
2055 scheduleFound
= Schedule
.insert(SU
, EarlyStart
, SchedEnd
, II
);
2056 } else if (EarlyStart
== INT_MIN
&& LateStart
!= INT_MAX
) {
2057 SchedStart
= std::max(SchedStart
, LateStart
- (int)II
+ 1);
2058 scheduleFound
= Schedule
.insert(SU
, LateStart
, SchedStart
, II
);
2059 } else if (EarlyStart
!= INT_MIN
&& LateStart
!= INT_MAX
) {
2061 std::min(SchedEnd
, std::min(LateStart
, EarlyStart
+ (int)II
- 1));
2062 // When scheduling a Phi it is better to start at the late cycle and go
2063 // backwards. The default order may insert the Phi too far away from
2064 // its first dependence.
2065 if (SU
->getInstr()->isPHI())
2066 scheduleFound
= Schedule
.insert(SU
, SchedEnd
, EarlyStart
, II
);
2068 scheduleFound
= Schedule
.insert(SU
, EarlyStart
, SchedEnd
, II
);
2070 int FirstCycle
= Schedule
.getFirstCycle();
2071 scheduleFound
= Schedule
.insert(SU
, FirstCycle
+ getASAP(SU
),
2072 FirstCycle
+ getASAP(SU
) + II
- 1, II
);
2074 // Even if we find a schedule, make sure the schedule doesn't exceed the
2075 // allowable number of stages. We keep trying if this happens.
2077 if (SwpMaxStages
> -1 &&
2078 Schedule
.getMaxStageCount() > (unsigned)SwpMaxStages
)
2079 scheduleFound
= false;
2083 dbgs() << "\tCan't schedule\n";
2085 } while (++NI
!= NE
&& scheduleFound
);
2087 // If a schedule is found, ensure non-pipelined instructions are in stage 0
2090 Schedule
.normalizeNonPipelinedInstructions(this, LoopPipelinerInfo
);
2092 // If a schedule is found, check if it is a valid schedule too.
2094 scheduleFound
= Schedule
.isValidSchedule(this);
2097 LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound
2098 << " (II=" << Schedule
.getInitiationInterval()
2101 if (scheduleFound
) {
2102 scheduleFound
= LoopPipelinerInfo
->shouldUseSchedule(*this, Schedule
);
2104 dbgs() << "Target rejected schedule\n";
2107 if (scheduleFound
) {
2108 Schedule
.finalizeSchedule(this);
2109 Pass
.ORE
->emit([&]() {
2110 return MachineOptimizationRemarkAnalysis(
2111 DEBUG_TYPE
, "schedule", Loop
.getStartLoc(), Loop
.getHeader())
2112 << "Schedule found with Initiation Interval: "
2113 << ore::NV("II", Schedule
.getInitiationInterval())
2114 << ", MaxStageCount: "
2115 << ore::NV("MaxStageCount", Schedule
.getMaxStageCount());
2120 return scheduleFound
&& Schedule
.getMaxStageCount() > 0;
2123 /// Return true if we can compute the amount the instruction changes
2124 /// during each iteration. Set Delta to the amount of the change.
2125 bool SwingSchedulerDAG::computeDelta(MachineInstr
&MI
, unsigned &Delta
) {
2126 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
2127 const MachineOperand
*BaseOp
;
2129 bool OffsetIsScalable
;
2130 if (!TII
->getMemOperandWithOffset(MI
, BaseOp
, Offset
, OffsetIsScalable
, TRI
))
2133 // FIXME: This algorithm assumes instructions have fixed-size offsets.
2134 if (OffsetIsScalable
)
2137 if (!BaseOp
->isReg())
2140 Register BaseReg
= BaseOp
->getReg();
2142 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
2143 // Check if there is a Phi. If so, get the definition in the loop.
2144 MachineInstr
*BaseDef
= MRI
.getVRegDef(BaseReg
);
2145 if (BaseDef
&& BaseDef
->isPHI()) {
2146 BaseReg
= getLoopPhiReg(*BaseDef
, MI
.getParent());
2147 BaseDef
= MRI
.getVRegDef(BaseReg
);
2153 if (!TII
->getIncrementValue(*BaseDef
, D
) && D
>= 0)
2160 /// Check if we can change the instruction to use an offset value from the
2161 /// previous iteration. If so, return true and set the base and offset values
2162 /// so that we can rewrite the load, if necessary.
2163 /// v1 = Phi(v0, v3)
2165 /// v3 = post_store v1, 4, x
2166 /// This function enables the load to be rewritten as v2 = load v3, 4.
2167 bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr
*MI
,
2169 unsigned &OffsetPos
,
2172 // Get the load instruction.
2173 if (TII
->isPostIncrement(*MI
))
2175 unsigned BasePosLd
, OffsetPosLd
;
2176 if (!TII
->getBaseAndOffsetPosition(*MI
, BasePosLd
, OffsetPosLd
))
2178 Register BaseReg
= MI
->getOperand(BasePosLd
).getReg();
2180 // Look for the Phi instruction.
2181 MachineRegisterInfo
&MRI
= MI
->getMF()->getRegInfo();
2182 MachineInstr
*Phi
= MRI
.getVRegDef(BaseReg
);
2183 if (!Phi
|| !Phi
->isPHI())
2185 // Get the register defined in the loop block.
2186 unsigned PrevReg
= getLoopPhiReg(*Phi
, MI
->getParent());
2190 // Check for the post-increment load/store instruction.
2191 MachineInstr
*PrevDef
= MRI
.getVRegDef(PrevReg
);
2192 if (!PrevDef
|| PrevDef
== MI
)
2195 if (!TII
->isPostIncrement(*PrevDef
))
2198 unsigned BasePos1
= 0, OffsetPos1
= 0;
2199 if (!TII
->getBaseAndOffsetPosition(*PrevDef
, BasePos1
, OffsetPos1
))
2202 // Make sure that the instructions do not access the same memory location in
2203 // the next iteration.
2204 int64_t LoadOffset
= MI
->getOperand(OffsetPosLd
).getImm();
2205 int64_t StoreOffset
= PrevDef
->getOperand(OffsetPos1
).getImm();
2206 MachineInstr
*NewMI
= MF
.CloneMachineInstr(MI
);
2207 NewMI
->getOperand(OffsetPosLd
).setImm(LoadOffset
+ StoreOffset
);
2208 bool Disjoint
= TII
->areMemAccessesTriviallyDisjoint(*NewMI
, *PrevDef
);
2209 MF
.deleteMachineInstr(NewMI
);
2213 // Set the return value once we determine that we return true.
2214 BasePos
= BasePosLd
;
2215 OffsetPos
= OffsetPosLd
;
2217 Offset
= StoreOffset
;
2221 /// Apply changes to the instruction if needed. The changes are need
2222 /// to improve the scheduling and depend up on the final schedule.
2223 void SwingSchedulerDAG::applyInstrChange(MachineInstr
*MI
,
2224 SMSchedule
&Schedule
) {
2225 SUnit
*SU
= getSUnit(MI
);
2226 DenseMap
<SUnit
*, std::pair
<unsigned, int64_t>>::iterator It
=
2227 InstrChanges
.find(SU
);
2228 if (It
!= InstrChanges
.end()) {
2229 std::pair
<unsigned, int64_t> RegAndOffset
= It
->second
;
2230 unsigned BasePos
, OffsetPos
;
2231 if (!TII
->getBaseAndOffsetPosition(*MI
, BasePos
, OffsetPos
))
2233 Register BaseReg
= MI
->getOperand(BasePos
).getReg();
2234 MachineInstr
*LoopDef
= findDefInLoop(BaseReg
);
2235 int DefStageNum
= Schedule
.stageScheduled(getSUnit(LoopDef
));
2236 int DefCycleNum
= Schedule
.cycleScheduled(getSUnit(LoopDef
));
2237 int BaseStageNum
= Schedule
.stageScheduled(SU
);
2238 int BaseCycleNum
= Schedule
.cycleScheduled(SU
);
2239 if (BaseStageNum
< DefStageNum
) {
2240 MachineInstr
*NewMI
= MF
.CloneMachineInstr(MI
);
2241 int OffsetDiff
= DefStageNum
- BaseStageNum
;
2242 if (DefCycleNum
< BaseCycleNum
) {
2243 NewMI
->getOperand(BasePos
).setReg(RegAndOffset
.first
);
2248 MI
->getOperand(OffsetPos
).getImm() + RegAndOffset
.second
* OffsetDiff
;
2249 NewMI
->getOperand(OffsetPos
).setImm(NewOffset
);
2250 SU
->setInstr(NewMI
);
2251 MISUnitMap
[NewMI
] = SU
;
2257 /// Return the instruction in the loop that defines the register.
2258 /// If the definition is a Phi, then follow the Phi operand to
2259 /// the instruction in the loop.
2260 MachineInstr
*SwingSchedulerDAG::findDefInLoop(Register Reg
) {
2261 SmallPtrSet
<MachineInstr
*, 8> Visited
;
2262 MachineInstr
*Def
= MRI
.getVRegDef(Reg
);
2263 while (Def
->isPHI()) {
2264 if (!Visited
.insert(Def
).second
)
2266 for (unsigned i
= 1, e
= Def
->getNumOperands(); i
< e
; i
+= 2)
2267 if (Def
->getOperand(i
+ 1).getMBB() == BB
) {
2268 Def
= MRI
.getVRegDef(Def
->getOperand(i
).getReg());
2275 /// Return true for an order or output dependence that is loop carried
2276 /// potentially. A dependence is loop carried if the destination defines a valu
2277 /// that may be used or defined by the source in a subsequent iteration.
2278 bool SwingSchedulerDAG::isLoopCarriedDep(SUnit
*Source
, const SDep
&Dep
,
2280 if ((Dep
.getKind() != SDep::Order
&& Dep
.getKind() != SDep::Output
) ||
2281 Dep
.isArtificial() || Dep
.getSUnit()->isBoundaryNode())
2284 if (!SwpPruneLoopCarried
)
2287 if (Dep
.getKind() == SDep::Output
)
2290 MachineInstr
*SI
= Source
->getInstr();
2291 MachineInstr
*DI
= Dep
.getSUnit()->getInstr();
2294 assert(SI
!= nullptr && DI
!= nullptr && "Expecting SUnit with an MI.");
2296 // Assume ordered loads and stores may have a loop carried dependence.
2297 if (SI
->hasUnmodeledSideEffects() || DI
->hasUnmodeledSideEffects() ||
2298 SI
->mayRaiseFPException() || DI
->mayRaiseFPException() ||
2299 SI
->hasOrderedMemoryRef() || DI
->hasOrderedMemoryRef())
2302 // Only chain dependences between a load and store can be loop carried.
2303 if (!DI
->mayStore() || !SI
->mayLoad())
2306 unsigned DeltaS
, DeltaD
;
2307 if (!computeDelta(*SI
, DeltaS
) || !computeDelta(*DI
, DeltaD
))
2310 const MachineOperand
*BaseOpS
, *BaseOpD
;
2311 int64_t OffsetS
, OffsetD
;
2312 bool OffsetSIsScalable
, OffsetDIsScalable
;
2313 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
2314 if (!TII
->getMemOperandWithOffset(*SI
, BaseOpS
, OffsetS
, OffsetSIsScalable
,
2316 !TII
->getMemOperandWithOffset(*DI
, BaseOpD
, OffsetD
, OffsetDIsScalable
,
2320 assert(!OffsetSIsScalable
&& !OffsetDIsScalable
&&
2321 "Expected offsets to be byte offsets");
2323 if (!BaseOpS
->isIdenticalTo(*BaseOpD
))
2326 // Check that the base register is incremented by a constant value for each
2328 MachineInstr
*Def
= MRI
.getVRegDef(BaseOpS
->getReg());
2329 if (!Def
|| !Def
->isPHI())
2331 unsigned InitVal
= 0;
2332 unsigned LoopVal
= 0;
2333 getPhiRegs(*Def
, BB
, InitVal
, LoopVal
);
2334 MachineInstr
*LoopDef
= MRI
.getVRegDef(LoopVal
);
2336 if (!LoopDef
|| !TII
->getIncrementValue(*LoopDef
, D
))
2339 uint64_t AccessSizeS
= (*SI
->memoperands_begin())->getSize();
2340 uint64_t AccessSizeD
= (*DI
->memoperands_begin())->getSize();
2342 // This is the main test, which checks the offset values and the loop
2343 // increment value to determine if the accesses may be loop carried.
2344 if (AccessSizeS
== MemoryLocation::UnknownSize
||
2345 AccessSizeD
== MemoryLocation::UnknownSize
)
2348 if (DeltaS
!= DeltaD
|| DeltaS
< AccessSizeS
|| DeltaD
< AccessSizeD
)
2351 return (OffsetS
+ (int64_t)AccessSizeS
< OffsetD
+ (int64_t)AccessSizeD
);
2354 void SwingSchedulerDAG::postprocessDAG() {
2355 for (auto &M
: Mutations
)
2359 /// Try to schedule the node at the specified StartCycle and continue
2360 /// until the node is schedule or the EndCycle is reached. This function
2361 /// returns true if the node is scheduled. This routine may search either
2362 /// forward or backward for a place to insert the instruction based upon
2363 /// the relative values of StartCycle and EndCycle.
2364 bool SMSchedule::insert(SUnit
*SU
, int StartCycle
, int EndCycle
, int II
) {
2365 bool forward
= true;
2367 dbgs() << "Trying to insert node between " << StartCycle
<< " and "
2368 << EndCycle
<< " II: " << II
<< "\n";
2370 if (StartCycle
> EndCycle
)
2373 // The terminating condition depends on the direction.
2374 int termCycle
= forward
? EndCycle
+ 1 : EndCycle
- 1;
2375 for (int curCycle
= StartCycle
; curCycle
!= termCycle
;
2376 forward
? ++curCycle
: --curCycle
) {
2378 // Add the already scheduled instructions at the specified cycle to the
2380 ProcItinResources
.clearResources();
2381 for (int checkCycle
= FirstCycle
+ ((curCycle
- FirstCycle
) % II
);
2382 checkCycle
<= LastCycle
; checkCycle
+= II
) {
2383 std::deque
<SUnit
*> &cycleInstrs
= ScheduledInstrs
[checkCycle
];
2385 for (SUnit
*CI
: cycleInstrs
) {
2386 if (ST
.getInstrInfo()->isZeroCost(CI
->getInstr()->getOpcode()))
2388 assert(ProcItinResources
.canReserveResources(*CI
->getInstr()) &&
2389 "These instructions have already been scheduled.");
2390 ProcItinResources
.reserveResources(*CI
->getInstr());
2393 if (ST
.getInstrInfo()->isZeroCost(SU
->getInstr()->getOpcode()) ||
2394 ProcItinResources
.canReserveResources(*SU
->getInstr())) {
2396 dbgs() << "\tinsert at cycle " << curCycle
<< " ";
2397 SU
->getInstr()->dump();
2400 ScheduledInstrs
[curCycle
].push_back(SU
);
2401 InstrToCycle
.insert(std::make_pair(SU
, curCycle
));
2402 if (curCycle
> LastCycle
)
2403 LastCycle
= curCycle
;
2404 if (curCycle
< FirstCycle
)
2405 FirstCycle
= curCycle
;
2409 dbgs() << "\tfailed to insert at cycle " << curCycle
<< " ";
2410 SU
->getInstr()->dump();
2416 // Return the cycle of the earliest scheduled instruction in the chain.
2417 int SMSchedule::earliestCycleInChain(const SDep
&Dep
) {
2418 SmallPtrSet
<SUnit
*, 8> Visited
;
2419 SmallVector
<SDep
, 8> Worklist
;
2420 Worklist
.push_back(Dep
);
2421 int EarlyCycle
= INT_MAX
;
2422 while (!Worklist
.empty()) {
2423 const SDep
&Cur
= Worklist
.pop_back_val();
2424 SUnit
*PrevSU
= Cur
.getSUnit();
2425 if (Visited
.count(PrevSU
))
2427 std::map
<SUnit
*, int>::const_iterator it
= InstrToCycle
.find(PrevSU
);
2428 if (it
== InstrToCycle
.end())
2430 EarlyCycle
= std::min(EarlyCycle
, it
->second
);
2431 for (const auto &PI
: PrevSU
->Preds
)
2432 if (PI
.getKind() == SDep::Order
|| PI
.getKind() == SDep::Output
)
2433 Worklist
.push_back(PI
);
2434 Visited
.insert(PrevSU
);
2439 // Return the cycle of the latest scheduled instruction in the chain.
2440 int SMSchedule::latestCycleInChain(const SDep
&Dep
) {
2441 SmallPtrSet
<SUnit
*, 8> Visited
;
2442 SmallVector
<SDep
, 8> Worklist
;
2443 Worklist
.push_back(Dep
);
2444 int LateCycle
= INT_MIN
;
2445 while (!Worklist
.empty()) {
2446 const SDep
&Cur
= Worklist
.pop_back_val();
2447 SUnit
*SuccSU
= Cur
.getSUnit();
2448 if (Visited
.count(SuccSU
) || SuccSU
->isBoundaryNode())
2450 std::map
<SUnit
*, int>::const_iterator it
= InstrToCycle
.find(SuccSU
);
2451 if (it
== InstrToCycle
.end())
2453 LateCycle
= std::max(LateCycle
, it
->second
);
2454 for (const auto &SI
: SuccSU
->Succs
)
2455 if (SI
.getKind() == SDep::Order
|| SI
.getKind() == SDep::Output
)
2456 Worklist
.push_back(SI
);
2457 Visited
.insert(SuccSU
);
2462 /// If an instruction has a use that spans multiple iterations, then
2463 /// return true. These instructions are characterized by having a back-ege
2464 /// to a Phi, which contains a reference to another Phi.
2465 static SUnit
*multipleIterations(SUnit
*SU
, SwingSchedulerDAG
*DAG
) {
2466 for (auto &P
: SU
->Preds
)
2467 if (DAG
->isBackedge(SU
, P
) && P
.getSUnit()->getInstr()->isPHI())
2468 for (auto &S
: P
.getSUnit()->Succs
)
2469 if (S
.getKind() == SDep::Data
&& S
.getSUnit()->getInstr()->isPHI())
2470 return P
.getSUnit();
2474 /// Compute the scheduling start slot for the instruction. The start slot
2475 /// depends on any predecessor or successor nodes scheduled already.
2476 void SMSchedule::computeStart(SUnit
*SU
, int *MaxEarlyStart
, int *MinLateStart
,
2477 int *MinEnd
, int *MaxStart
, int II
,
2478 SwingSchedulerDAG
*DAG
) {
2479 // Iterate over each instruction that has been scheduled already. The start
2480 // slot computation depends on whether the previously scheduled instruction
2481 // is a predecessor or successor of the specified instruction.
2482 for (int cycle
= getFirstCycle(); cycle
<= LastCycle
; ++cycle
) {
2484 // Iterate over each instruction in the current cycle.
2485 for (SUnit
*I
: getInstructions(cycle
)) {
2486 // Because we're processing a DAG for the dependences, we recognize
2487 // the back-edge in recurrences by anti dependences.
2488 for (unsigned i
= 0, e
= (unsigned)SU
->Preds
.size(); i
!= e
; ++i
) {
2489 const SDep
&Dep
= SU
->Preds
[i
];
2490 if (Dep
.getSUnit() == I
) {
2491 if (!DAG
->isBackedge(SU
, Dep
)) {
2492 int EarlyStart
= cycle
+ Dep
.getLatency() -
2493 DAG
->getDistance(Dep
.getSUnit(), SU
, Dep
) * II
;
2494 *MaxEarlyStart
= std::max(*MaxEarlyStart
, EarlyStart
);
2495 if (DAG
->isLoopCarriedDep(SU
, Dep
, false)) {
2496 int End
= earliestCycleInChain(Dep
) + (II
- 1);
2497 *MinEnd
= std::min(*MinEnd
, End
);
2500 int LateStart
= cycle
- Dep
.getLatency() +
2501 DAG
->getDistance(SU
, Dep
.getSUnit(), Dep
) * II
;
2502 *MinLateStart
= std::min(*MinLateStart
, LateStart
);
2505 // For instruction that requires multiple iterations, make sure that
2506 // the dependent instruction is not scheduled past the definition.
2507 SUnit
*BE
= multipleIterations(I
, DAG
);
2508 if (BE
&& Dep
.getSUnit() == BE
&& !SU
->getInstr()->isPHI() &&
2510 *MinLateStart
= std::min(*MinLateStart
, cycle
);
2512 for (unsigned i
= 0, e
= (unsigned)SU
->Succs
.size(); i
!= e
; ++i
) {
2513 if (SU
->Succs
[i
].getSUnit() == I
) {
2514 const SDep
&Dep
= SU
->Succs
[i
];
2515 if (!DAG
->isBackedge(SU
, Dep
)) {
2516 int LateStart
= cycle
- Dep
.getLatency() +
2517 DAG
->getDistance(SU
, Dep
.getSUnit(), Dep
) * II
;
2518 *MinLateStart
= std::min(*MinLateStart
, LateStart
);
2519 if (DAG
->isLoopCarriedDep(SU
, Dep
)) {
2520 int Start
= latestCycleInChain(Dep
) + 1 - II
;
2521 *MaxStart
= std::max(*MaxStart
, Start
);
2524 int EarlyStart
= cycle
+ Dep
.getLatency() -
2525 DAG
->getDistance(Dep
.getSUnit(), SU
, Dep
) * II
;
2526 *MaxEarlyStart
= std::max(*MaxEarlyStart
, EarlyStart
);
2534 /// Order the instructions within a cycle so that the definitions occur
2535 /// before the uses. Returns true if the instruction is added to the start
2536 /// of the list, or false if added to the end.
2537 void SMSchedule::orderDependence(SwingSchedulerDAG
*SSD
, SUnit
*SU
,
2538 std::deque
<SUnit
*> &Insts
) {
2539 MachineInstr
*MI
= SU
->getInstr();
2540 bool OrderBeforeUse
= false;
2541 bool OrderAfterDef
= false;
2542 bool OrderBeforeDef
= false;
2543 unsigned MoveDef
= 0;
2544 unsigned MoveUse
= 0;
2545 int StageInst1
= stageScheduled(SU
);
2548 for (std::deque
<SUnit
*>::iterator I
= Insts
.begin(), E
= Insts
.end(); I
!= E
;
2550 for (MachineOperand
&MO
: MI
->operands()) {
2551 if (!MO
.isReg() || !Register::isVirtualRegister(MO
.getReg()))
2554 Register Reg
= MO
.getReg();
2555 unsigned BasePos
, OffsetPos
;
2556 if (ST
.getInstrInfo()->getBaseAndOffsetPosition(*MI
, BasePos
, OffsetPos
))
2557 if (MI
->getOperand(BasePos
).getReg() == Reg
)
2558 if (unsigned NewReg
= SSD
->getInstrBaseReg(SU
))
2561 std::tie(Reads
, Writes
) =
2562 (*I
)->getInstr()->readsWritesVirtualRegister(Reg
);
2563 if (MO
.isDef() && Reads
&& stageScheduled(*I
) <= StageInst1
) {
2564 OrderBeforeUse
= true;
2567 } else if (MO
.isDef() && Reads
&& stageScheduled(*I
) > StageInst1
) {
2568 // Add the instruction after the scheduled instruction.
2569 OrderAfterDef
= true;
2571 } else if (MO
.isUse() && Writes
&& stageScheduled(*I
) == StageInst1
) {
2572 if (cycleScheduled(*I
) == cycleScheduled(SU
) && !(*I
)->isSucc(SU
)) {
2573 OrderBeforeUse
= true;
2577 OrderAfterDef
= true;
2580 } else if (MO
.isUse() && Writes
&& stageScheduled(*I
) > StageInst1
) {
2581 OrderBeforeUse
= true;
2585 OrderAfterDef
= true;
2588 } else if (MO
.isUse() && Writes
&& stageScheduled(*I
) < StageInst1
) {
2589 // Add the instruction before the scheduled instruction.
2590 OrderBeforeUse
= true;
2593 } else if (MO
.isUse() && stageScheduled(*I
) == StageInst1
&&
2594 isLoopCarriedDefOfUse(SSD
, (*I
)->getInstr(), MO
)) {
2596 OrderBeforeDef
= true;
2601 // Check for order dependences between instructions. Make sure the source
2602 // is ordered before the destination.
2603 for (auto &S
: SU
->Succs
) {
2604 if (S
.getSUnit() != *I
)
2606 if (S
.getKind() == SDep::Order
&& stageScheduled(*I
) == StageInst1
) {
2607 OrderBeforeUse
= true;
2611 // We did not handle HW dependences in previous for loop,
2612 // and we normally set Latency = 0 for Anti deps,
2613 // so may have nodes in same cycle with Anti denpendent on HW regs.
2614 else if (S
.getKind() == SDep::Anti
&& stageScheduled(*I
) == StageInst1
) {
2615 OrderBeforeUse
= true;
2616 if ((MoveUse
== 0) || (Pos
< MoveUse
))
2620 for (auto &P
: SU
->Preds
) {
2621 if (P
.getSUnit() != *I
)
2623 if (P
.getKind() == SDep::Order
&& stageScheduled(*I
) == StageInst1
) {
2624 OrderAfterDef
= true;
2630 // A circular dependence.
2631 if (OrderAfterDef
&& OrderBeforeUse
&& MoveUse
== MoveDef
)
2632 OrderBeforeUse
= false;
2634 // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
2635 // to a loop-carried dependence.
2637 OrderBeforeUse
= !OrderAfterDef
|| (MoveUse
> MoveDef
);
2639 // The uncommon case when the instruction order needs to be updated because
2640 // there is both a use and def.
2641 if (OrderBeforeUse
&& OrderAfterDef
) {
2642 SUnit
*UseSU
= Insts
.at(MoveUse
);
2643 SUnit
*DefSU
= Insts
.at(MoveDef
);
2644 if (MoveUse
> MoveDef
) {
2645 Insts
.erase(Insts
.begin() + MoveUse
);
2646 Insts
.erase(Insts
.begin() + MoveDef
);
2648 Insts
.erase(Insts
.begin() + MoveDef
);
2649 Insts
.erase(Insts
.begin() + MoveUse
);
2651 orderDependence(SSD
, UseSU
, Insts
);
2652 orderDependence(SSD
, SU
, Insts
);
2653 orderDependence(SSD
, DefSU
, Insts
);
2656 // Put the new instruction first if there is a use in the list. Otherwise,
2657 // put it at the end of the list.
2659 Insts
.push_front(SU
);
2661 Insts
.push_back(SU
);
2664 /// Return true if the scheduled Phi has a loop carried operand.
2665 bool SMSchedule::isLoopCarried(SwingSchedulerDAG
*SSD
, MachineInstr
&Phi
) {
2668 assert(Phi
.isPHI() && "Expecting a Phi.");
2669 SUnit
*DefSU
= SSD
->getSUnit(&Phi
);
2670 unsigned DefCycle
= cycleScheduled(DefSU
);
2671 int DefStage
= stageScheduled(DefSU
);
2673 unsigned InitVal
= 0;
2674 unsigned LoopVal
= 0;
2675 getPhiRegs(Phi
, Phi
.getParent(), InitVal
, LoopVal
);
2676 SUnit
*UseSU
= SSD
->getSUnit(MRI
.getVRegDef(LoopVal
));
2679 if (UseSU
->getInstr()->isPHI())
2681 unsigned LoopCycle
= cycleScheduled(UseSU
);
2682 int LoopStage
= stageScheduled(UseSU
);
2683 return (LoopCycle
> DefCycle
) || (LoopStage
<= DefStage
);
2686 /// Return true if the instruction is a definition that is loop carried
2687 /// and defines the use on the next iteration.
2688 /// v1 = phi(v2, v3)
2689 /// (Def) v3 = op v1
2691 /// If MO appears before Def, then then v1 and v3 may get assigned to the same
2693 bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG
*SSD
,
2694 MachineInstr
*Def
, MachineOperand
&MO
) {
2699 MachineInstr
*Phi
= MRI
.getVRegDef(MO
.getReg());
2700 if (!Phi
|| !Phi
->isPHI() || Phi
->getParent() != Def
->getParent())
2702 if (!isLoopCarried(SSD
, *Phi
))
2704 unsigned LoopReg
= getLoopPhiReg(*Phi
, Phi
->getParent());
2705 for (unsigned i
= 0, e
= Def
->getNumOperands(); i
!= e
; ++i
) {
2706 MachineOperand
&DMO
= Def
->getOperand(i
);
2707 if (!DMO
.isReg() || !DMO
.isDef())
2709 if (DMO
.getReg() == LoopReg
)
2715 /// Determine transitive dependences of unpipelineable instructions
2716 SmallSet
<SUnit
*, 8> SMSchedule::computeUnpipelineableNodes(
2717 SwingSchedulerDAG
*SSD
, TargetInstrInfo::PipelinerLoopInfo
*PLI
) {
2718 SmallSet
<SUnit
*, 8> DoNotPipeline
;
2719 SmallVector
<SUnit
*, 8> Worklist
;
2721 for (auto &SU
: SSD
->SUnits
)
2722 if (SU
.isInstr() && PLI
->shouldIgnoreForPipelining(SU
.getInstr()))
2723 Worklist
.push_back(&SU
);
2725 while (!Worklist
.empty()) {
2726 auto SU
= Worklist
.pop_back_val();
2727 if (DoNotPipeline
.count(SU
))
2729 LLVM_DEBUG(dbgs() << "Do not pipeline SU(" << SU
->NodeNum
<< ")\n");
2730 DoNotPipeline
.insert(SU
);
2731 for (auto &Dep
: SU
->Preds
)
2732 Worklist
.push_back(Dep
.getSUnit());
2733 if (SU
->getInstr()->isPHI())
2734 for (auto &Dep
: SU
->Succs
)
2735 if (Dep
.getKind() == SDep::Anti
)
2736 Worklist
.push_back(Dep
.getSUnit());
2738 return DoNotPipeline
;
2741 // Determine all instructions upon which any unpipelineable instruction depends
2742 // and ensure that they are in stage 0. If unable to do so, return false.
2743 bool SMSchedule::normalizeNonPipelinedInstructions(
2744 SwingSchedulerDAG
*SSD
, TargetInstrInfo::PipelinerLoopInfo
*PLI
) {
2745 SmallSet
<SUnit
*, 8> DNP
= computeUnpipelineableNodes(SSD
, PLI
);
2747 int NewLastCycle
= INT_MIN
;
2748 for (SUnit
&SU
: SSD
->SUnits
) {
2751 if (!DNP
.contains(&SU
) || stageScheduled(&SU
) == 0) {
2752 NewLastCycle
= std::max(NewLastCycle
, InstrToCycle
[&SU
]);
2756 // Put the non-pipelined instruction as early as possible in the schedule
2757 int NewCycle
= getFirstCycle();
2758 for (auto &Dep
: SU
.Preds
)
2759 NewCycle
= std::max(InstrToCycle
[Dep
.getSUnit()], NewCycle
);
2761 int OldCycle
= InstrToCycle
[&SU
];
2762 if (OldCycle
!= NewCycle
) {
2763 InstrToCycle
[&SU
] = NewCycle
;
2764 auto &OldS
= getInstructions(OldCycle
);
2765 llvm::erase_value(OldS
, &SU
);
2766 getInstructions(NewCycle
).emplace_back(&SU
);
2767 LLVM_DEBUG(dbgs() << "SU(" << SU
.NodeNum
2768 << ") is not pipelined; moving from cycle " << OldCycle
2769 << " to " << NewCycle
<< " Instr:" << *SU
.getInstr());
2771 NewLastCycle
= std::max(NewLastCycle
, NewCycle
);
2773 LastCycle
= NewLastCycle
;
2777 // Check if the generated schedule is valid. This function checks if
2778 // an instruction that uses a physical register is scheduled in a
2779 // different stage than the definition. The pipeliner does not handle
2780 // physical register values that may cross a basic block boundary.
2781 // Furthermore, if a physical def/use pair is assigned to the same
2782 // cycle, orderDependence does not guarantee def/use ordering, so that
2783 // case should be considered invalid. (The test checks for both
2784 // earlier and same-cycle use to be more robust.)
2785 bool SMSchedule::isValidSchedule(SwingSchedulerDAG
*SSD
) {
2786 for (SUnit
&SU
: SSD
->SUnits
) {
2787 if (!SU
.hasPhysRegDefs
)
2789 int StageDef
= stageScheduled(&SU
);
2790 int CycleDef
= InstrToCycle
[&SU
];
2791 assert(StageDef
!= -1 && "Instruction should have been scheduled.");
2792 for (auto &SI
: SU
.Succs
)
2793 if (SI
.isAssignedRegDep() && !SI
.getSUnit()->isBoundaryNode())
2794 if (Register::isPhysicalRegister(SI
.getReg())) {
2795 if (stageScheduled(SI
.getSUnit()) != StageDef
)
2797 if (InstrToCycle
[SI
.getSUnit()] <= CycleDef
)
2804 /// A property of the node order in swing-modulo-scheduling is
2805 /// that for nodes outside circuits the following holds:
2806 /// none of them is scheduled after both a successor and a
2808 /// The method below checks whether the property is met.
2809 /// If not, debug information is printed and statistics information updated.
2810 /// Note that we do not use an assert statement.
2811 /// The reason is that although an invalid node oder may prevent
2812 /// the pipeliner from finding a pipelined schedule for arbitrary II,
2813 /// it does not lead to the generation of incorrect code.
2814 void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType
&Circuits
) const {
2816 // a sorted vector that maps each SUnit to its index in the NodeOrder
2817 typedef std::pair
<SUnit
*, unsigned> UnitIndex
;
2818 std::vector
<UnitIndex
> Indices(NodeOrder
.size(), std::make_pair(nullptr, 0));
2820 for (unsigned i
= 0, s
= NodeOrder
.size(); i
< s
; ++i
)
2821 Indices
.push_back(std::make_pair(NodeOrder
[i
], i
));
2823 auto CompareKey
= [](UnitIndex i1
, UnitIndex i2
) {
2824 return std::get
<0>(i1
) < std::get
<0>(i2
);
2827 // sort, so that we can perform a binary search
2828 llvm::sort(Indices
, CompareKey
);
2832 // for each SUnit in the NodeOrder, check whether
2833 // it appears after both a successor and a predecessor
2834 // of the SUnit. If this is the case, and the SUnit
2835 // is not part of circuit, then the NodeOrder is not
2837 for (unsigned i
= 0, s
= NodeOrder
.size(); i
< s
; ++i
) {
2838 SUnit
*SU
= NodeOrder
[i
];
2841 bool PredBefore
= false;
2842 bool SuccBefore
= false;
2849 for (SDep
&PredEdge
: SU
->Preds
) {
2850 SUnit
*PredSU
= PredEdge
.getSUnit();
2851 unsigned PredIndex
= std::get
<1>(
2852 *llvm::lower_bound(Indices
, std::make_pair(PredSU
, 0), CompareKey
));
2853 if (!PredSU
->getInstr()->isPHI() && PredIndex
< Index
) {
2860 for (SDep
&SuccEdge
: SU
->Succs
) {
2861 SUnit
*SuccSU
= SuccEdge
.getSUnit();
2862 // Do not process a boundary node, it was not included in NodeOrder,
2863 // hence not in Indices either, call to std::lower_bound() below will
2864 // return Indices.end().
2865 if (SuccSU
->isBoundaryNode())
2867 unsigned SuccIndex
= std::get
<1>(
2868 *llvm::lower_bound(Indices
, std::make_pair(SuccSU
, 0), CompareKey
));
2869 if (!SuccSU
->getInstr()->isPHI() && SuccIndex
< Index
) {
2876 if (PredBefore
&& SuccBefore
&& !SU
->getInstr()->isPHI()) {
2877 // instructions in circuits are allowed to be scheduled
2878 // after both a successor and predecessor.
2879 bool InCircuit
= llvm::any_of(
2880 Circuits
, [SU
](const NodeSet
&Circuit
) { return Circuit
.count(SU
); });
2882 LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
2885 NumNodeOrderIssues
++;
2886 LLVM_DEBUG(dbgs() << "Predecessor ";);
2888 LLVM_DEBUG(dbgs() << Pred
->NodeNum
<< " and successor " << Succ
->NodeNum
2889 << " are scheduled before node " << SU
->NodeNum
2896 dbgs() << "Invalid node order found!\n";
2900 /// Attempt to fix the degenerate cases when the instruction serialization
2901 /// causes the register lifetimes to overlap. For example,
2902 /// p' = store_pi(p, b)
2903 /// = load p, offset
2904 /// In this case p and p' overlap, which means that two registers are needed.
2905 /// Instead, this function changes the load to use p' and updates the offset.
2906 void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque
<SUnit
*> &Instrs
) {
2907 unsigned OverlapReg
= 0;
2908 unsigned NewBaseReg
= 0;
2909 for (SUnit
*SU
: Instrs
) {
2910 MachineInstr
*MI
= SU
->getInstr();
2911 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
< e
; ++i
) {
2912 const MachineOperand
&MO
= MI
->getOperand(i
);
2913 // Look for an instruction that uses p. The instruction occurs in the
2914 // same cycle but occurs later in the serialized order.
2915 if (MO
.isReg() && MO
.isUse() && MO
.getReg() == OverlapReg
) {
2916 // Check that the instruction appears in the InstrChanges structure,
2917 // which contains instructions that can have the offset updated.
2918 DenseMap
<SUnit
*, std::pair
<unsigned, int64_t>>::iterator It
=
2919 InstrChanges
.find(SU
);
2920 if (It
!= InstrChanges
.end()) {
2921 unsigned BasePos
, OffsetPos
;
2922 // Update the base register and adjust the offset.
2923 if (TII
->getBaseAndOffsetPosition(*MI
, BasePos
, OffsetPos
)) {
2924 MachineInstr
*NewMI
= MF
.CloneMachineInstr(MI
);
2925 NewMI
->getOperand(BasePos
).setReg(NewBaseReg
);
2927 MI
->getOperand(OffsetPos
).getImm() - It
->second
.second
;
2928 NewMI
->getOperand(OffsetPos
).setImm(NewOffset
);
2929 SU
->setInstr(NewMI
);
2930 MISUnitMap
[NewMI
] = SU
;
2938 // Look for an instruction of the form p' = op(p), which uses and defines
2939 // two virtual registers that get allocated to the same physical register.
2940 unsigned TiedUseIdx
= 0;
2941 if (MI
->isRegTiedToUseOperand(i
, &TiedUseIdx
)) {
2942 // OverlapReg is p in the example above.
2943 OverlapReg
= MI
->getOperand(TiedUseIdx
).getReg();
2944 // NewBaseReg is p' in the example above.
2945 NewBaseReg
= MI
->getOperand(i
).getReg();
2952 /// After the schedule has been formed, call this function to combine
2953 /// the instructions from the different stages/cycles. That is, this
2954 /// function creates a schedule that represents a single iteration.
2955 void SMSchedule::finalizeSchedule(SwingSchedulerDAG
*SSD
) {
2956 // Move all instructions to the first stage from later stages.
2957 for (int cycle
= getFirstCycle(); cycle
<= getFinalCycle(); ++cycle
) {
2958 for (int stage
= 1, lastStage
= getMaxStageCount(); stage
<= lastStage
;
2960 std::deque
<SUnit
*> &cycleInstrs
=
2961 ScheduledInstrs
[cycle
+ (stage
* InitiationInterval
)];
2962 for (SUnit
*SU
: llvm::reverse(cycleInstrs
))
2963 ScheduledInstrs
[cycle
].push_front(SU
);
2967 // Erase all the elements in the later stages. Only one iteration should
2968 // remain in the scheduled list, and it contains all the instructions.
2969 for (int cycle
= getFinalCycle() + 1; cycle
<= LastCycle
; ++cycle
)
2970 ScheduledInstrs
.erase(cycle
);
2972 // Change the registers in instruction as specified in the InstrChanges
2973 // map. We need to use the new registers to create the correct order.
2974 for (const SUnit
&SU
: SSD
->SUnits
)
2975 SSD
->applyInstrChange(SU
.getInstr(), *this);
2977 // Reorder the instructions in each cycle to fix and improve the
2979 for (int Cycle
= getFirstCycle(), E
= getFinalCycle(); Cycle
<= E
; ++Cycle
) {
2980 std::deque
<SUnit
*> &cycleInstrs
= ScheduledInstrs
[Cycle
];
2981 std::deque
<SUnit
*> newOrderPhi
;
2982 for (SUnit
*SU
: cycleInstrs
) {
2983 if (SU
->getInstr()->isPHI())
2984 newOrderPhi
.push_back(SU
);
2986 std::deque
<SUnit
*> newOrderI
;
2987 for (SUnit
*SU
: cycleInstrs
) {
2988 if (!SU
->getInstr()->isPHI())
2989 orderDependence(SSD
, SU
, newOrderI
);
2991 // Replace the old order with the new order.
2992 cycleInstrs
.swap(newOrderPhi
);
2993 llvm::append_range(cycleInstrs
, newOrderI
);
2994 SSD
->fixupRegisterOverlaps(cycleInstrs
);
2997 LLVM_DEBUG(dump(););
3000 void NodeSet::print(raw_ostream
&os
) const {
3001 os
<< "Num nodes " << size() << " rec " << RecMII
<< " mov " << MaxMOV
3002 << " depth " << MaxDepth
<< " col " << Colocate
<< "\n";
3003 for (const auto &I
: Nodes
)
3004 os
<< " SU(" << I
->NodeNum
<< ") " << *(I
->getInstr());
3008 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3009 /// Print the schedule information to the given output.
3010 void SMSchedule::print(raw_ostream
&os
) const {
3011 // Iterate over each cycle.
3012 for (int cycle
= getFirstCycle(); cycle
<= getFinalCycle(); ++cycle
) {
3013 // Iterate over each instruction in the cycle.
3014 const_sched_iterator cycleInstrs
= ScheduledInstrs
.find(cycle
);
3015 for (SUnit
*CI
: cycleInstrs
->second
) {
3016 os
<< "cycle " << cycle
<< " (" << stageScheduled(CI
) << ") ";
3017 os
<< "(" << CI
->NodeNum
<< ") ";
3018 CI
->getInstr()->print(os
);
3024 /// Utility function used for debugging to print the schedule.
3025 LLVM_DUMP_METHOD
void SMSchedule::dump() const { print(dbgs()); }
3026 LLVM_DUMP_METHOD
void NodeSet::dump() const { print(dbgs()); }
3030 void ResourceManager::initProcResourceVectors(
3031 const MCSchedModel
&SM
, SmallVectorImpl
<uint64_t> &Masks
) {
3032 unsigned ProcResourceID
= 0;
3034 // We currently limit the resource kinds to 64 and below so that we can use
3035 // uint64_t for Masks
3036 assert(SM
.getNumProcResourceKinds() < 64 &&
3037 "Too many kinds of resources, unsupported");
3038 // Create a unique bitmask for every processor resource unit.
3039 // Skip resource at index 0, since it always references 'InvalidUnit'.
3040 Masks
.resize(SM
.getNumProcResourceKinds());
3041 for (unsigned I
= 1, E
= SM
.getNumProcResourceKinds(); I
< E
; ++I
) {
3042 const MCProcResourceDesc
&Desc
= *SM
.getProcResource(I
);
3043 if (Desc
.SubUnitsIdxBegin
)
3045 Masks
[I
] = 1ULL << ProcResourceID
;
3048 // Create a unique bitmask for every processor resource group.
3049 for (unsigned I
= 1, E
= SM
.getNumProcResourceKinds(); I
< E
; ++I
) {
3050 const MCProcResourceDesc
&Desc
= *SM
.getProcResource(I
);
3051 if (!Desc
.SubUnitsIdxBegin
)
3053 Masks
[I
] = 1ULL << ProcResourceID
;
3054 for (unsigned U
= 0; U
< Desc
.NumUnits
; ++U
)
3055 Masks
[I
] |= Masks
[Desc
.SubUnitsIdxBegin
[U
]];
3059 if (SwpShowResMask
) {
3060 dbgs() << "ProcResourceDesc:\n";
3061 for (unsigned I
= 1, E
= SM
.getNumProcResourceKinds(); I
< E
; ++I
) {
3062 const MCProcResourceDesc
*ProcResource
= SM
.getProcResource(I
);
3063 dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
3064 ProcResource
->Name
, I
, Masks
[I
],
3065 ProcResource
->NumUnits
);
3067 dbgs() << " -----------------\n";
3072 bool ResourceManager::canReserveResources(const MCInstrDesc
*MID
) const {
3075 if (SwpDebugResource
)
3076 dbgs() << "canReserveResources:\n";
3079 return DFAResources
->canReserveResources(MID
);
3081 unsigned InsnClass
= MID
->getSchedClass();
3082 const MCSchedClassDesc
*SCDesc
= SM
.getSchedClassDesc(InsnClass
);
3083 if (!SCDesc
->isValid()) {
3085 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3086 dbgs() << "isPseudo:" << MID
->isPseudo() << "\n";
3091 const MCWriteProcResEntry
*I
= STI
->getWriteProcResBegin(SCDesc
);
3092 const MCWriteProcResEntry
*E
= STI
->getWriteProcResEnd(SCDesc
);
3093 for (; I
!= E
; ++I
) {
3096 const MCProcResourceDesc
*ProcResource
=
3097 SM
.getProcResource(I
->ProcResourceIdx
);
3098 unsigned NumUnits
= ProcResource
->NumUnits
;
3100 if (SwpDebugResource
)
3101 dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
3102 ProcResource
->Name
, I
->ProcResourceIdx
,
3103 ProcResourceCount
[I
->ProcResourceIdx
], NumUnits
,
3106 if (ProcResourceCount
[I
->ProcResourceIdx
] >= NumUnits
)
3109 LLVM_DEBUG(if (SwpDebugResource
) dbgs() << "return true\n\n";);
3113 void ResourceManager::reserveResources(const MCInstrDesc
*MID
) {
3115 if (SwpDebugResource
)
3116 dbgs() << "reserveResources:\n";
3119 return DFAResources
->reserveResources(MID
);
3121 unsigned InsnClass
= MID
->getSchedClass();
3122 const MCSchedClassDesc
*SCDesc
= SM
.getSchedClassDesc(InsnClass
);
3123 if (!SCDesc
->isValid()) {
3125 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3126 dbgs() << "isPseudo:" << MID
->isPseudo() << "\n";
3130 for (const MCWriteProcResEntry
&PRE
:
3131 make_range(STI
->getWriteProcResBegin(SCDesc
),
3132 STI
->getWriteProcResEnd(SCDesc
))) {
3135 ++ProcResourceCount
[PRE
.ProcResourceIdx
];
3137 if (SwpDebugResource
) {
3138 const MCProcResourceDesc
*ProcResource
=
3139 SM
.getProcResource(PRE
.ProcResourceIdx
);
3140 dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
3141 ProcResource
->Name
, PRE
.ProcResourceIdx
,
3142 ProcResourceCount
[PRE
.ProcResourceIdx
],
3143 ProcResource
->NumUnits
, PRE
.Cycles
);
3148 if (SwpDebugResource
)
3149 dbgs() << "reserveResources: done!\n\n";
3153 bool ResourceManager::canReserveResources(const MachineInstr
&MI
) const {
3154 return canReserveResources(&MI
.getDesc());
3157 void ResourceManager::reserveResources(const MachineInstr
&MI
) {
3158 return reserveResources(&MI
.getDesc());
3161 void ResourceManager::clearResources() {
3163 return DFAResources
->clearResources();
3164 std::fill(ProcResourceCount
.begin(), ProcResourceCount
.end(), 0);