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/ADT/ArrayRef.h"
33 #include "llvm/ADT/BitVector.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/MapVector.h"
36 #include "llvm/ADT/PriorityQueue.h"
37 #include "llvm/ADT/SetVector.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/iterator_range.h"
43 #include "llvm/Analysis/AliasAnalysis.h"
44 #include "llvm/Analysis/MemoryLocation.h"
45 #include "llvm/Analysis/ValueTracking.h"
46 #include "llvm/CodeGen/DFAPacketizer.h"
47 #include "llvm/CodeGen/LiveIntervals.h"
48 #include "llvm/CodeGen/MachineBasicBlock.h"
49 #include "llvm/CodeGen/MachineDominators.h"
50 #include "llvm/CodeGen/MachineFunction.h"
51 #include "llvm/CodeGen/MachineFunctionPass.h"
52 #include "llvm/CodeGen/MachineInstr.h"
53 #include "llvm/CodeGen/MachineInstrBuilder.h"
54 #include "llvm/CodeGen/MachineLoopInfo.h"
55 #include "llvm/CodeGen/MachineMemOperand.h"
56 #include "llvm/CodeGen/MachineOperand.h"
57 #include "llvm/CodeGen/MachinePipeliner.h"
58 #include "llvm/CodeGen/MachineRegisterInfo.h"
59 #include "llvm/CodeGen/ModuloSchedule.h"
60 #include "llvm/CodeGen/RegisterPressure.h"
61 #include "llvm/CodeGen/ScheduleDAG.h"
62 #include "llvm/CodeGen/ScheduleDAGMutation.h"
63 #include "llvm/CodeGen/TargetOpcodes.h"
64 #include "llvm/CodeGen/TargetRegisterInfo.h"
65 #include "llvm/CodeGen/TargetSubtargetInfo.h"
66 #include "llvm/Config/llvm-config.h"
67 #include "llvm/IR/Attributes.h"
68 #include "llvm/IR/DebugLoc.h"
69 #include "llvm/IR/Function.h"
70 #include "llvm/MC/LaneBitmask.h"
71 #include "llvm/MC/MCInstrDesc.h"
72 #include "llvm/MC/MCInstrItineraries.h"
73 #include "llvm/MC/MCRegisterInfo.h"
74 #include "llvm/Pass.h"
75 #include "llvm/Support/CommandLine.h"
76 #include "llvm/Support/Compiler.h"
77 #include "llvm/Support/Debug.h"
78 #include "llvm/Support/MathExtras.h"
79 #include "llvm/Support/raw_ostream.h"
95 #define DEBUG_TYPE "pipeliner"
97 STATISTIC(NumTrytoPipeline
, "Number of loops that we attempt to pipeline");
98 STATISTIC(NumPipelined
, "Number of loops software pipelined");
99 STATISTIC(NumNodeOrderIssues
, "Number of node order issues found");
100 STATISTIC(NumFailBranch
, "Pipeliner abort due to unknown branch");
101 STATISTIC(NumFailLoop
, "Pipeliner abort due to unsupported loop");
102 STATISTIC(NumFailPreheader
, "Pipeliner abort due to missing preheader");
103 STATISTIC(NumFailLargeMaxMII
, "Pipeliner abort due to MaxMII too large");
104 STATISTIC(NumFailZeroMII
, "Pipeliner abort due to zero MII");
105 STATISTIC(NumFailNoSchedule
, "Pipeliner abort due to no schedule found");
106 STATISTIC(NumFailZeroStage
, "Pipeliner abort due to zero stage");
107 STATISTIC(NumFailLargeMaxStage
, "Pipeliner abort due to too many stages");
109 /// A command line option to turn software pipelining on or off.
110 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",
149 cl::ReallyHidden
, cl::init(false),
150 cl::ZeroOrMore
, 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.
172 SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden
,
173 cl::init(true), cl::ZeroOrMore
,
174 cl::desc("Enable CopyToPhi DAG Mutation"));
176 } // end namespace llvm
178 unsigned SwingSchedulerDAG::Circuits::MaxPaths
= 5;
179 char MachinePipeliner::ID
= 0;
181 int MachinePipeliner::NumTries
= 0;
183 char &llvm::MachinePipelinerID
= MachinePipeliner::ID
;
185 INITIALIZE_PASS_BEGIN(MachinePipeliner
, DEBUG_TYPE
,
186 "Modulo Software Pipelining", false, false)
187 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass
)
188 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo
)
189 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
190 INITIALIZE_PASS_DEPENDENCY(LiveIntervals
)
191 INITIALIZE_PASS_END(MachinePipeliner
, DEBUG_TYPE
,
192 "Modulo Software Pipelining", false, false)
194 /// The "main" function for implementing Swing Modulo Scheduling.
195 bool MachinePipeliner::runOnMachineFunction(MachineFunction
&mf
) {
196 if (skipFunction(mf
.getFunction()))
202 if (mf
.getFunction().getAttributes().hasAttribute(
203 AttributeList::FunctionIndex
, Attribute::OptimizeForSize
) &&
204 !EnableSWPOptSize
.getPosition())
207 if (!mf
.getSubtarget().enableMachinePipeliner())
210 // Cannot pipeline loops without instruction itineraries if we are using
211 // DFA for the pipeliner.
212 if (mf
.getSubtarget().useDFAforSMS() &&
213 (!mf
.getSubtarget().getInstrItineraryData() ||
214 mf
.getSubtarget().getInstrItineraryData()->isEmpty()))
218 MLI
= &getAnalysis
<MachineLoopInfo
>();
219 MDT
= &getAnalysis
<MachineDominatorTree
>();
220 TII
= MF
->getSubtarget().getInstrInfo();
221 RegClassInfo
.runOnMachineFunction(*MF
);
229 /// Attempt to perform the SMS algorithm on the specified loop. This function is
230 /// the main entry point for the algorithm. The function identifies candidate
231 /// loops, calculates the minimum initiation interval, and attempts to schedule
233 bool MachinePipeliner::scheduleLoop(MachineLoop
&L
) {
234 bool Changed
= false;
235 for (auto &InnerLoop
: L
)
236 Changed
|= scheduleLoop(*InnerLoop
);
239 // Stop trying after reaching the limit (if any).
240 int Limit
= SwpLoopLimit
;
242 if (NumTries
>= SwpLoopLimit
)
248 setPragmaPipelineOptions(L
);
249 if (!canPipelineLoop(L
)) {
250 LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
256 Changed
= swingModuloScheduler(L
);
261 void MachinePipeliner::setPragmaPipelineOptions(MachineLoop
&L
) {
262 MachineBasicBlock
*LBLK
= L
.getTopBlock();
267 const BasicBlock
*BBLK
= LBLK
->getBasicBlock();
271 const Instruction
*TI
= BBLK
->getTerminator();
275 MDNode
*LoopID
= TI
->getMetadata(LLVMContext::MD_loop
);
276 if (LoopID
== nullptr)
279 assert(LoopID
->getNumOperands() > 0 && "requires atleast one operand");
280 assert(LoopID
->getOperand(0) == LoopID
&& "invalid loop");
282 for (unsigned i
= 1, e
= LoopID
->getNumOperands(); i
< e
; ++i
) {
283 MDNode
*MD
= dyn_cast
<MDNode
>(LoopID
->getOperand(i
));
288 MDString
*S
= dyn_cast
<MDString
>(MD
->getOperand(0));
293 if (S
->getString() == "llvm.loop.pipeline.initiationinterval") {
294 assert(MD
->getNumOperands() == 2 &&
295 "Pipeline initiation interval hint metadata should have two operands.");
297 mdconst::extract
<ConstantInt
>(MD
->getOperand(1))->getZExtValue();
298 assert(II_setByPragma
>= 1 && "Pipeline initiation interval must be positive.");
299 } else if (S
->getString() == "llvm.loop.pipeline.disable") {
300 disabledByPragma
= true;
305 /// Return true if the loop can be software pipelined. The algorithm is
306 /// restricted to loops with a single basic block. Make sure that the
307 /// branch in the loop can be analyzed.
308 bool MachinePipeliner::canPipelineLoop(MachineLoop
&L
) {
309 if (L
.getNumBlocks() != 1)
312 if (disabledByPragma
)
315 // Check if the branch can't be understood because we can't do pipelining
316 // if that's the case.
320 if (TII
->analyzeBranch(*L
.getHeader(), LI
.TBB
, LI
.FBB
, LI
.BrCond
)) {
322 dbgs() << "Unable to analyzeBranch, can NOT pipeline current Loop\n");
327 LI
.LoopInductionVar
= nullptr;
328 LI
.LoopCompare
= nullptr;
329 if (!TII
->analyzeLoopForPipelining(L
.getTopBlock())) {
331 dbgs() << "Unable to analyzeLoop, can NOT pipeline current Loop\n");
336 if (!L
.getLoopPreheader()) {
338 dbgs() << "Preheader not found, can NOT pipeline current Loop\n");
343 // Remove any subregisters from inputs to phi nodes.
344 preprocessPhiNodes(*L
.getHeader());
348 void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock
&B
) {
349 MachineRegisterInfo
&MRI
= MF
->getRegInfo();
350 SlotIndexes
&Slots
= *getAnalysis
<LiveIntervals
>().getSlotIndexes();
352 for (MachineInstr
&PI
: make_range(B
.begin(), B
.getFirstNonPHI())) {
353 MachineOperand
&DefOp
= PI
.getOperand(0);
354 assert(DefOp
.getSubReg() == 0);
355 auto *RC
= MRI
.getRegClass(DefOp
.getReg());
357 for (unsigned i
= 1, n
= PI
.getNumOperands(); i
!= n
; i
+= 2) {
358 MachineOperand
&RegOp
= PI
.getOperand(i
);
359 if (RegOp
.getSubReg() == 0)
362 // If the operand uses a subregister, replace it with a new register
363 // without subregisters, and generate a copy to the new register.
364 Register NewReg
= MRI
.createVirtualRegister(RC
);
365 MachineBasicBlock
&PredB
= *PI
.getOperand(i
+1).getMBB();
366 MachineBasicBlock::iterator At
= PredB
.getFirstTerminator();
367 const DebugLoc
&DL
= PredB
.findDebugLoc(At
);
368 auto Copy
= BuildMI(PredB
, At
, DL
, TII
->get(TargetOpcode::COPY
), NewReg
)
369 .addReg(RegOp
.getReg(), getRegState(RegOp
),
371 Slots
.insertMachineInstrInMaps(*Copy
);
372 RegOp
.setReg(NewReg
);
378 /// The SMS algorithm consists of the following main steps:
379 /// 1. Computation and analysis of the dependence graph.
380 /// 2. Ordering of the nodes (instructions).
381 /// 3. Attempt to Schedule the loop.
382 bool MachinePipeliner::swingModuloScheduler(MachineLoop
&L
) {
383 assert(L
.getBlocks().size() == 1 && "SMS works on single blocks only.");
385 SwingSchedulerDAG
SMS(*this, L
, getAnalysis
<LiveIntervals
>(), RegClassInfo
,
388 MachineBasicBlock
*MBB
= L
.getHeader();
389 // The kernel should not include any terminator instructions. These
390 // will be added back later.
393 // Compute the number of 'real' instructions in the basic block by
394 // ignoring terminators.
395 unsigned size
= MBB
->size();
396 for (MachineBasicBlock::iterator I
= MBB
->getFirstTerminator(),
397 E
= MBB
->instr_end();
401 SMS
.enterRegion(MBB
, MBB
->begin(), MBB
->getFirstTerminator(), size
);
406 return SMS
.hasNewSchedule();
409 void SwingSchedulerDAG::setMII(unsigned ResMII
, unsigned RecMII
) {
410 if (II_setByPragma
> 0)
411 MII
= II_setByPragma
;
413 MII
= std::max(ResMII
, RecMII
);
416 void SwingSchedulerDAG::setMAX_II() {
417 if (II_setByPragma
> 0)
418 MAX_II
= II_setByPragma
;
423 /// We override the schedule function in ScheduleDAGInstrs to implement the
424 /// scheduling part of the Swing Modulo Scheduling algorithm.
425 void SwingSchedulerDAG::schedule() {
426 AliasAnalysis
*AA
= &Pass
.getAnalysis
<AAResultsWrapperPass
>().getAAResults();
428 addLoopCarriedDependences(AA
);
429 updatePhiDependences();
430 Topo
.InitDAGTopologicalSorting();
435 NodeSetType NodeSets
;
436 findCircuits(NodeSets
);
437 NodeSetType Circuits
= NodeSets
;
439 // Calculate the MII.
440 unsigned ResMII
= calculateResMII();
441 unsigned RecMII
= calculateRecMII(NodeSets
);
445 // This flag is used for testing and can cause correctness problems.
449 setMII(ResMII
, RecMII
);
452 LLVM_DEBUG(dbgs() << "MII = " << MII
<< " MAX_II = " << MAX_II
453 << " (rec=" << RecMII
<< ", res=" << ResMII
<< ")\n");
455 // Can't schedule a loop without a valid MII.
459 << "0 is not a valid Minimal Initiation Interval, can NOT schedule\n");
464 // Don't pipeline large loops.
465 if (SwpMaxMii
!= -1 && (int)MII
> SwpMaxMii
) {
466 LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
467 << ", we don't pipleline large loops\n");
468 NumFailLargeMaxMII
++;
472 computeNodeFunctions(NodeSets
);
474 registerPressureFilter(NodeSets
);
476 colocateNodeSets(NodeSets
);
478 checkNodeSets(NodeSets
);
481 for (auto &I
: NodeSets
) {
482 dbgs() << " Rec NodeSet ";
487 llvm::stable_sort(NodeSets
, std::greater
<NodeSet
>());
489 groupRemainingNodes(NodeSets
);
491 removeDuplicateNodes(NodeSets
);
494 for (auto &I
: NodeSets
) {
495 dbgs() << " NodeSet ";
500 computeNodeOrder(NodeSets
);
502 // check for node order issues
503 checkValidNodeOrder(Circuits
);
505 SMSchedule
Schedule(Pass
.MF
);
506 Scheduled
= schedulePipeline(Schedule
);
509 LLVM_DEBUG(dbgs() << "No schedule found, return\n");
514 unsigned numStages
= Schedule
.getMaxStageCount();
515 // No need to generate pipeline if there are no overlapped iterations.
516 if (numStages
== 0) {
518 dbgs() << "No overlapped iterations, no need to generate pipeline\n");
522 // Check that the maximum stage count is less than user-defined limit.
523 if (SwpMaxStages
> -1 && (int)numStages
> SwpMaxStages
) {
524 LLVM_DEBUG(dbgs() << "numStages:" << numStages
<< ">" << SwpMaxStages
525 << " : too many stages, abort\n");
526 NumFailLargeMaxStage
++;
530 // Generate the schedule as a ModuloSchedule.
531 DenseMap
<MachineInstr
*, int> Cycles
, Stages
;
532 std::vector
<MachineInstr
*> OrderedInsts
;
533 for (int Cycle
= Schedule
.getFirstCycle(); Cycle
<= Schedule
.getFinalCycle();
535 for (SUnit
*SU
: Schedule
.getInstructions(Cycle
)) {
536 OrderedInsts
.push_back(SU
->getInstr());
537 Cycles
[SU
->getInstr()] = Cycle
;
538 Stages
[SU
->getInstr()] = Schedule
.stageScheduled(SU
);
541 DenseMap
<MachineInstr
*, std::pair
<unsigned, int64_t>> NewInstrChanges
;
542 for (auto &KV
: NewMIs
) {
543 Cycles
[KV
.first
] = Cycles
[KV
.second
];
544 Stages
[KV
.first
] = Stages
[KV
.second
];
545 NewInstrChanges
[KV
.first
] = InstrChanges
[getSUnit(KV
.first
)];
548 ModuloSchedule
MS(MF
, &Loop
, std::move(OrderedInsts
), std::move(Cycles
),
550 if (EmitTestAnnotations
) {
551 assert(NewInstrChanges
.empty() &&
552 "Cannot serialize a schedule with InstrChanges!");
553 ModuloScheduleTestAnnotater
MSTI(MF
, MS
);
557 // The experimental code generator can't work if there are InstChanges.
558 if (ExperimentalCodeGen
&& NewInstrChanges
.empty()) {
559 PeelingModuloScheduleExpander
MSE(MF
, MS
, &LIS
);
562 ModuloScheduleExpander
MSE(MF
, MS
, LIS
, std::move(NewInstrChanges
));
569 /// Clean up after the software pipeliner runs.
570 void SwingSchedulerDAG::finishBlock() {
571 for (auto &KV
: NewMIs
)
572 MF
.DeleteMachineInstr(KV
.second
);
575 // Call the superclass.
576 ScheduleDAGInstrs::finishBlock();
579 /// Return the register values for the operands of a Phi instruction.
580 /// This function assume the instruction is a Phi.
581 static void getPhiRegs(MachineInstr
&Phi
, MachineBasicBlock
*Loop
,
582 unsigned &InitVal
, unsigned &LoopVal
) {
583 assert(Phi
.isPHI() && "Expecting a Phi.");
587 for (unsigned i
= 1, e
= Phi
.getNumOperands(); i
!= e
; i
+= 2)
588 if (Phi
.getOperand(i
+ 1).getMBB() != Loop
)
589 InitVal
= Phi
.getOperand(i
).getReg();
591 LoopVal
= Phi
.getOperand(i
).getReg();
593 assert(InitVal
!= 0 && LoopVal
!= 0 && "Unexpected Phi structure.");
596 /// Return the Phi register value that comes the loop block.
597 static unsigned getLoopPhiReg(MachineInstr
&Phi
, MachineBasicBlock
*LoopBB
) {
598 for (unsigned i
= 1, e
= Phi
.getNumOperands(); i
!= e
; i
+= 2)
599 if (Phi
.getOperand(i
+ 1).getMBB() == LoopBB
)
600 return Phi
.getOperand(i
).getReg();
604 /// Return true if SUb can be reached from SUa following the chain edges.
605 static bool isSuccOrder(SUnit
*SUa
, SUnit
*SUb
) {
606 SmallPtrSet
<SUnit
*, 8> Visited
;
607 SmallVector
<SUnit
*, 8> Worklist
;
608 Worklist
.push_back(SUa
);
609 while (!Worklist
.empty()) {
610 const SUnit
*SU
= Worklist
.pop_back_val();
611 for (auto &SI
: SU
->Succs
) {
612 SUnit
*SuccSU
= SI
.getSUnit();
613 if (SI
.getKind() == SDep::Order
) {
614 if (Visited
.count(SuccSU
))
618 Worklist
.push_back(SuccSU
);
619 Visited
.insert(SuccSU
);
626 /// Return true if the instruction causes a chain between memory
627 /// references before and after it.
628 static bool isDependenceBarrier(MachineInstr
&MI
, AliasAnalysis
*AA
) {
629 return MI
.isCall() || MI
.mayRaiseFPException() ||
630 MI
.hasUnmodeledSideEffects() ||
631 (MI
.hasOrderedMemoryRef() &&
632 (!MI
.mayLoad() || !MI
.isDereferenceableInvariantLoad(AA
)));
635 /// Return the underlying objects for the memory references of an instruction.
636 /// This function calls the code in ValueTracking, but first checks that the
637 /// instruction has a memory operand.
638 static void getUnderlyingObjects(const MachineInstr
*MI
,
639 SmallVectorImpl
<const Value
*> &Objs
,
640 const DataLayout
&DL
) {
641 if (!MI
->hasOneMemOperand())
643 MachineMemOperand
*MM
= *MI
->memoperands_begin();
646 GetUnderlyingObjects(MM
->getValue(), Objs
, DL
);
647 for (const Value
*V
: Objs
) {
648 if (!isIdentifiedObject(V
)) {
656 /// Add a chain edge between a load and store if the store can be an
657 /// alias of the load on a subsequent iteration, i.e., a loop carried
658 /// dependence. This code is very similar to the code in ScheduleDAGInstrs
659 /// but that code doesn't create loop carried dependences.
660 void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis
*AA
) {
661 MapVector
<const Value
*, SmallVector
<SUnit
*, 4>> PendingLoads
;
662 Value
*UnknownValue
=
663 UndefValue::get(Type::getVoidTy(MF
.getFunction().getContext()));
664 for (auto &SU
: SUnits
) {
665 MachineInstr
&MI
= *SU
.getInstr();
666 if (isDependenceBarrier(MI
, AA
))
667 PendingLoads
.clear();
668 else if (MI
.mayLoad()) {
669 SmallVector
<const Value
*, 4> Objs
;
670 getUnderlyingObjects(&MI
, Objs
, MF
.getDataLayout());
672 Objs
.push_back(UnknownValue
);
673 for (auto V
: Objs
) {
674 SmallVector
<SUnit
*, 4> &SUs
= PendingLoads
[V
];
677 } else if (MI
.mayStore()) {
678 SmallVector
<const Value
*, 4> Objs
;
679 getUnderlyingObjects(&MI
, Objs
, MF
.getDataLayout());
681 Objs
.push_back(UnknownValue
);
682 for (auto V
: Objs
) {
683 MapVector
<const Value
*, SmallVector
<SUnit
*, 4>>::iterator I
=
684 PendingLoads
.find(V
);
685 if (I
== PendingLoads
.end())
687 for (auto Load
: I
->second
) {
688 if (isSuccOrder(Load
, &SU
))
690 MachineInstr
&LdMI
= *Load
->getInstr();
691 // First, perform the cheaper check that compares the base register.
692 // If they are the same and the load offset is less than the store
693 // offset, then mark the dependence as loop carried potentially.
694 const MachineOperand
*BaseOp1
, *BaseOp2
;
695 int64_t Offset1
, Offset2
;
696 if (TII
->getMemOperandWithOffset(LdMI
, BaseOp1
, Offset1
, TRI
) &&
697 TII
->getMemOperandWithOffset(MI
, BaseOp2
, Offset2
, TRI
)) {
698 if (BaseOp1
->isIdenticalTo(*BaseOp2
) &&
699 (int)Offset1
< (int)Offset2
) {
700 assert(TII
->areMemAccessesTriviallyDisjoint(LdMI
, MI
) &&
701 "What happened to the chain edge?");
702 SDep
Dep(Load
, SDep::Barrier
);
708 // Second, the more expensive check that uses alias analysis on the
709 // base registers. If they alias, and the load offset is less than
710 // the store offset, the mark the dependence as loop carried.
712 SDep
Dep(Load
, SDep::Barrier
);
717 MachineMemOperand
*MMO1
= *LdMI
.memoperands_begin();
718 MachineMemOperand
*MMO2
= *MI
.memoperands_begin();
719 if (!MMO1
->getValue() || !MMO2
->getValue()) {
720 SDep
Dep(Load
, SDep::Barrier
);
725 if (MMO1
->getValue() == MMO2
->getValue() &&
726 MMO1
->getOffset() <= MMO2
->getOffset()) {
727 SDep
Dep(Load
, SDep::Barrier
);
732 AliasResult AAResult
= AA
->alias(
733 MemoryLocation(MMO1
->getValue(), LocationSize::unknown(),
735 MemoryLocation(MMO2
->getValue(), LocationSize::unknown(),
738 if (AAResult
!= NoAlias
) {
739 SDep
Dep(Load
, SDep::Barrier
);
749 /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
750 /// processes dependences for PHIs. This function adds true dependences
751 /// from a PHI to a use, and a loop carried dependence from the use to the
752 /// PHI. The loop carried dependence is represented as an anti dependence
753 /// edge. This function also removes chain dependences between unrelated
755 void SwingSchedulerDAG::updatePhiDependences() {
756 SmallVector
<SDep
, 4> RemoveDeps
;
757 const TargetSubtargetInfo
&ST
= MF
.getSubtarget
<TargetSubtargetInfo
>();
759 // Iterate over each DAG node.
760 for (SUnit
&I
: SUnits
) {
762 // Set to true if the instruction has an operand defined by a Phi.
763 unsigned HasPhiUse
= 0;
764 unsigned HasPhiDef
= 0;
765 MachineInstr
*MI
= I
.getInstr();
766 // Iterate over each operand, and we process the definitions.
767 for (MachineInstr::mop_iterator MOI
= MI
->operands_begin(),
768 MOE
= MI
->operands_end();
772 Register Reg
= MOI
->getReg();
774 // If the register is used by a Phi, then create an anti dependence.
775 for (MachineRegisterInfo::use_instr_iterator
776 UI
= MRI
.use_instr_begin(Reg
),
777 UE
= MRI
.use_instr_end();
779 MachineInstr
*UseMI
= &*UI
;
780 SUnit
*SU
= getSUnit(UseMI
);
781 if (SU
!= nullptr && UseMI
->isPHI()) {
783 SDep
Dep(SU
, SDep::Anti
, Reg
);
788 // Add a chain edge to a dependent Phi that isn't an existing
790 if (SU
->NodeNum
< I
.NodeNum
&& !I
.isPred(SU
))
791 I
.addPred(SDep(SU
, SDep::Barrier
));
795 } else if (MOI
->isUse()) {
796 // If the register is defined by a Phi, then create a true dependence.
797 MachineInstr
*DefMI
= MRI
.getUniqueVRegDef(Reg
);
798 if (DefMI
== nullptr)
800 SUnit
*SU
= getSUnit(DefMI
);
801 if (SU
!= nullptr && DefMI
->isPHI()) {
803 SDep
Dep(SU
, SDep::Data
, Reg
);
805 ST
.adjustSchedDependency(SU
, &I
, Dep
);
809 // Add a chain edge to a dependent Phi that isn't an existing
811 if (SU
->NodeNum
< I
.NodeNum
&& !I
.isPred(SU
))
812 I
.addPred(SDep(SU
, SDep::Barrier
));
817 // Remove order dependences from an unrelated Phi.
820 for (auto &PI
: I
.Preds
) {
821 MachineInstr
*PMI
= PI
.getSUnit()->getInstr();
822 if (PMI
->isPHI() && PI
.getKind() == SDep::Order
) {
823 if (I
.getInstr()->isPHI()) {
824 if (PMI
->getOperand(0).getReg() == HasPhiUse
)
826 if (getLoopPhiReg(*PMI
, PMI
->getParent()) == HasPhiDef
)
829 RemoveDeps
.push_back(PI
);
832 for (int i
= 0, e
= RemoveDeps
.size(); i
!= e
; ++i
)
833 I
.removePred(RemoveDeps
[i
]);
837 /// Iterate over each DAG node and see if we can change any dependences
838 /// in order to reduce the recurrence MII.
839 void SwingSchedulerDAG::changeDependences() {
840 // See if an instruction can use a value from the previous iteration.
841 // If so, we update the base and offset of the instruction and change
843 for (SUnit
&I
: SUnits
) {
844 unsigned BasePos
= 0, OffsetPos
= 0, NewBase
= 0;
845 int64_t NewOffset
= 0;
846 if (!canUseLastOffsetValue(I
.getInstr(), BasePos
, OffsetPos
, NewBase
,
850 // Get the MI and SUnit for the instruction that defines the original base.
851 Register OrigBase
= I
.getInstr()->getOperand(BasePos
).getReg();
852 MachineInstr
*DefMI
= MRI
.getUniqueVRegDef(OrigBase
);
855 SUnit
*DefSU
= getSUnit(DefMI
);
858 // Get the MI and SUnit for the instruction that defins the new base.
859 MachineInstr
*LastMI
= MRI
.getUniqueVRegDef(NewBase
);
862 SUnit
*LastSU
= getSUnit(LastMI
);
866 if (Topo
.IsReachable(&I
, LastSU
))
869 // Remove the dependence. The value now depends on a prior iteration.
870 SmallVector
<SDep
, 4> Deps
;
871 for (SUnit::pred_iterator P
= I
.Preds
.begin(), E
= I
.Preds
.end(); P
!= E
;
873 if (P
->getSUnit() == DefSU
)
875 for (int i
= 0, e
= Deps
.size(); i
!= e
; i
++) {
876 Topo
.RemovePred(&I
, Deps
[i
].getSUnit());
877 I
.removePred(Deps
[i
]);
879 // Remove the chain dependence between the instructions.
881 for (auto &P
: LastSU
->Preds
)
882 if (P
.getSUnit() == &I
&& P
.getKind() == SDep::Order
)
884 for (int i
= 0, e
= Deps
.size(); i
!= e
; i
++) {
885 Topo
.RemovePred(LastSU
, Deps
[i
].getSUnit());
886 LastSU
->removePred(Deps
[i
]);
889 // Add a dependence between the new instruction and the instruction
890 // that defines the new base.
891 SDep
Dep(&I
, SDep::Anti
, NewBase
);
892 Topo
.AddPred(LastSU
, &I
);
893 LastSU
->addPred(Dep
);
895 // Remember the base and offset information so that we can update the
896 // instruction during code generation.
897 InstrChanges
[&I
] = std::make_pair(NewBase
, NewOffset
);
903 // FuncUnitSorter - Comparison operator used to sort instructions by
904 // the number of functional unit choices.
905 struct FuncUnitSorter
{
906 const InstrItineraryData
*InstrItins
;
907 const MCSubtargetInfo
*STI
;
908 DenseMap
<unsigned, unsigned> Resources
;
910 FuncUnitSorter(const TargetSubtargetInfo
&TSI
)
911 : InstrItins(TSI
.getInstrItineraryData()), STI(&TSI
) {}
913 // Compute the number of functional unit alternatives needed
914 // at each stage, and take the minimum value. We prioritize the
915 // instructions by the least number of choices first.
916 unsigned minFuncUnits(const MachineInstr
*Inst
, unsigned &F
) const {
917 unsigned SchedClass
= Inst
->getDesc().getSchedClass();
918 unsigned min
= UINT_MAX
;
919 if (InstrItins
&& !InstrItins
->isEmpty()) {
920 for (const InstrStage
&IS
:
921 make_range(InstrItins
->beginStage(SchedClass
),
922 InstrItins
->endStage(SchedClass
))) {
923 unsigned funcUnits
= IS
.getUnits();
924 unsigned numAlternatives
= countPopulation(funcUnits
);
925 if (numAlternatives
< min
) {
926 min
= numAlternatives
;
932 if (STI
&& STI
->getSchedModel().hasInstrSchedModel()) {
933 const MCSchedClassDesc
*SCDesc
=
934 STI
->getSchedModel().getSchedClassDesc(SchedClass
);
935 if (!SCDesc
->isValid())
936 // No valid Schedule Class Desc for schedClass, should be
937 // Pseudo/PostRAPseudo
940 for (const MCWriteProcResEntry
&PRE
:
941 make_range(STI
->getWriteProcResBegin(SCDesc
),
942 STI
->getWriteProcResEnd(SCDesc
))) {
945 const MCProcResourceDesc
*ProcResource
=
946 STI
->getSchedModel().getProcResource(PRE
.ProcResourceIdx
);
947 unsigned NumUnits
= ProcResource
->NumUnits
;
948 if (NumUnits
< min
) {
950 F
= PRE
.ProcResourceIdx
;
955 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
958 // Compute the critical resources needed by the instruction. This
959 // function records the functional units needed by instructions that
960 // must use only one functional unit. We use this as a tie breaker
961 // for computing the resource MII. The instrutions that require
962 // the same, highly used, functional unit have high priority.
963 void calcCriticalResources(MachineInstr
&MI
) {
964 unsigned SchedClass
= MI
.getDesc().getSchedClass();
965 if (InstrItins
&& !InstrItins
->isEmpty()) {
966 for (const InstrStage
&IS
:
967 make_range(InstrItins
->beginStage(SchedClass
),
968 InstrItins
->endStage(SchedClass
))) {
969 unsigned FuncUnits
= IS
.getUnits();
970 if (countPopulation(FuncUnits
) == 1)
971 Resources
[FuncUnits
]++;
975 if (STI
&& STI
->getSchedModel().hasInstrSchedModel()) {
976 const MCSchedClassDesc
*SCDesc
=
977 STI
->getSchedModel().getSchedClassDesc(SchedClass
);
978 if (!SCDesc
->isValid())
979 // No valid Schedule Class Desc for schedClass, should be
980 // Pseudo/PostRAPseudo
983 for (const MCWriteProcResEntry
&PRE
:
984 make_range(STI
->getWriteProcResBegin(SCDesc
),
985 STI
->getWriteProcResEnd(SCDesc
))) {
988 Resources
[PRE
.ProcResourceIdx
]++;
992 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
995 /// Return true if IS1 has less priority than IS2.
996 bool operator()(const MachineInstr
*IS1
, const MachineInstr
*IS2
) const {
997 unsigned F1
= 0, F2
= 0;
998 unsigned MFUs1
= minFuncUnits(IS1
, F1
);
999 unsigned MFUs2
= minFuncUnits(IS2
, F2
);
1001 return Resources
.lookup(F1
) < Resources
.lookup(F2
);
1002 return MFUs1
> MFUs2
;
1006 } // end anonymous namespace
1008 /// Calculate the resource constrained minimum initiation interval for the
1009 /// specified loop. We use the DFA to model the resources needed for
1010 /// each instruction, and we ignore dependences. A different DFA is created
1011 /// for each cycle that is required. When adding a new instruction, we attempt
1012 /// to add it to each existing DFA, until a legal space is found. If the
1013 /// instruction cannot be reserved in an existing DFA, we create a new one.
1014 unsigned SwingSchedulerDAG::calculateResMII() {
1016 LLVM_DEBUG(dbgs() << "calculateResMII:\n");
1017 SmallVector
<ResourceManager
*, 8> Resources
;
1018 MachineBasicBlock
*MBB
= Loop
.getHeader();
1019 Resources
.push_back(new ResourceManager(&MF
.getSubtarget()));
1021 // Sort the instructions by the number of available choices for scheduling,
1022 // least to most. Use the number of critical resources as the tie breaker.
1023 FuncUnitSorter FUS
= FuncUnitSorter(MF
.getSubtarget());
1024 for (MachineBasicBlock::iterator I
= MBB
->getFirstNonPHI(),
1025 E
= MBB
->getFirstTerminator();
1027 FUS
.calcCriticalResources(*I
);
1028 PriorityQueue
<MachineInstr
*, std::vector
<MachineInstr
*>, FuncUnitSorter
>
1031 for (MachineBasicBlock::iterator I
= MBB
->getFirstNonPHI(),
1032 E
= MBB
->getFirstTerminator();
1034 FuncUnitOrder
.push(&*I
);
1036 while (!FuncUnitOrder
.empty()) {
1037 MachineInstr
*MI
= FuncUnitOrder
.top();
1038 FuncUnitOrder
.pop();
1039 if (TII
->isZeroCost(MI
->getOpcode()))
1041 // Attempt to reserve the instruction in an existing DFA. At least one
1042 // DFA is needed for each cycle.
1043 unsigned NumCycles
= getSUnit(MI
)->Latency
;
1044 unsigned ReservedCycles
= 0;
1045 SmallVectorImpl
<ResourceManager
*>::iterator RI
= Resources
.begin();
1046 SmallVectorImpl
<ResourceManager
*>::iterator RE
= Resources
.end();
1048 dbgs() << "Trying to reserve resource for " << NumCycles
1049 << " cycles for \n";
1052 for (unsigned C
= 0; C
< NumCycles
; ++C
)
1054 if ((*RI
)->canReserveResources(*MI
)) {
1055 (*RI
)->reserveResources(*MI
);
1061 LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
1062 << ", NumCycles:" << NumCycles
<< "\n");
1063 // Add new DFAs, if needed, to reserve resources.
1064 for (unsigned C
= ReservedCycles
; C
< NumCycles
; ++C
) {
1065 LLVM_DEBUG(if (SwpDebugResource
) dbgs()
1066 << "NewResource created to reserve resources"
1068 ResourceManager
*NewResource
= new ResourceManager(&MF
.getSubtarget());
1069 assert(NewResource
->canReserveResources(*MI
) && "Reserve error.");
1070 NewResource
->reserveResources(*MI
);
1071 Resources
.push_back(NewResource
);
1074 int Resmii
= Resources
.size();
1075 LLVM_DEBUG(dbgs() << "Retrun Res MII:" << Resmii
<< "\n");
1076 // Delete the memory for each of the DFAs that were created earlier.
1077 for (ResourceManager
*RI
: Resources
) {
1078 ResourceManager
*D
= RI
;
1085 /// Calculate the recurrence-constrainted minimum initiation interval.
1086 /// Iterate over each circuit. Compute the delay(c) and distance(c)
1087 /// for each circuit. The II needs to satisfy the inequality
1088 /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
1089 /// II that satisfies the inequality, and the RecMII is the maximum
1090 /// of those values.
1091 unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType
&NodeSets
) {
1092 unsigned RecMII
= 0;
1094 for (NodeSet
&Nodes
: NodeSets
) {
1098 unsigned Delay
= Nodes
.getLatency();
1099 unsigned Distance
= 1;
1101 // ii = ceil(delay / distance)
1102 unsigned CurMII
= (Delay
+ Distance
- 1) / Distance
;
1103 Nodes
.setRecMII(CurMII
);
1104 if (CurMII
> RecMII
)
1111 /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1112 /// but we do this to find the circuits, and then change them back.
1113 static void swapAntiDependences(std::vector
<SUnit
> &SUnits
) {
1114 SmallVector
<std::pair
<SUnit
*, SDep
>, 8> DepsAdded
;
1115 for (unsigned i
= 0, e
= SUnits
.size(); i
!= e
; ++i
) {
1116 SUnit
*SU
= &SUnits
[i
];
1117 for (SUnit::pred_iterator IP
= SU
->Preds
.begin(), EP
= SU
->Preds
.end();
1119 if (IP
->getKind() != SDep::Anti
)
1121 DepsAdded
.push_back(std::make_pair(SU
, *IP
));
1124 for (SmallVector
<std::pair
<SUnit
*, SDep
>, 8>::iterator I
= DepsAdded
.begin(),
1125 E
= DepsAdded
.end();
1127 // Remove this anti dependency and add one in the reverse direction.
1128 SUnit
*SU
= I
->first
;
1129 SDep
&D
= I
->second
;
1130 SUnit
*TargetSU
= D
.getSUnit();
1131 unsigned Reg
= D
.getReg();
1132 unsigned Lat
= D
.getLatency();
1134 SDep
Dep(SU
, SDep::Anti
, Reg
);
1135 Dep
.setLatency(Lat
);
1136 TargetSU
->addPred(Dep
);
1140 /// Create the adjacency structure of the nodes in the graph.
1141 void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1142 SwingSchedulerDAG
*DAG
) {
1143 BitVector
Added(SUnits
.size());
1144 DenseMap
<int, int> OutputDeps
;
1145 for (int i
= 0, e
= SUnits
.size(); i
!= e
; ++i
) {
1147 // Add any successor to the adjacency matrix and exclude duplicates.
1148 for (auto &SI
: SUnits
[i
].Succs
) {
1149 // Only create a back-edge on the first and last nodes of a dependence
1150 // chain. This records any chains and adds them later.
1151 if (SI
.getKind() == SDep::Output
) {
1152 int N
= SI
.getSUnit()->NodeNum
;
1154 auto Dep
= OutputDeps
.find(BackEdge
);
1155 if (Dep
!= OutputDeps
.end()) {
1156 BackEdge
= Dep
->second
;
1157 OutputDeps
.erase(Dep
);
1159 OutputDeps
[N
] = BackEdge
;
1161 // Do not process a boundary node, an artificial node.
1162 // A back-edge is processed only if it goes to a Phi.
1163 if (SI
.getSUnit()->isBoundaryNode() || SI
.isArtificial() ||
1164 (SI
.getKind() == SDep::Anti
&& !SI
.getSUnit()->getInstr()->isPHI()))
1166 int N
= SI
.getSUnit()->NodeNum
;
1167 if (!Added
.test(N
)) {
1168 AdjK
[i
].push_back(N
);
1172 // A chain edge between a store and a load is treated as a back-edge in the
1173 // adjacency matrix.
1174 for (auto &PI
: SUnits
[i
].Preds
) {
1175 if (!SUnits
[i
].getInstr()->mayStore() ||
1176 !DAG
->isLoopCarriedDep(&SUnits
[i
], PI
, false))
1178 if (PI
.getKind() == SDep::Order
&& PI
.getSUnit()->getInstr()->mayLoad()) {
1179 int N
= PI
.getSUnit()->NodeNum
;
1180 if (!Added
.test(N
)) {
1181 AdjK
[i
].push_back(N
);
1187 // Add back-edges in the adjacency matrix for the output dependences.
1188 for (auto &OD
: OutputDeps
)
1189 if (!Added
.test(OD
.second
)) {
1190 AdjK
[OD
.first
].push_back(OD
.second
);
1191 Added
.set(OD
.second
);
1195 /// Identify an elementary circuit in the dependence graph starting at the
1197 bool SwingSchedulerDAG::Circuits::circuit(int V
, int S
, NodeSetType
&NodeSets
,
1199 SUnit
*SV
= &SUnits
[V
];
1204 for (auto W
: AdjK
[V
]) {
1205 if (NumPaths
> MaxPaths
)
1211 NodeSets
.push_back(NodeSet(Stack
.begin(), Stack
.end()));
1215 } else if (!Blocked
.test(W
)) {
1216 if (circuit(W
, S
, NodeSets
,
1217 Node2Idx
->at(W
) < Node2Idx
->at(V
) ? true : HasBackedge
))
1225 for (auto W
: AdjK
[V
]) {
1228 if (B
[W
].count(SV
) == 0)
1236 /// Unblock a node in the circuit finding algorithm.
1237 void SwingSchedulerDAG::Circuits::unblock(int U
) {
1239 SmallPtrSet
<SUnit
*, 4> &BU
= B
[U
];
1240 while (!BU
.empty()) {
1241 SmallPtrSet
<SUnit
*, 4>::iterator SI
= BU
.begin();
1242 assert(SI
!= BU
.end() && "Invalid B set.");
1245 if (Blocked
.test(W
->NodeNum
))
1246 unblock(W
->NodeNum
);
1250 /// Identify all the elementary circuits in the dependence graph using
1251 /// Johnson's circuit algorithm.
1252 void SwingSchedulerDAG::findCircuits(NodeSetType
&NodeSets
) {
1253 // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1254 // but we do this to find the circuits, and then change them back.
1255 swapAntiDependences(SUnits
);
1257 Circuits
Cir(SUnits
, Topo
);
1258 // Create the adjacency structure.
1259 Cir
.createAdjacencyStructure(this);
1260 for (int i
= 0, e
= SUnits
.size(); i
!= e
; ++i
) {
1262 Cir
.circuit(i
, i
, NodeSets
);
1265 // Change the dependences back so that we've created a DAG again.
1266 swapAntiDependences(SUnits
);
1269 // Create artificial dependencies between the source of COPY/REG_SEQUENCE that
1270 // is loop-carried to the USE in next iteration. This will help pipeliner avoid
1271 // additional copies that are needed across iterations. An artificial dependence
1272 // edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
1274 // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
1275 // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
1276 // PHI-------True-Dep------> USEOfPhi
1278 // The mutation creates
1279 // USEOfPHI -------Artificial-Dep---> SRCOfCopy
1281 // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
1282 // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
1283 // late to avoid additional copies across iterations. The possible scheduling
1285 // USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE.
1287 void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs
*DAG
) {
1288 for (SUnit
&SU
: DAG
->SUnits
) {
1289 // Find the COPY/REG_SEQUENCE instruction.
1290 if (!SU
.getInstr()->isCopy() && !SU
.getInstr()->isRegSequence())
1293 // Record the loop carried PHIs.
1294 SmallVector
<SUnit
*, 4> PHISUs
;
1295 // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
1296 SmallVector
<SUnit
*, 4> SrcSUs
;
1298 for (auto &Dep
: SU
.Preds
) {
1299 SUnit
*TmpSU
= Dep
.getSUnit();
1300 MachineInstr
*TmpMI
= TmpSU
->getInstr();
1301 SDep::Kind DepKind
= Dep
.getKind();
1302 // Save the loop carried PHI.
1303 if (DepKind
== SDep::Anti
&& TmpMI
->isPHI())
1304 PHISUs
.push_back(TmpSU
);
1305 // Save the source of COPY/REG_SEQUENCE.
1306 // If the source has no pre-decessors, we will end up creating cycles.
1307 else if (DepKind
== SDep::Data
&& !TmpMI
->isPHI() && TmpSU
->NumPreds
> 0)
1308 SrcSUs
.push_back(TmpSU
);
1311 if (PHISUs
.size() == 0 || SrcSUs
.size() == 0)
1314 // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
1315 // SUnit to the container.
1316 SmallVector
<SUnit
*, 8> UseSUs
;
1317 for (auto I
= PHISUs
.begin(); I
!= PHISUs
.end(); ++I
) {
1318 for (auto &Dep
: (*I
)->Succs
) {
1319 if (Dep
.getKind() != SDep::Data
)
1322 SUnit
*TmpSU
= Dep
.getSUnit();
1323 MachineInstr
*TmpMI
= TmpSU
->getInstr();
1324 if (TmpMI
->isPHI() || TmpMI
->isRegSequence()) {
1325 PHISUs
.push_back(TmpSU
);
1328 UseSUs
.push_back(TmpSU
);
1332 if (UseSUs
.size() == 0)
1335 SwingSchedulerDAG
*SDAG
= cast
<SwingSchedulerDAG
>(DAG
);
1336 // Add the artificial dependencies if it does not form a cycle.
1337 for (auto I
: UseSUs
) {
1338 for (auto Src
: SrcSUs
) {
1339 if (!SDAG
->Topo
.IsReachable(I
, Src
) && Src
!= I
) {
1340 Src
->addPred(SDep(I
, SDep::Artificial
));
1341 SDAG
->Topo
.AddPred(Src
, I
);
1348 /// Return true for DAG nodes that we ignore when computing the cost functions.
1349 /// We ignore the back-edge recurrence in order to avoid unbounded recursion
1350 /// in the calculation of the ASAP, ALAP, etc functions.
1351 static bool ignoreDependence(const SDep
&D
, bool isPred
) {
1352 if (D
.isArtificial())
1354 return D
.getKind() == SDep::Anti
&& isPred
;
1357 /// Compute several functions need to order the nodes for scheduling.
1358 /// ASAP - Earliest time to schedule a node.
1359 /// ALAP - Latest time to schedule a node.
1360 /// MOV - Mobility function, difference between ALAP and ASAP.
1361 /// D - Depth of each node.
1362 /// H - Height of each node.
1363 void SwingSchedulerDAG::computeNodeFunctions(NodeSetType
&NodeSets
) {
1364 ScheduleInfo
.resize(SUnits
.size());
1367 for (ScheduleDAGTopologicalSort::const_iterator I
= Topo
.begin(),
1370 const SUnit
&SU
= SUnits
[*I
];
1376 // Compute ASAP and ZeroLatencyDepth.
1377 for (ScheduleDAGTopologicalSort::const_iterator I
= Topo
.begin(),
1381 int zeroLatencyDepth
= 0;
1382 SUnit
*SU
= &SUnits
[*I
];
1383 for (SUnit::const_pred_iterator IP
= SU
->Preds
.begin(),
1384 EP
= SU
->Preds
.end();
1386 SUnit
*pred
= IP
->getSUnit();
1387 if (IP
->getLatency() == 0)
1389 std::max(zeroLatencyDepth
, getZeroLatencyDepth(pred
) + 1);
1390 if (ignoreDependence(*IP
, true))
1392 asap
= std::max(asap
, (int)(getASAP(pred
) + IP
->getLatency() -
1393 getDistance(pred
, SU
, *IP
) * MII
));
1395 maxASAP
= std::max(maxASAP
, asap
);
1396 ScheduleInfo
[*I
].ASAP
= asap
;
1397 ScheduleInfo
[*I
].ZeroLatencyDepth
= zeroLatencyDepth
;
1400 // Compute ALAP, ZeroLatencyHeight, and MOV.
1401 for (ScheduleDAGTopologicalSort::const_reverse_iterator I
= Topo
.rbegin(),
1405 int zeroLatencyHeight
= 0;
1406 SUnit
*SU
= &SUnits
[*I
];
1407 for (SUnit::const_succ_iterator IS
= SU
->Succs
.begin(),
1408 ES
= SU
->Succs
.end();
1410 SUnit
*succ
= IS
->getSUnit();
1411 if (IS
->getLatency() == 0)
1413 std::max(zeroLatencyHeight
, getZeroLatencyHeight(succ
) + 1);
1414 if (ignoreDependence(*IS
, true))
1416 alap
= std::min(alap
, (int)(getALAP(succ
) - IS
->getLatency() +
1417 getDistance(SU
, succ
, *IS
) * MII
));
1420 ScheduleInfo
[*I
].ALAP
= alap
;
1421 ScheduleInfo
[*I
].ZeroLatencyHeight
= zeroLatencyHeight
;
1424 // After computing the node functions, compute the summary for each node set.
1425 for (NodeSet
&I
: NodeSets
)
1426 I
.computeNodeSetInfo(this);
1429 for (unsigned i
= 0; i
< SUnits
.size(); i
++) {
1430 dbgs() << "\tNode " << i
<< ":\n";
1431 dbgs() << "\t ASAP = " << getASAP(&SUnits
[i
]) << "\n";
1432 dbgs() << "\t ALAP = " << getALAP(&SUnits
[i
]) << "\n";
1433 dbgs() << "\t MOV = " << getMOV(&SUnits
[i
]) << "\n";
1434 dbgs() << "\t D = " << getDepth(&SUnits
[i
]) << "\n";
1435 dbgs() << "\t H = " << getHeight(&SUnits
[i
]) << "\n";
1436 dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits
[i
]) << "\n";
1437 dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits
[i
]) << "\n";
1442 /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1443 /// as the predecessors of the elements of NodeOrder that are not also in
1445 static bool pred_L(SetVector
<SUnit
*> &NodeOrder
,
1446 SmallSetVector
<SUnit
*, 8> &Preds
,
1447 const NodeSet
*S
= nullptr) {
1449 for (SetVector
<SUnit
*>::iterator I
= NodeOrder
.begin(), E
= NodeOrder
.end();
1451 for (SUnit::pred_iterator PI
= (*I
)->Preds
.begin(), PE
= (*I
)->Preds
.end();
1453 if (S
&& S
->count(PI
->getSUnit()) == 0)
1455 if (ignoreDependence(*PI
, true))
1457 if (NodeOrder
.count(PI
->getSUnit()) == 0)
1458 Preds
.insert(PI
->getSUnit());
1460 // Back-edges are predecessors with an anti-dependence.
1461 for (SUnit::const_succ_iterator IS
= (*I
)->Succs
.begin(),
1462 ES
= (*I
)->Succs
.end();
1464 if (IS
->getKind() != SDep::Anti
)
1466 if (S
&& S
->count(IS
->getSUnit()) == 0)
1468 if (NodeOrder
.count(IS
->getSUnit()) == 0)
1469 Preds
.insert(IS
->getSUnit());
1472 return !Preds
.empty();
1475 /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1476 /// as the successors of the elements of NodeOrder that are not also in
1478 static bool succ_L(SetVector
<SUnit
*> &NodeOrder
,
1479 SmallSetVector
<SUnit
*, 8> &Succs
,
1480 const NodeSet
*S
= nullptr) {
1482 for (SetVector
<SUnit
*>::iterator I
= NodeOrder
.begin(), E
= NodeOrder
.end();
1484 for (SUnit::succ_iterator SI
= (*I
)->Succs
.begin(), SE
= (*I
)->Succs
.end();
1486 if (S
&& S
->count(SI
->getSUnit()) == 0)
1488 if (ignoreDependence(*SI
, false))
1490 if (NodeOrder
.count(SI
->getSUnit()) == 0)
1491 Succs
.insert(SI
->getSUnit());
1493 for (SUnit::const_pred_iterator PI
= (*I
)->Preds
.begin(),
1494 PE
= (*I
)->Preds
.end();
1496 if (PI
->getKind() != SDep::Anti
)
1498 if (S
&& S
->count(PI
->getSUnit()) == 0)
1500 if (NodeOrder
.count(PI
->getSUnit()) == 0)
1501 Succs
.insert(PI
->getSUnit());
1504 return !Succs
.empty();
1507 /// Return true if there is a path from the specified node to any of the nodes
1508 /// in DestNodes. Keep track and return the nodes in any path.
1509 static bool computePath(SUnit
*Cur
, SetVector
<SUnit
*> &Path
,
1510 SetVector
<SUnit
*> &DestNodes
,
1511 SetVector
<SUnit
*> &Exclude
,
1512 SmallPtrSet
<SUnit
*, 8> &Visited
) {
1513 if (Cur
->isBoundaryNode())
1515 if (Exclude
.count(Cur
) != 0)
1517 if (DestNodes
.count(Cur
) != 0)
1519 if (!Visited
.insert(Cur
).second
)
1520 return Path
.count(Cur
) != 0;
1521 bool FoundPath
= false;
1522 for (auto &SI
: Cur
->Succs
)
1523 FoundPath
|= computePath(SI
.getSUnit(), Path
, DestNodes
, Exclude
, Visited
);
1524 for (auto &PI
: Cur
->Preds
)
1525 if (PI
.getKind() == SDep::Anti
)
1527 computePath(PI
.getSUnit(), Path
, DestNodes
, Exclude
, Visited
);
1533 /// Return true if Set1 is a subset of Set2.
1534 template <class S1Ty
, class S2Ty
> static bool isSubset(S1Ty
&Set1
, S2Ty
&Set2
) {
1535 for (typename
S1Ty::iterator I
= Set1
.begin(), E
= Set1
.end(); I
!= E
; ++I
)
1536 if (Set2
.count(*I
) == 0)
1541 /// Compute the live-out registers for the instructions in a node-set.
1542 /// The live-out registers are those that are defined in the node-set,
1543 /// but not used. Except for use operands of Phis.
1544 static void computeLiveOuts(MachineFunction
&MF
, RegPressureTracker
&RPTracker
,
1546 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
1547 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
1548 SmallVector
<RegisterMaskPair
, 8> LiveOutRegs
;
1549 SmallSet
<unsigned, 4> Uses
;
1550 for (SUnit
*SU
: NS
) {
1551 const MachineInstr
*MI
= SU
->getInstr();
1554 for (const MachineOperand
&MO
: MI
->operands())
1555 if (MO
.isReg() && MO
.isUse()) {
1556 Register Reg
= MO
.getReg();
1557 if (Register::isVirtualRegister(Reg
))
1559 else if (MRI
.isAllocatable(Reg
))
1560 for (MCRegUnitIterator
Units(Reg
, TRI
); Units
.isValid(); ++Units
)
1561 Uses
.insert(*Units
);
1564 for (SUnit
*SU
: NS
)
1565 for (const MachineOperand
&MO
: SU
->getInstr()->operands())
1566 if (MO
.isReg() && MO
.isDef() && !MO
.isDead()) {
1567 Register Reg
= MO
.getReg();
1568 if (Register::isVirtualRegister(Reg
)) {
1569 if (!Uses
.count(Reg
))
1570 LiveOutRegs
.push_back(RegisterMaskPair(Reg
,
1571 LaneBitmask::getNone()));
1572 } else if (MRI
.isAllocatable(Reg
)) {
1573 for (MCRegUnitIterator
Units(Reg
, TRI
); Units
.isValid(); ++Units
)
1574 if (!Uses
.count(*Units
))
1575 LiveOutRegs
.push_back(RegisterMaskPair(*Units
,
1576 LaneBitmask::getNone()));
1579 RPTracker
.addLiveRegs(LiveOutRegs
);
1582 /// A heuristic to filter nodes in recurrent node-sets if the register
1583 /// pressure of a set is too high.
1584 void SwingSchedulerDAG::registerPressureFilter(NodeSetType
&NodeSets
) {
1585 for (auto &NS
: NodeSets
) {
1586 // Skip small node-sets since they won't cause register pressure problems.
1589 IntervalPressure RecRegPressure
;
1590 RegPressureTracker
RecRPTracker(RecRegPressure
);
1591 RecRPTracker
.init(&MF
, &RegClassInfo
, &LIS
, BB
, BB
->end(), false, true);
1592 computeLiveOuts(MF
, RecRPTracker
, NS
);
1593 RecRPTracker
.closeBottom();
1595 std::vector
<SUnit
*> SUnits(NS
.begin(), NS
.end());
1596 llvm::sort(SUnits
, [](const SUnit
*A
, const SUnit
*B
) {
1597 return A
->NodeNum
> B
->NodeNum
;
1600 for (auto &SU
: SUnits
) {
1601 // Since we're computing the register pressure for a subset of the
1602 // instructions in a block, we need to set the tracker for each
1603 // instruction in the node-set. The tracker is set to the instruction
1604 // just after the one we're interested in.
1605 MachineBasicBlock::const_iterator CurInstI
= SU
->getInstr();
1606 RecRPTracker
.setPos(std::next(CurInstI
));
1608 RegPressureDelta RPDelta
;
1609 ArrayRef
<PressureChange
> CriticalPSets
;
1610 RecRPTracker
.getMaxUpwardPressureDelta(SU
->getInstr(), nullptr, RPDelta
,
1612 RecRegPressure
.MaxSetPressure
);
1613 if (RPDelta
.Excess
.isValid()) {
1615 dbgs() << "Excess register pressure: SU(" << SU
->NodeNum
<< ") "
1616 << TRI
->getRegPressureSetName(RPDelta
.Excess
.getPSet())
1617 << ":" << RPDelta
.Excess
.getUnitInc());
1618 NS
.setExceedPressure(SU
);
1621 RecRPTracker
.recede();
1626 /// A heuristic to colocate node sets that have the same set of
1628 void SwingSchedulerDAG::colocateNodeSets(NodeSetType
&NodeSets
) {
1629 unsigned Colocate
= 0;
1630 for (int i
= 0, e
= NodeSets
.size(); i
< e
; ++i
) {
1631 NodeSet
&N1
= NodeSets
[i
];
1632 SmallSetVector
<SUnit
*, 8> S1
;
1633 if (N1
.empty() || !succ_L(N1
, S1
))
1635 for (int j
= i
+ 1; j
< e
; ++j
) {
1636 NodeSet
&N2
= NodeSets
[j
];
1637 if (N1
.compareRecMII(N2
) != 0)
1639 SmallSetVector
<SUnit
*, 8> S2
;
1640 if (N2
.empty() || !succ_L(N2
, S2
))
1642 if (isSubset(S1
, S2
) && S1
.size() == S2
.size()) {
1643 N1
.setColocate(++Colocate
);
1644 N2
.setColocate(Colocate
);
1651 /// Check if the existing node-sets are profitable. If not, then ignore the
1652 /// recurrent node-sets, and attempt to schedule all nodes together. This is
1653 /// a heuristic. If the MII is large and all the recurrent node-sets are small,
1654 /// then it's best to try to schedule all instructions together instead of
1655 /// starting with the recurrent node-sets.
1656 void SwingSchedulerDAG::checkNodeSets(NodeSetType
&NodeSets
) {
1657 // Look for loops with a large MII.
1660 // Check if the node-set contains only a simple add recurrence.
1661 for (auto &NS
: NodeSets
) {
1662 if (NS
.getRecMII() > 2)
1664 if (NS
.getMaxDepth() > MII
)
1668 LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
1672 /// Add the nodes that do not belong to a recurrence set into groups
1673 /// based upon connected componenets.
1674 void SwingSchedulerDAG::groupRemainingNodes(NodeSetType
&NodeSets
) {
1675 SetVector
<SUnit
*> NodesAdded
;
1676 SmallPtrSet
<SUnit
*, 8> Visited
;
1677 // Add the nodes that are on a path between the previous node sets and
1678 // the current node set.
1679 for (NodeSet
&I
: NodeSets
) {
1680 SmallSetVector
<SUnit
*, 8> N
;
1681 // Add the nodes from the current node set to the previous node set.
1683 SetVector
<SUnit
*> Path
;
1684 for (SUnit
*NI
: N
) {
1686 computePath(NI
, Path
, NodesAdded
, I
, Visited
);
1689 I
.insert(Path
.begin(), Path
.end());
1691 // Add the nodes from the previous node set to the current node set.
1693 if (succ_L(NodesAdded
, N
)) {
1694 SetVector
<SUnit
*> Path
;
1695 for (SUnit
*NI
: N
) {
1697 computePath(NI
, Path
, I
, NodesAdded
, Visited
);
1700 I
.insert(Path
.begin(), Path
.end());
1702 NodesAdded
.insert(I
.begin(), I
.end());
1705 // Create a new node set with the connected nodes of any successor of a node
1706 // in a recurrent set.
1708 SmallSetVector
<SUnit
*, 8> N
;
1709 if (succ_L(NodesAdded
, N
))
1711 addConnectedNodes(I
, NewSet
, NodesAdded
);
1712 if (!NewSet
.empty())
1713 NodeSets
.push_back(NewSet
);
1715 // Create a new node set with the connected nodes of any predecessor of a node
1716 // in a recurrent set.
1718 if (pred_L(NodesAdded
, N
))
1720 addConnectedNodes(I
, NewSet
, NodesAdded
);
1721 if (!NewSet
.empty())
1722 NodeSets
.push_back(NewSet
);
1724 // Create new nodes sets with the connected nodes any remaining node that
1725 // has no predecessor.
1726 for (unsigned i
= 0; i
< SUnits
.size(); ++i
) {
1727 SUnit
*SU
= &SUnits
[i
];
1728 if (NodesAdded
.count(SU
) == 0) {
1730 addConnectedNodes(SU
, NewSet
, NodesAdded
);
1731 if (!NewSet
.empty())
1732 NodeSets
.push_back(NewSet
);
1737 /// Add the node to the set, and add all of its connected nodes to the set.
1738 void SwingSchedulerDAG::addConnectedNodes(SUnit
*SU
, NodeSet
&NewSet
,
1739 SetVector
<SUnit
*> &NodesAdded
) {
1741 NodesAdded
.insert(SU
);
1742 for (auto &SI
: SU
->Succs
) {
1743 SUnit
*Successor
= SI
.getSUnit();
1744 if (!SI
.isArtificial() && NodesAdded
.count(Successor
) == 0)
1745 addConnectedNodes(Successor
, NewSet
, NodesAdded
);
1747 for (auto &PI
: SU
->Preds
) {
1748 SUnit
*Predecessor
= PI
.getSUnit();
1749 if (!PI
.isArtificial() && NodesAdded
.count(Predecessor
) == 0)
1750 addConnectedNodes(Predecessor
, NewSet
, NodesAdded
);
1754 /// Return true if Set1 contains elements in Set2. The elements in common
1755 /// are returned in a different container.
1756 static bool isIntersect(SmallSetVector
<SUnit
*, 8> &Set1
, const NodeSet
&Set2
,
1757 SmallSetVector
<SUnit
*, 8> &Result
) {
1759 for (unsigned i
= 0, e
= Set1
.size(); i
!= e
; ++i
) {
1760 SUnit
*SU
= Set1
[i
];
1761 if (Set2
.count(SU
) != 0)
1764 return !Result
.empty();
1767 /// Merge the recurrence node sets that have the same initial node.
1768 void SwingSchedulerDAG::fuseRecs(NodeSetType
&NodeSets
) {
1769 for (NodeSetType::iterator I
= NodeSets
.begin(), E
= NodeSets
.end(); I
!= E
;
1772 for (NodeSetType::iterator J
= I
+ 1; J
!= E
;) {
1774 if (NI
.getNode(0)->NodeNum
== NJ
.getNode(0)->NodeNum
) {
1775 if (NJ
.compareRecMII(NI
) > 0)
1776 NI
.setRecMII(NJ
.getRecMII());
1777 for (NodeSet::iterator NII
= J
->begin(), ENI
= J
->end(); NII
!= ENI
;
1789 /// Remove nodes that have been scheduled in previous NodeSets.
1790 void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType
&NodeSets
) {
1791 for (NodeSetType::iterator I
= NodeSets
.begin(), E
= NodeSets
.end(); I
!= E
;
1793 for (NodeSetType::iterator J
= I
+ 1; J
!= E
;) {
1794 J
->remove_if([&](SUnit
*SUJ
) { return I
->count(SUJ
); });
1805 /// Compute an ordered list of the dependence graph nodes, which
1806 /// indicates the order that the nodes will be scheduled. This is a
1807 /// two-level algorithm. First, a partial order is created, which
1808 /// consists of a list of sets ordered from highest to lowest priority.
1809 void SwingSchedulerDAG::computeNodeOrder(NodeSetType
&NodeSets
) {
1810 SmallSetVector
<SUnit
*, 8> R
;
1813 for (auto &Nodes
: NodeSets
) {
1814 LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes
.size() << "\n");
1816 SmallSetVector
<SUnit
*, 8> N
;
1817 if (pred_L(NodeOrder
, N
) && isSubset(N
, Nodes
)) {
1818 R
.insert(N
.begin(), N
.end());
1820 LLVM_DEBUG(dbgs() << " Bottom up (preds) ");
1821 } else if (succ_L(NodeOrder
, N
) && isSubset(N
, Nodes
)) {
1822 R
.insert(N
.begin(), N
.end());
1824 LLVM_DEBUG(dbgs() << " Top down (succs) ");
1825 } else if (isIntersect(N
, Nodes
, R
)) {
1826 // If some of the successors are in the existing node-set, then use the
1827 // top-down ordering.
1829 LLVM_DEBUG(dbgs() << " Top down (intersect) ");
1830 } else if (NodeSets
.size() == 1) {
1831 for (auto &N
: Nodes
)
1832 if (N
->Succs
.size() == 0)
1835 LLVM_DEBUG(dbgs() << " Bottom up (all) ");
1837 // Find the node with the highest ASAP.
1838 SUnit
*maxASAP
= nullptr;
1839 for (SUnit
*SU
: Nodes
) {
1840 if (maxASAP
== nullptr || getASAP(SU
) > getASAP(maxASAP
) ||
1841 (getASAP(SU
) == getASAP(maxASAP
) && SU
->NodeNum
> maxASAP
->NodeNum
))
1846 LLVM_DEBUG(dbgs() << " Bottom up (default) ");
1849 while (!R
.empty()) {
1850 if (Order
== TopDown
) {
1851 // Choose the node with the maximum height. If more than one, choose
1852 // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
1853 // choose the node with the lowest MOV.
1854 while (!R
.empty()) {
1855 SUnit
*maxHeight
= nullptr;
1856 for (SUnit
*I
: R
) {
1857 if (maxHeight
== nullptr || getHeight(I
) > getHeight(maxHeight
))
1859 else if (getHeight(I
) == getHeight(maxHeight
) &&
1860 getZeroLatencyHeight(I
) > getZeroLatencyHeight(maxHeight
))
1862 else if (getHeight(I
) == getHeight(maxHeight
) &&
1863 getZeroLatencyHeight(I
) ==
1864 getZeroLatencyHeight(maxHeight
) &&
1865 getMOV(I
) < getMOV(maxHeight
))
1868 NodeOrder
.insert(maxHeight
);
1869 LLVM_DEBUG(dbgs() << maxHeight
->NodeNum
<< " ");
1870 R
.remove(maxHeight
);
1871 for (const auto &I
: maxHeight
->Succs
) {
1872 if (Nodes
.count(I
.getSUnit()) == 0)
1874 if (NodeOrder
.count(I
.getSUnit()) != 0)
1876 if (ignoreDependence(I
, false))
1878 R
.insert(I
.getSUnit());
1880 // Back-edges are predecessors with an anti-dependence.
1881 for (const auto &I
: maxHeight
->Preds
) {
1882 if (I
.getKind() != SDep::Anti
)
1884 if (Nodes
.count(I
.getSUnit()) == 0)
1886 if (NodeOrder
.count(I
.getSUnit()) != 0)
1888 R
.insert(I
.getSUnit());
1892 LLVM_DEBUG(dbgs() << "\n Switching order to bottom up ");
1893 SmallSetVector
<SUnit
*, 8> N
;
1894 if (pred_L(NodeOrder
, N
, &Nodes
))
1895 R
.insert(N
.begin(), N
.end());
1897 // Choose the node with the maximum depth. If more than one, choose
1898 // the node with the maximum ZeroLatencyDepth. If still more than one,
1899 // choose the node with the lowest MOV.
1900 while (!R
.empty()) {
1901 SUnit
*maxDepth
= nullptr;
1902 for (SUnit
*I
: R
) {
1903 if (maxDepth
== nullptr || getDepth(I
) > getDepth(maxDepth
))
1905 else if (getDepth(I
) == getDepth(maxDepth
) &&
1906 getZeroLatencyDepth(I
) > getZeroLatencyDepth(maxDepth
))
1908 else if (getDepth(I
) == getDepth(maxDepth
) &&
1909 getZeroLatencyDepth(I
) == getZeroLatencyDepth(maxDepth
) &&
1910 getMOV(I
) < getMOV(maxDepth
))
1913 NodeOrder
.insert(maxDepth
);
1914 LLVM_DEBUG(dbgs() << maxDepth
->NodeNum
<< " ");
1916 if (Nodes
.isExceedSU(maxDepth
)) {
1919 R
.insert(Nodes
.getNode(0));
1922 for (const auto &I
: maxDepth
->Preds
) {
1923 if (Nodes
.count(I
.getSUnit()) == 0)
1925 if (NodeOrder
.count(I
.getSUnit()) != 0)
1927 R
.insert(I
.getSUnit());
1929 // Back-edges are predecessors with an anti-dependence.
1930 for (const auto &I
: maxDepth
->Succs
) {
1931 if (I
.getKind() != SDep::Anti
)
1933 if (Nodes
.count(I
.getSUnit()) == 0)
1935 if (NodeOrder
.count(I
.getSUnit()) != 0)
1937 R
.insert(I
.getSUnit());
1941 LLVM_DEBUG(dbgs() << "\n Switching order to top down ");
1942 SmallSetVector
<SUnit
*, 8> N
;
1943 if (succ_L(NodeOrder
, N
, &Nodes
))
1944 R
.insert(N
.begin(), N
.end());
1947 LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
1951 dbgs() << "Node order: ";
1952 for (SUnit
*I
: NodeOrder
)
1953 dbgs() << " " << I
->NodeNum
<< " ";
1958 /// Process the nodes in the computed order and create the pipelined schedule
1959 /// of the instructions, if possible. Return true if a schedule is found.
1960 bool SwingSchedulerDAG::schedulePipeline(SMSchedule
&Schedule
) {
1962 if (NodeOrder
.empty()){
1963 LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
1967 bool scheduleFound
= false;
1969 // Keep increasing II until a valid schedule is found.
1970 for (II
= MII
; II
<= MAX_II
&& !scheduleFound
; ++II
) {
1972 Schedule
.setInitiationInterval(II
);
1973 LLVM_DEBUG(dbgs() << "Try to schedule with " << II
<< "\n");
1975 SetVector
<SUnit
*>::iterator NI
= NodeOrder
.begin();
1976 SetVector
<SUnit
*>::iterator NE
= NodeOrder
.end();
1980 // Compute the schedule time for the instruction, which is based
1981 // upon the scheduled time for any predecessors/successors.
1982 int EarlyStart
= INT_MIN
;
1983 int LateStart
= INT_MAX
;
1984 // These values are set when the size of the schedule window is limited
1985 // due to chain dependences.
1986 int SchedEnd
= INT_MAX
;
1987 int SchedStart
= INT_MIN
;
1988 Schedule
.computeStart(SU
, &EarlyStart
, &LateStart
, &SchedEnd
, &SchedStart
,
1992 dbgs() << "Inst (" << SU
->NodeNum
<< ") ";
1993 SU
->getInstr()->dump();
1997 dbgs() << format("\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart
,
1998 LateStart
, SchedEnd
, SchedStart
);
2001 if (EarlyStart
> LateStart
|| SchedEnd
< EarlyStart
||
2002 SchedStart
> LateStart
)
2003 scheduleFound
= false;
2004 else if (EarlyStart
!= INT_MIN
&& LateStart
== INT_MAX
) {
2005 SchedEnd
= std::min(SchedEnd
, EarlyStart
+ (int)II
- 1);
2006 scheduleFound
= Schedule
.insert(SU
, EarlyStart
, SchedEnd
, II
);
2007 } else if (EarlyStart
== INT_MIN
&& LateStart
!= INT_MAX
) {
2008 SchedStart
= std::max(SchedStart
, LateStart
- (int)II
+ 1);
2009 scheduleFound
= Schedule
.insert(SU
, LateStart
, SchedStart
, II
);
2010 } else if (EarlyStart
!= INT_MIN
&& LateStart
!= INT_MAX
) {
2012 std::min(SchedEnd
, std::min(LateStart
, EarlyStart
+ (int)II
- 1));
2013 // When scheduling a Phi it is better to start at the late cycle and go
2014 // backwards. The default order may insert the Phi too far away from
2015 // its first dependence.
2016 if (SU
->getInstr()->isPHI())
2017 scheduleFound
= Schedule
.insert(SU
, SchedEnd
, EarlyStart
, II
);
2019 scheduleFound
= Schedule
.insert(SU
, EarlyStart
, SchedEnd
, II
);
2021 int FirstCycle
= Schedule
.getFirstCycle();
2022 scheduleFound
= Schedule
.insert(SU
, FirstCycle
+ getASAP(SU
),
2023 FirstCycle
+ getASAP(SU
) + II
- 1, II
);
2025 // Even if we find a schedule, make sure the schedule doesn't exceed the
2026 // allowable number of stages. We keep trying if this happens.
2028 if (SwpMaxStages
> -1 &&
2029 Schedule
.getMaxStageCount() > (unsigned)SwpMaxStages
)
2030 scheduleFound
= false;
2034 dbgs() << "\tCan't schedule\n";
2036 } while (++NI
!= NE
&& scheduleFound
);
2038 // If a schedule is found, check if it is a valid schedule too.
2040 scheduleFound
= Schedule
.isValidSchedule(this);
2043 LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound
<< " (II=" << II
2047 Schedule
.finalizeSchedule(this);
2051 return scheduleFound
&& Schedule
.getMaxStageCount() > 0;
2054 /// Return true if we can compute the amount the instruction changes
2055 /// during each iteration. Set Delta to the amount of the change.
2056 bool SwingSchedulerDAG::computeDelta(MachineInstr
&MI
, unsigned &Delta
) {
2057 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
2058 const MachineOperand
*BaseOp
;
2060 if (!TII
->getMemOperandWithOffset(MI
, BaseOp
, Offset
, TRI
))
2063 if (!BaseOp
->isReg())
2066 Register BaseReg
= BaseOp
->getReg();
2068 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
2069 // Check if there is a Phi. If so, get the definition in the loop.
2070 MachineInstr
*BaseDef
= MRI
.getVRegDef(BaseReg
);
2071 if (BaseDef
&& BaseDef
->isPHI()) {
2072 BaseReg
= getLoopPhiReg(*BaseDef
, MI
.getParent());
2073 BaseDef
= MRI
.getVRegDef(BaseReg
);
2079 if (!TII
->getIncrementValue(*BaseDef
, D
) && D
>= 0)
2086 /// Check if we can change the instruction to use an offset value from the
2087 /// previous iteration. If so, return true and set the base and offset values
2088 /// so that we can rewrite the load, if necessary.
2089 /// v1 = Phi(v0, v3)
2091 /// v3 = post_store v1, 4, x
2092 /// This function enables the load to be rewritten as v2 = load v3, 4.
2093 bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr
*MI
,
2095 unsigned &OffsetPos
,
2098 // Get the load instruction.
2099 if (TII
->isPostIncrement(*MI
))
2101 unsigned BasePosLd
, OffsetPosLd
;
2102 if (!TII
->getBaseAndOffsetPosition(*MI
, BasePosLd
, OffsetPosLd
))
2104 Register BaseReg
= MI
->getOperand(BasePosLd
).getReg();
2106 // Look for the Phi instruction.
2107 MachineRegisterInfo
&MRI
= MI
->getMF()->getRegInfo();
2108 MachineInstr
*Phi
= MRI
.getVRegDef(BaseReg
);
2109 if (!Phi
|| !Phi
->isPHI())
2111 // Get the register defined in the loop block.
2112 unsigned PrevReg
= getLoopPhiReg(*Phi
, MI
->getParent());
2116 // Check for the post-increment load/store instruction.
2117 MachineInstr
*PrevDef
= MRI
.getVRegDef(PrevReg
);
2118 if (!PrevDef
|| PrevDef
== MI
)
2121 if (!TII
->isPostIncrement(*PrevDef
))
2124 unsigned BasePos1
= 0, OffsetPos1
= 0;
2125 if (!TII
->getBaseAndOffsetPosition(*PrevDef
, BasePos1
, OffsetPos1
))
2128 // Make sure that the instructions do not access the same memory location in
2129 // the next iteration.
2130 int64_t LoadOffset
= MI
->getOperand(OffsetPosLd
).getImm();
2131 int64_t StoreOffset
= PrevDef
->getOperand(OffsetPos1
).getImm();
2132 MachineInstr
*NewMI
= MF
.CloneMachineInstr(MI
);
2133 NewMI
->getOperand(OffsetPosLd
).setImm(LoadOffset
+ StoreOffset
);
2134 bool Disjoint
= TII
->areMemAccessesTriviallyDisjoint(*NewMI
, *PrevDef
);
2135 MF
.DeleteMachineInstr(NewMI
);
2139 // Set the return value once we determine that we return true.
2140 BasePos
= BasePosLd
;
2141 OffsetPos
= OffsetPosLd
;
2143 Offset
= StoreOffset
;
2147 /// Apply changes to the instruction if needed. The changes are need
2148 /// to improve the scheduling and depend up on the final schedule.
2149 void SwingSchedulerDAG::applyInstrChange(MachineInstr
*MI
,
2150 SMSchedule
&Schedule
) {
2151 SUnit
*SU
= getSUnit(MI
);
2152 DenseMap
<SUnit
*, std::pair
<unsigned, int64_t>>::iterator It
=
2153 InstrChanges
.find(SU
);
2154 if (It
!= InstrChanges
.end()) {
2155 std::pair
<unsigned, int64_t> RegAndOffset
= It
->second
;
2156 unsigned BasePos
, OffsetPos
;
2157 if (!TII
->getBaseAndOffsetPosition(*MI
, BasePos
, OffsetPos
))
2159 Register BaseReg
= MI
->getOperand(BasePos
).getReg();
2160 MachineInstr
*LoopDef
= findDefInLoop(BaseReg
);
2161 int DefStageNum
= Schedule
.stageScheduled(getSUnit(LoopDef
));
2162 int DefCycleNum
= Schedule
.cycleScheduled(getSUnit(LoopDef
));
2163 int BaseStageNum
= Schedule
.stageScheduled(SU
);
2164 int BaseCycleNum
= Schedule
.cycleScheduled(SU
);
2165 if (BaseStageNum
< DefStageNum
) {
2166 MachineInstr
*NewMI
= MF
.CloneMachineInstr(MI
);
2167 int OffsetDiff
= DefStageNum
- BaseStageNum
;
2168 if (DefCycleNum
< BaseCycleNum
) {
2169 NewMI
->getOperand(BasePos
).setReg(RegAndOffset
.first
);
2174 MI
->getOperand(OffsetPos
).getImm() + RegAndOffset
.second
* OffsetDiff
;
2175 NewMI
->getOperand(OffsetPos
).setImm(NewOffset
);
2176 SU
->setInstr(NewMI
);
2177 MISUnitMap
[NewMI
] = SU
;
2183 /// Return the instruction in the loop that defines the register.
2184 /// If the definition is a Phi, then follow the Phi operand to
2185 /// the instruction in the loop.
2186 MachineInstr
*SwingSchedulerDAG::findDefInLoop(unsigned Reg
) {
2187 SmallPtrSet
<MachineInstr
*, 8> Visited
;
2188 MachineInstr
*Def
= MRI
.getVRegDef(Reg
);
2189 while (Def
->isPHI()) {
2190 if (!Visited
.insert(Def
).second
)
2192 for (unsigned i
= 1, e
= Def
->getNumOperands(); i
< e
; i
+= 2)
2193 if (Def
->getOperand(i
+ 1).getMBB() == BB
) {
2194 Def
= MRI
.getVRegDef(Def
->getOperand(i
).getReg());
2201 /// Return true for an order or output dependence that is loop carried
2202 /// potentially. A dependence is loop carried if the destination defines a valu
2203 /// that may be used or defined by the source in a subsequent iteration.
2204 bool SwingSchedulerDAG::isLoopCarriedDep(SUnit
*Source
, const SDep
&Dep
,
2206 if ((Dep
.getKind() != SDep::Order
&& Dep
.getKind() != SDep::Output
) ||
2210 if (!SwpPruneLoopCarried
)
2213 if (Dep
.getKind() == SDep::Output
)
2216 MachineInstr
*SI
= Source
->getInstr();
2217 MachineInstr
*DI
= Dep
.getSUnit()->getInstr();
2220 assert(SI
!= nullptr && DI
!= nullptr && "Expecting SUnit with an MI.");
2222 // Assume ordered loads and stores may have a loop carried dependence.
2223 if (SI
->hasUnmodeledSideEffects() || DI
->hasUnmodeledSideEffects() ||
2224 SI
->mayRaiseFPException() || DI
->mayRaiseFPException() ||
2225 SI
->hasOrderedMemoryRef() || DI
->hasOrderedMemoryRef())
2228 // Only chain dependences between a load and store can be loop carried.
2229 if (!DI
->mayStore() || !SI
->mayLoad())
2232 unsigned DeltaS
, DeltaD
;
2233 if (!computeDelta(*SI
, DeltaS
) || !computeDelta(*DI
, DeltaD
))
2236 const MachineOperand
*BaseOpS
, *BaseOpD
;
2237 int64_t OffsetS
, OffsetD
;
2238 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
2239 if (!TII
->getMemOperandWithOffset(*SI
, BaseOpS
, OffsetS
, TRI
) ||
2240 !TII
->getMemOperandWithOffset(*DI
, BaseOpD
, OffsetD
, TRI
))
2243 if (!BaseOpS
->isIdenticalTo(*BaseOpD
))
2246 // Check that the base register is incremented by a constant value for each
2248 MachineInstr
*Def
= MRI
.getVRegDef(BaseOpS
->getReg());
2249 if (!Def
|| !Def
->isPHI())
2251 unsigned InitVal
= 0;
2252 unsigned LoopVal
= 0;
2253 getPhiRegs(*Def
, BB
, InitVal
, LoopVal
);
2254 MachineInstr
*LoopDef
= MRI
.getVRegDef(LoopVal
);
2256 if (!LoopDef
|| !TII
->getIncrementValue(*LoopDef
, D
))
2259 uint64_t AccessSizeS
= (*SI
->memoperands_begin())->getSize();
2260 uint64_t AccessSizeD
= (*DI
->memoperands_begin())->getSize();
2262 // This is the main test, which checks the offset values and the loop
2263 // increment value to determine if the accesses may be loop carried.
2264 if (AccessSizeS
== MemoryLocation::UnknownSize
||
2265 AccessSizeD
== MemoryLocation::UnknownSize
)
2268 if (DeltaS
!= DeltaD
|| DeltaS
< AccessSizeS
|| DeltaD
< AccessSizeD
)
2271 return (OffsetS
+ (int64_t)AccessSizeS
< OffsetD
+ (int64_t)AccessSizeD
);
2274 void SwingSchedulerDAG::postprocessDAG() {
2275 for (auto &M
: Mutations
)
2279 /// Try to schedule the node at the specified StartCycle and continue
2280 /// until the node is schedule or the EndCycle is reached. This function
2281 /// returns true if the node is scheduled. This routine may search either
2282 /// forward or backward for a place to insert the instruction based upon
2283 /// the relative values of StartCycle and EndCycle.
2284 bool SMSchedule::insert(SUnit
*SU
, int StartCycle
, int EndCycle
, int II
) {
2285 bool forward
= true;
2287 dbgs() << "Trying to insert node between " << StartCycle
<< " and "
2288 << EndCycle
<< " II: " << II
<< "\n";
2290 if (StartCycle
> EndCycle
)
2293 // The terminating condition depends on the direction.
2294 int termCycle
= forward
? EndCycle
+ 1 : EndCycle
- 1;
2295 for (int curCycle
= StartCycle
; curCycle
!= termCycle
;
2296 forward
? ++curCycle
: --curCycle
) {
2298 // Add the already scheduled instructions at the specified cycle to the
2300 ProcItinResources
.clearResources();
2301 for (int checkCycle
= FirstCycle
+ ((curCycle
- FirstCycle
) % II
);
2302 checkCycle
<= LastCycle
; checkCycle
+= II
) {
2303 std::deque
<SUnit
*> &cycleInstrs
= ScheduledInstrs
[checkCycle
];
2305 for (std::deque
<SUnit
*>::iterator I
= cycleInstrs
.begin(),
2306 E
= cycleInstrs
.end();
2308 if (ST
.getInstrInfo()->isZeroCost((*I
)->getInstr()->getOpcode()))
2310 assert(ProcItinResources
.canReserveResources(*(*I
)->getInstr()) &&
2311 "These instructions have already been scheduled.");
2312 ProcItinResources
.reserveResources(*(*I
)->getInstr());
2315 if (ST
.getInstrInfo()->isZeroCost(SU
->getInstr()->getOpcode()) ||
2316 ProcItinResources
.canReserveResources(*SU
->getInstr())) {
2318 dbgs() << "\tinsert at cycle " << curCycle
<< " ";
2319 SU
->getInstr()->dump();
2322 ScheduledInstrs
[curCycle
].push_back(SU
);
2323 InstrToCycle
.insert(std::make_pair(SU
, curCycle
));
2324 if (curCycle
> LastCycle
)
2325 LastCycle
= curCycle
;
2326 if (curCycle
< FirstCycle
)
2327 FirstCycle
= curCycle
;
2331 dbgs() << "\tfailed to insert at cycle " << curCycle
<< " ";
2332 SU
->getInstr()->dump();
2338 // Return the cycle of the earliest scheduled instruction in the chain.
2339 int SMSchedule::earliestCycleInChain(const SDep
&Dep
) {
2340 SmallPtrSet
<SUnit
*, 8> Visited
;
2341 SmallVector
<SDep
, 8> Worklist
;
2342 Worklist
.push_back(Dep
);
2343 int EarlyCycle
= INT_MAX
;
2344 while (!Worklist
.empty()) {
2345 const SDep
&Cur
= Worklist
.pop_back_val();
2346 SUnit
*PrevSU
= Cur
.getSUnit();
2347 if (Visited
.count(PrevSU
))
2349 std::map
<SUnit
*, int>::const_iterator it
= InstrToCycle
.find(PrevSU
);
2350 if (it
== InstrToCycle
.end())
2352 EarlyCycle
= std::min(EarlyCycle
, it
->second
);
2353 for (const auto &PI
: PrevSU
->Preds
)
2354 if (PI
.getKind() == SDep::Order
|| Dep
.getKind() == SDep::Output
)
2355 Worklist
.push_back(PI
);
2356 Visited
.insert(PrevSU
);
2361 // Return the cycle of the latest scheduled instruction in the chain.
2362 int SMSchedule::latestCycleInChain(const SDep
&Dep
) {
2363 SmallPtrSet
<SUnit
*, 8> Visited
;
2364 SmallVector
<SDep
, 8> Worklist
;
2365 Worklist
.push_back(Dep
);
2366 int LateCycle
= INT_MIN
;
2367 while (!Worklist
.empty()) {
2368 const SDep
&Cur
= Worklist
.pop_back_val();
2369 SUnit
*SuccSU
= Cur
.getSUnit();
2370 if (Visited
.count(SuccSU
))
2372 std::map
<SUnit
*, int>::const_iterator it
= InstrToCycle
.find(SuccSU
);
2373 if (it
== InstrToCycle
.end())
2375 LateCycle
= std::max(LateCycle
, it
->second
);
2376 for (const auto &SI
: SuccSU
->Succs
)
2377 if (SI
.getKind() == SDep::Order
|| Dep
.getKind() == SDep::Output
)
2378 Worklist
.push_back(SI
);
2379 Visited
.insert(SuccSU
);
2384 /// If an instruction has a use that spans multiple iterations, then
2385 /// return true. These instructions are characterized by having a back-ege
2386 /// to a Phi, which contains a reference to another Phi.
2387 static SUnit
*multipleIterations(SUnit
*SU
, SwingSchedulerDAG
*DAG
) {
2388 for (auto &P
: SU
->Preds
)
2389 if (DAG
->isBackedge(SU
, P
) && P
.getSUnit()->getInstr()->isPHI())
2390 for (auto &S
: P
.getSUnit()->Succs
)
2391 if (S
.getKind() == SDep::Data
&& S
.getSUnit()->getInstr()->isPHI())
2392 return P
.getSUnit();
2396 /// Compute the scheduling start slot for the instruction. The start slot
2397 /// depends on any predecessor or successor nodes scheduled already.
2398 void SMSchedule::computeStart(SUnit
*SU
, int *MaxEarlyStart
, int *MinLateStart
,
2399 int *MinEnd
, int *MaxStart
, int II
,
2400 SwingSchedulerDAG
*DAG
) {
2401 // Iterate over each instruction that has been scheduled already. The start
2402 // slot computation depends on whether the previously scheduled instruction
2403 // is a predecessor or successor of the specified instruction.
2404 for (int cycle
= getFirstCycle(); cycle
<= LastCycle
; ++cycle
) {
2406 // Iterate over each instruction in the current cycle.
2407 for (SUnit
*I
: getInstructions(cycle
)) {
2408 // Because we're processing a DAG for the dependences, we recognize
2409 // the back-edge in recurrences by anti dependences.
2410 for (unsigned i
= 0, e
= (unsigned)SU
->Preds
.size(); i
!= e
; ++i
) {
2411 const SDep
&Dep
= SU
->Preds
[i
];
2412 if (Dep
.getSUnit() == I
) {
2413 if (!DAG
->isBackedge(SU
, Dep
)) {
2414 int EarlyStart
= cycle
+ Dep
.getLatency() -
2415 DAG
->getDistance(Dep
.getSUnit(), SU
, Dep
) * II
;
2416 *MaxEarlyStart
= std::max(*MaxEarlyStart
, EarlyStart
);
2417 if (DAG
->isLoopCarriedDep(SU
, Dep
, false)) {
2418 int End
= earliestCycleInChain(Dep
) + (II
- 1);
2419 *MinEnd
= std::min(*MinEnd
, End
);
2422 int LateStart
= cycle
- Dep
.getLatency() +
2423 DAG
->getDistance(SU
, Dep
.getSUnit(), Dep
) * II
;
2424 *MinLateStart
= std::min(*MinLateStart
, LateStart
);
2427 // For instruction that requires multiple iterations, make sure that
2428 // the dependent instruction is not scheduled past the definition.
2429 SUnit
*BE
= multipleIterations(I
, DAG
);
2430 if (BE
&& Dep
.getSUnit() == BE
&& !SU
->getInstr()->isPHI() &&
2432 *MinLateStart
= std::min(*MinLateStart
, cycle
);
2434 for (unsigned i
= 0, e
= (unsigned)SU
->Succs
.size(); i
!= e
; ++i
) {
2435 if (SU
->Succs
[i
].getSUnit() == I
) {
2436 const SDep
&Dep
= SU
->Succs
[i
];
2437 if (!DAG
->isBackedge(SU
, Dep
)) {
2438 int LateStart
= cycle
- Dep
.getLatency() +
2439 DAG
->getDistance(SU
, Dep
.getSUnit(), Dep
) * II
;
2440 *MinLateStart
= std::min(*MinLateStart
, LateStart
);
2441 if (DAG
->isLoopCarriedDep(SU
, Dep
)) {
2442 int Start
= latestCycleInChain(Dep
) + 1 - II
;
2443 *MaxStart
= std::max(*MaxStart
, Start
);
2446 int EarlyStart
= cycle
+ Dep
.getLatency() -
2447 DAG
->getDistance(Dep
.getSUnit(), SU
, Dep
) * II
;
2448 *MaxEarlyStart
= std::max(*MaxEarlyStart
, EarlyStart
);
2456 /// Order the instructions within a cycle so that the definitions occur
2457 /// before the uses. Returns true if the instruction is added to the start
2458 /// of the list, or false if added to the end.
2459 void SMSchedule::orderDependence(SwingSchedulerDAG
*SSD
, SUnit
*SU
,
2460 std::deque
<SUnit
*> &Insts
) {
2461 MachineInstr
*MI
= SU
->getInstr();
2462 bool OrderBeforeUse
= false;
2463 bool OrderAfterDef
= false;
2464 bool OrderBeforeDef
= false;
2465 unsigned MoveDef
= 0;
2466 unsigned MoveUse
= 0;
2467 int StageInst1
= stageScheduled(SU
);
2470 for (std::deque
<SUnit
*>::iterator I
= Insts
.begin(), E
= Insts
.end(); I
!= E
;
2472 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
< e
; ++i
) {
2473 MachineOperand
&MO
= MI
->getOperand(i
);
2474 if (!MO
.isReg() || !Register::isVirtualRegister(MO
.getReg()))
2477 Register Reg
= MO
.getReg();
2478 unsigned BasePos
, OffsetPos
;
2479 if (ST
.getInstrInfo()->getBaseAndOffsetPosition(*MI
, BasePos
, OffsetPos
))
2480 if (MI
->getOperand(BasePos
).getReg() == Reg
)
2481 if (unsigned NewReg
= SSD
->getInstrBaseReg(SU
))
2484 std::tie(Reads
, Writes
) =
2485 (*I
)->getInstr()->readsWritesVirtualRegister(Reg
);
2486 if (MO
.isDef() && Reads
&& stageScheduled(*I
) <= StageInst1
) {
2487 OrderBeforeUse
= true;
2490 } else if (MO
.isDef() && Reads
&& stageScheduled(*I
) > StageInst1
) {
2491 // Add the instruction after the scheduled instruction.
2492 OrderAfterDef
= true;
2494 } else if (MO
.isUse() && Writes
&& stageScheduled(*I
) == StageInst1
) {
2495 if (cycleScheduled(*I
) == cycleScheduled(SU
) && !(*I
)->isSucc(SU
)) {
2496 OrderBeforeUse
= true;
2500 OrderAfterDef
= true;
2503 } else if (MO
.isUse() && Writes
&& stageScheduled(*I
) > StageInst1
) {
2504 OrderBeforeUse
= true;
2508 OrderAfterDef
= true;
2511 } else if (MO
.isUse() && Writes
&& stageScheduled(*I
) < StageInst1
) {
2512 // Add the instruction before the scheduled instruction.
2513 OrderBeforeUse
= true;
2516 } else if (MO
.isUse() && stageScheduled(*I
) == StageInst1
&&
2517 isLoopCarriedDefOfUse(SSD
, (*I
)->getInstr(), MO
)) {
2519 OrderBeforeDef
= true;
2524 // Check for order dependences between instructions. Make sure the source
2525 // is ordered before the destination.
2526 for (auto &S
: SU
->Succs
) {
2527 if (S
.getSUnit() != *I
)
2529 if (S
.getKind() == SDep::Order
&& stageScheduled(*I
) == StageInst1
) {
2530 OrderBeforeUse
= true;
2534 // We did not handle HW dependences in previous for loop,
2535 // and we normally set Latency = 0 for Anti deps,
2536 // so may have nodes in same cycle with Anti denpendent on HW regs.
2537 else if (S
.getKind() == SDep::Anti
&& stageScheduled(*I
) == StageInst1
) {
2538 OrderBeforeUse
= true;
2539 if ((MoveUse
== 0) || (Pos
< MoveUse
))
2543 for (auto &P
: SU
->Preds
) {
2544 if (P
.getSUnit() != *I
)
2546 if (P
.getKind() == SDep::Order
&& stageScheduled(*I
) == StageInst1
) {
2547 OrderAfterDef
= true;
2553 // A circular dependence.
2554 if (OrderAfterDef
&& OrderBeforeUse
&& MoveUse
== MoveDef
)
2555 OrderBeforeUse
= false;
2557 // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
2558 // to a loop-carried dependence.
2560 OrderBeforeUse
= !OrderAfterDef
|| (MoveUse
> MoveDef
);
2562 // The uncommon case when the instruction order needs to be updated because
2563 // there is both a use and def.
2564 if (OrderBeforeUse
&& OrderAfterDef
) {
2565 SUnit
*UseSU
= Insts
.at(MoveUse
);
2566 SUnit
*DefSU
= Insts
.at(MoveDef
);
2567 if (MoveUse
> MoveDef
) {
2568 Insts
.erase(Insts
.begin() + MoveUse
);
2569 Insts
.erase(Insts
.begin() + MoveDef
);
2571 Insts
.erase(Insts
.begin() + MoveDef
);
2572 Insts
.erase(Insts
.begin() + MoveUse
);
2574 orderDependence(SSD
, UseSU
, Insts
);
2575 orderDependence(SSD
, SU
, Insts
);
2576 orderDependence(SSD
, DefSU
, Insts
);
2579 // Put the new instruction first if there is a use in the list. Otherwise,
2580 // put it at the end of the list.
2582 Insts
.push_front(SU
);
2584 Insts
.push_back(SU
);
2587 /// Return true if the scheduled Phi has a loop carried operand.
2588 bool SMSchedule::isLoopCarried(SwingSchedulerDAG
*SSD
, MachineInstr
&Phi
) {
2591 assert(Phi
.isPHI() && "Expecting a Phi.");
2592 SUnit
*DefSU
= SSD
->getSUnit(&Phi
);
2593 unsigned DefCycle
= cycleScheduled(DefSU
);
2594 int DefStage
= stageScheduled(DefSU
);
2596 unsigned InitVal
= 0;
2597 unsigned LoopVal
= 0;
2598 getPhiRegs(Phi
, Phi
.getParent(), InitVal
, LoopVal
);
2599 SUnit
*UseSU
= SSD
->getSUnit(MRI
.getVRegDef(LoopVal
));
2602 if (UseSU
->getInstr()->isPHI())
2604 unsigned LoopCycle
= cycleScheduled(UseSU
);
2605 int LoopStage
= stageScheduled(UseSU
);
2606 return (LoopCycle
> DefCycle
) || (LoopStage
<= DefStage
);
2609 /// Return true if the instruction is a definition that is loop carried
2610 /// and defines the use on the next iteration.
2611 /// v1 = phi(v2, v3)
2612 /// (Def) v3 = op v1
2614 /// If MO appears before Def, then then v1 and v3 may get assigned to the same
2616 bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG
*SSD
,
2617 MachineInstr
*Def
, MachineOperand
&MO
) {
2622 MachineInstr
*Phi
= MRI
.getVRegDef(MO
.getReg());
2623 if (!Phi
|| !Phi
->isPHI() || Phi
->getParent() != Def
->getParent())
2625 if (!isLoopCarried(SSD
, *Phi
))
2627 unsigned LoopReg
= getLoopPhiReg(*Phi
, Phi
->getParent());
2628 for (unsigned i
= 0, e
= Def
->getNumOperands(); i
!= e
; ++i
) {
2629 MachineOperand
&DMO
= Def
->getOperand(i
);
2630 if (!DMO
.isReg() || !DMO
.isDef())
2632 if (DMO
.getReg() == LoopReg
)
2638 // Check if the generated schedule is valid. This function checks if
2639 // an instruction that uses a physical register is scheduled in a
2640 // different stage than the definition. The pipeliner does not handle
2641 // physical register values that may cross a basic block boundary.
2642 bool SMSchedule::isValidSchedule(SwingSchedulerDAG
*SSD
) {
2643 for (int i
= 0, e
= SSD
->SUnits
.size(); i
< e
; ++i
) {
2644 SUnit
&SU
= SSD
->SUnits
[i
];
2645 if (!SU
.hasPhysRegDefs
)
2647 int StageDef
= stageScheduled(&SU
);
2648 assert(StageDef
!= -1 && "Instruction should have been scheduled.");
2649 for (auto &SI
: SU
.Succs
)
2650 if (SI
.isAssignedRegDep())
2651 if (Register::isPhysicalRegister(SI
.getReg()))
2652 if (stageScheduled(SI
.getSUnit()) != StageDef
)
2658 /// A property of the node order in swing-modulo-scheduling is
2659 /// that for nodes outside circuits the following holds:
2660 /// none of them is scheduled after both a successor and a
2662 /// The method below checks whether the property is met.
2663 /// If not, debug information is printed and statistics information updated.
2664 /// Note that we do not use an assert statement.
2665 /// The reason is that although an invalid node oder may prevent
2666 /// the pipeliner from finding a pipelined schedule for arbitrary II,
2667 /// it does not lead to the generation of incorrect code.
2668 void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType
&Circuits
) const {
2670 // a sorted vector that maps each SUnit to its index in the NodeOrder
2671 typedef std::pair
<SUnit
*, unsigned> UnitIndex
;
2672 std::vector
<UnitIndex
> Indices(NodeOrder
.size(), std::make_pair(nullptr, 0));
2674 for (unsigned i
= 0, s
= NodeOrder
.size(); i
< s
; ++i
)
2675 Indices
.push_back(std::make_pair(NodeOrder
[i
], i
));
2677 auto CompareKey
= [](UnitIndex i1
, UnitIndex i2
) {
2678 return std::get
<0>(i1
) < std::get
<0>(i2
);
2681 // sort, so that we can perform a binary search
2682 llvm::sort(Indices
, CompareKey
);
2686 // for each SUnit in the NodeOrder, check whether
2687 // it appears after both a successor and a predecessor
2688 // of the SUnit. If this is the case, and the SUnit
2689 // is not part of circuit, then the NodeOrder is not
2691 for (unsigned i
= 0, s
= NodeOrder
.size(); i
< s
; ++i
) {
2692 SUnit
*SU
= NodeOrder
[i
];
2695 bool PredBefore
= false;
2696 bool SuccBefore
= false;
2703 for (SDep
&PredEdge
: SU
->Preds
) {
2704 SUnit
*PredSU
= PredEdge
.getSUnit();
2705 unsigned PredIndex
= std::get
<1>(
2706 *llvm::lower_bound(Indices
, std::make_pair(PredSU
, 0), CompareKey
));
2707 if (!PredSU
->getInstr()->isPHI() && PredIndex
< Index
) {
2714 for (SDep
&SuccEdge
: SU
->Succs
) {
2715 SUnit
*SuccSU
= SuccEdge
.getSUnit();
2716 // Do not process a boundary node, it was not included in NodeOrder,
2717 // hence not in Indices either, call to std::lower_bound() below will
2718 // return Indices.end().
2719 if (SuccSU
->isBoundaryNode())
2721 unsigned SuccIndex
= std::get
<1>(
2722 *llvm::lower_bound(Indices
, std::make_pair(SuccSU
, 0), CompareKey
));
2723 if (!SuccSU
->getInstr()->isPHI() && SuccIndex
< Index
) {
2730 if (PredBefore
&& SuccBefore
&& !SU
->getInstr()->isPHI()) {
2731 // instructions in circuits are allowed to be scheduled
2732 // after both a successor and predecessor.
2733 bool InCircuit
= llvm::any_of(
2734 Circuits
, [SU
](const NodeSet
&Circuit
) { return Circuit
.count(SU
); });
2736 LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
2739 NumNodeOrderIssues
++;
2740 LLVM_DEBUG(dbgs() << "Predecessor ";);
2742 LLVM_DEBUG(dbgs() << Pred
->NodeNum
<< " and successor " << Succ
->NodeNum
2743 << " are scheduled before node " << SU
->NodeNum
2750 dbgs() << "Invalid node order found!\n";
2754 /// Attempt to fix the degenerate cases when the instruction serialization
2755 /// causes the register lifetimes to overlap. For example,
2756 /// p' = store_pi(p, b)
2757 /// = load p, offset
2758 /// In this case p and p' overlap, which means that two registers are needed.
2759 /// Instead, this function changes the load to use p' and updates the offset.
2760 void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque
<SUnit
*> &Instrs
) {
2761 unsigned OverlapReg
= 0;
2762 unsigned NewBaseReg
= 0;
2763 for (SUnit
*SU
: Instrs
) {
2764 MachineInstr
*MI
= SU
->getInstr();
2765 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
< e
; ++i
) {
2766 const MachineOperand
&MO
= MI
->getOperand(i
);
2767 // Look for an instruction that uses p. The instruction occurs in the
2768 // same cycle but occurs later in the serialized order.
2769 if (MO
.isReg() && MO
.isUse() && MO
.getReg() == OverlapReg
) {
2770 // Check that the instruction appears in the InstrChanges structure,
2771 // which contains instructions that can have the offset updated.
2772 DenseMap
<SUnit
*, std::pair
<unsigned, int64_t>>::iterator It
=
2773 InstrChanges
.find(SU
);
2774 if (It
!= InstrChanges
.end()) {
2775 unsigned BasePos
, OffsetPos
;
2776 // Update the base register and adjust the offset.
2777 if (TII
->getBaseAndOffsetPosition(*MI
, BasePos
, OffsetPos
)) {
2778 MachineInstr
*NewMI
= MF
.CloneMachineInstr(MI
);
2779 NewMI
->getOperand(BasePos
).setReg(NewBaseReg
);
2781 MI
->getOperand(OffsetPos
).getImm() - It
->second
.second
;
2782 NewMI
->getOperand(OffsetPos
).setImm(NewOffset
);
2783 SU
->setInstr(NewMI
);
2784 MISUnitMap
[NewMI
] = SU
;
2792 // Look for an instruction of the form p' = op(p), which uses and defines
2793 // two virtual registers that get allocated to the same physical register.
2794 unsigned TiedUseIdx
= 0;
2795 if (MI
->isRegTiedToUseOperand(i
, &TiedUseIdx
)) {
2796 // OverlapReg is p in the example above.
2797 OverlapReg
= MI
->getOperand(TiedUseIdx
).getReg();
2798 // NewBaseReg is p' in the example above.
2799 NewBaseReg
= MI
->getOperand(i
).getReg();
2806 /// After the schedule has been formed, call this function to combine
2807 /// the instructions from the different stages/cycles. That is, this
2808 /// function creates a schedule that represents a single iteration.
2809 void SMSchedule::finalizeSchedule(SwingSchedulerDAG
*SSD
) {
2810 // Move all instructions to the first stage from later stages.
2811 for (int cycle
= getFirstCycle(); cycle
<= getFinalCycle(); ++cycle
) {
2812 for (int stage
= 1, lastStage
= getMaxStageCount(); stage
<= lastStage
;
2814 std::deque
<SUnit
*> &cycleInstrs
=
2815 ScheduledInstrs
[cycle
+ (stage
* InitiationInterval
)];
2816 for (std::deque
<SUnit
*>::reverse_iterator I
= cycleInstrs
.rbegin(),
2817 E
= cycleInstrs
.rend();
2819 ScheduledInstrs
[cycle
].push_front(*I
);
2823 // Erase all the elements in the later stages. Only one iteration should
2824 // remain in the scheduled list, and it contains all the instructions.
2825 for (int cycle
= getFinalCycle() + 1; cycle
<= LastCycle
; ++cycle
)
2826 ScheduledInstrs
.erase(cycle
);
2828 // Change the registers in instruction as specified in the InstrChanges
2829 // map. We need to use the new registers to create the correct order.
2830 for (int i
= 0, e
= SSD
->SUnits
.size(); i
!= e
; ++i
) {
2831 SUnit
*SU
= &SSD
->SUnits
[i
];
2832 SSD
->applyInstrChange(SU
->getInstr(), *this);
2835 // Reorder the instructions in each cycle to fix and improve the
2837 for (int Cycle
= getFirstCycle(), E
= getFinalCycle(); Cycle
<= E
; ++Cycle
) {
2838 std::deque
<SUnit
*> &cycleInstrs
= ScheduledInstrs
[Cycle
];
2839 std::deque
<SUnit
*> newOrderPhi
;
2840 for (unsigned i
= 0, e
= cycleInstrs
.size(); i
< e
; ++i
) {
2841 SUnit
*SU
= cycleInstrs
[i
];
2842 if (SU
->getInstr()->isPHI())
2843 newOrderPhi
.push_back(SU
);
2845 std::deque
<SUnit
*> newOrderI
;
2846 for (unsigned i
= 0, e
= cycleInstrs
.size(); i
< e
; ++i
) {
2847 SUnit
*SU
= cycleInstrs
[i
];
2848 if (!SU
->getInstr()->isPHI())
2849 orderDependence(SSD
, SU
, newOrderI
);
2851 // Replace the old order with the new order.
2852 cycleInstrs
.swap(newOrderPhi
);
2853 cycleInstrs
.insert(cycleInstrs
.end(), newOrderI
.begin(), newOrderI
.end());
2854 SSD
->fixupRegisterOverlaps(cycleInstrs
);
2857 LLVM_DEBUG(dump(););
2860 void NodeSet::print(raw_ostream
&os
) const {
2861 os
<< "Num nodes " << size() << " rec " << RecMII
<< " mov " << MaxMOV
2862 << " depth " << MaxDepth
<< " col " << Colocate
<< "\n";
2863 for (const auto &I
: Nodes
)
2864 os
<< " SU(" << I
->NodeNum
<< ") " << *(I
->getInstr());
2868 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2869 /// Print the schedule information to the given output.
2870 void SMSchedule::print(raw_ostream
&os
) const {
2871 // Iterate over each cycle.
2872 for (int cycle
= getFirstCycle(); cycle
<= getFinalCycle(); ++cycle
) {
2873 // Iterate over each instruction in the cycle.
2874 const_sched_iterator cycleInstrs
= ScheduledInstrs
.find(cycle
);
2875 for (SUnit
*CI
: cycleInstrs
->second
) {
2876 os
<< "cycle " << cycle
<< " (" << stageScheduled(CI
) << ") ";
2877 os
<< "(" << CI
->NodeNum
<< ") ";
2878 CI
->getInstr()->print(os
);
2884 /// Utility function used for debugging to print the schedule.
2885 LLVM_DUMP_METHOD
void SMSchedule::dump() const { print(dbgs()); }
2886 LLVM_DUMP_METHOD
void NodeSet::dump() const { print(dbgs()); }
2890 void ResourceManager::initProcResourceVectors(
2891 const MCSchedModel
&SM
, SmallVectorImpl
<uint64_t> &Masks
) {
2892 unsigned ProcResourceID
= 0;
2894 // We currently limit the resource kinds to 64 and below so that we can use
2895 // uint64_t for Masks
2896 assert(SM
.getNumProcResourceKinds() < 64 &&
2897 "Too many kinds of resources, unsupported");
2898 // Create a unique bitmask for every processor resource unit.
2899 // Skip resource at index 0, since it always references 'InvalidUnit'.
2900 Masks
.resize(SM
.getNumProcResourceKinds());
2901 for (unsigned I
= 1, E
= SM
.getNumProcResourceKinds(); I
< E
; ++I
) {
2902 const MCProcResourceDesc
&Desc
= *SM
.getProcResource(I
);
2903 if (Desc
.SubUnitsIdxBegin
)
2905 Masks
[I
] = 1ULL << ProcResourceID
;
2908 // Create a unique bitmask for every processor resource group.
2909 for (unsigned I
= 1, E
= SM
.getNumProcResourceKinds(); I
< E
; ++I
) {
2910 const MCProcResourceDesc
&Desc
= *SM
.getProcResource(I
);
2911 if (!Desc
.SubUnitsIdxBegin
)
2913 Masks
[I
] = 1ULL << ProcResourceID
;
2914 for (unsigned U
= 0; U
< Desc
.NumUnits
; ++U
)
2915 Masks
[I
] |= Masks
[Desc
.SubUnitsIdxBegin
[U
]];
2919 if (SwpShowResMask
) {
2920 dbgs() << "ProcResourceDesc:\n";
2921 for (unsigned I
= 1, E
= SM
.getNumProcResourceKinds(); I
< E
; ++I
) {
2922 const MCProcResourceDesc
*ProcResource
= SM
.getProcResource(I
);
2923 dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
2924 ProcResource
->Name
, I
, Masks
[I
],
2925 ProcResource
->NumUnits
);
2927 dbgs() << " -----------------\n";
2932 bool ResourceManager::canReserveResources(const MCInstrDesc
*MID
) const {
2935 if (SwpDebugResource
)
2936 dbgs() << "canReserveResources:\n";
2939 return DFAResources
->canReserveResources(MID
);
2941 unsigned InsnClass
= MID
->getSchedClass();
2942 const MCSchedClassDesc
*SCDesc
= SM
.getSchedClassDesc(InsnClass
);
2943 if (!SCDesc
->isValid()) {
2945 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
2946 dbgs() << "isPseduo:" << MID
->isPseudo() << "\n";
2951 const MCWriteProcResEntry
*I
= STI
->getWriteProcResBegin(SCDesc
);
2952 const MCWriteProcResEntry
*E
= STI
->getWriteProcResEnd(SCDesc
);
2953 for (; I
!= E
; ++I
) {
2956 const MCProcResourceDesc
*ProcResource
=
2957 SM
.getProcResource(I
->ProcResourceIdx
);
2958 unsigned NumUnits
= ProcResource
->NumUnits
;
2960 if (SwpDebugResource
)
2961 dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
2962 ProcResource
->Name
, I
->ProcResourceIdx
,
2963 ProcResourceCount
[I
->ProcResourceIdx
], NumUnits
,
2966 if (ProcResourceCount
[I
->ProcResourceIdx
] >= NumUnits
)
2969 LLVM_DEBUG(if (SwpDebugResource
) dbgs() << "return true\n\n";);
2973 void ResourceManager::reserveResources(const MCInstrDesc
*MID
) {
2975 if (SwpDebugResource
)
2976 dbgs() << "reserveResources:\n";
2979 return DFAResources
->reserveResources(MID
);
2981 unsigned InsnClass
= MID
->getSchedClass();
2982 const MCSchedClassDesc
*SCDesc
= SM
.getSchedClassDesc(InsnClass
);
2983 if (!SCDesc
->isValid()) {
2985 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
2986 dbgs() << "isPseduo:" << MID
->isPseudo() << "\n";
2990 for (const MCWriteProcResEntry
&PRE
:
2991 make_range(STI
->getWriteProcResBegin(SCDesc
),
2992 STI
->getWriteProcResEnd(SCDesc
))) {
2995 ++ProcResourceCount
[PRE
.ProcResourceIdx
];
2997 if (SwpDebugResource
) {
2998 const MCProcResourceDesc
*ProcResource
=
2999 SM
.getProcResource(PRE
.ProcResourceIdx
);
3000 dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
3001 ProcResource
->Name
, PRE
.ProcResourceIdx
,
3002 ProcResourceCount
[PRE
.ProcResourceIdx
],
3003 ProcResource
->NumUnits
, PRE
.Cycles
);
3008 if (SwpDebugResource
)
3009 dbgs() << "reserveResources: done!\n\n";
3013 bool ResourceManager::canReserveResources(const MachineInstr
&MI
) const {
3014 return canReserveResources(&MI
.getDesc());
3017 void ResourceManager::reserveResources(const MachineInstr
&MI
) {
3018 return reserveResources(&MI
.getDesc());
3021 void ResourceManager::clearResources() {
3023 return DFAResources
->clearResources();
3024 std::fill(ProcResourceCount
.begin(), ProcResourceCount
.end(), 0);