1 //===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
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 // Early if-conversion is for out-of-order CPUs that don't have a lot of
10 // predicable instructions. The goal is to eliminate conditional branches that
13 // Instructions from both sides of the branch are executed specutatively, and a
14 // cmov instruction selects the result.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SparseSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/MachineTraceMetrics.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/CodeGen/TargetInstrInfo.h"
35 #include "llvm/CodeGen/TargetRegisterInfo.h"
36 #include "llvm/CodeGen/TargetSubtargetInfo.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
44 #define DEBUG_TYPE "early-ifcvt"
46 // Absolute maximum number of instructions allowed per speculated block.
47 // This bypasses all other heuristics, so it should be set fairly high.
48 static cl::opt
<unsigned>
49 BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden
,
50 cl::desc("Maximum number of instructions per speculated block."));
52 // Stress testing mode - disable heuristics.
53 static cl::opt
<bool> Stress("stress-early-ifcvt", cl::Hidden
,
54 cl::desc("Turn all knobs to 11"));
56 STATISTIC(NumDiamondsSeen
, "Number of diamonds");
57 STATISTIC(NumDiamondsConv
, "Number of diamonds converted");
58 STATISTIC(NumTrianglesSeen
, "Number of triangles");
59 STATISTIC(NumTrianglesConv
, "Number of triangles converted");
61 //===----------------------------------------------------------------------===//
63 //===----------------------------------------------------------------------===//
65 // The SSAIfConv class performs if-conversion on SSA form machine code after
66 // determining if it is possible. The class contains no heuristics; external
67 // code should be used to determine when if-conversion is a good idea.
69 // SSAIfConv can convert both triangles and diamonds:
71 // Triangle: Head Diamond: Head
79 // Instructions in the conditional blocks TBB and/or FBB are spliced into the
80 // Head block, and phis in the Tail block are converted to select instructions.
84 const TargetInstrInfo
*TII
;
85 const TargetRegisterInfo
*TRI
;
86 MachineRegisterInfo
*MRI
;
89 /// The block containing the conditional branch.
90 MachineBasicBlock
*Head
;
92 /// The block containing phis after the if-then-else.
93 MachineBasicBlock
*Tail
;
95 /// The 'true' conditional block as determined by analyzeBranch.
96 MachineBasicBlock
*TBB
;
98 /// The 'false' conditional block as determined by analyzeBranch.
99 MachineBasicBlock
*FBB
;
101 /// isTriangle - When there is no 'else' block, either TBB or FBB will be
103 bool isTriangle() const { return TBB
== Tail
|| FBB
== Tail
; }
105 /// Returns the Tail predecessor for the True side.
106 MachineBasicBlock
*getTPred() const { return TBB
== Tail
? Head
: TBB
; }
108 /// Returns the Tail predecessor for the False side.
109 MachineBasicBlock
*getFPred() const { return FBB
== Tail
? Head
: FBB
; }
111 /// Information about each phi in the Tail block.
115 // Latencies from Cond+Branch, TReg, and FReg to DstReg.
116 int CondCycles
, TCycles
, FCycles
;
118 PHIInfo(MachineInstr
*phi
)
119 : PHI(phi
), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
122 SmallVector
<PHIInfo
, 8> PHIs
;
125 /// The branch condition determined by analyzeBranch.
126 SmallVector
<MachineOperand
, 4> Cond
;
128 /// Instructions in Head that define values used by the conditional blocks.
129 /// The hoisted instructions must be inserted after these instructions.
130 SmallPtrSet
<MachineInstr
*, 8> InsertAfter
;
132 /// Register units clobbered by the conditional blocks.
133 BitVector ClobberedRegUnits
;
135 // Scratch pad for findInsertionPoint.
136 SparseSet
<unsigned> LiveRegUnits
;
138 /// Insertion point in Head for speculatively executed instructions form TBB
140 MachineBasicBlock::iterator InsertionPoint
;
142 /// Return true if all non-terminator instructions in MBB can be safely
144 bool canSpeculateInstrs(MachineBasicBlock
*MBB
);
146 /// Return true if all non-terminator instructions in MBB can be safely
148 bool canPredicateInstrs(MachineBasicBlock
*MBB
);
150 /// Scan through instruction dependencies and update InsertAfter array.
151 /// Return false if any dependency is incompatible with if conversion.
152 bool InstrDependenciesAllowIfConv(MachineInstr
*I
);
154 /// Predicate all instructions of the basic block with current condition
155 /// except for terminators. Reverse the condition if ReversePredicate is set.
156 void PredicateBlock(MachineBasicBlock
*MBB
, bool ReversePredicate
);
158 /// Find a valid insertion point in Head.
159 bool findInsertionPoint();
161 /// Replace PHI instructions in Tail with selects.
162 void replacePHIInstrs();
164 /// Insert selects and rewrite PHI operands to use them.
165 void rewritePHIOperands();
168 /// runOnMachineFunction - Initialize per-function data structures.
169 void runOnMachineFunction(MachineFunction
&MF
) {
170 TII
= MF
.getSubtarget().getInstrInfo();
171 TRI
= MF
.getSubtarget().getRegisterInfo();
172 MRI
= &MF
.getRegInfo();
173 LiveRegUnits
.clear();
174 LiveRegUnits
.setUniverse(TRI
->getNumRegUnits());
175 ClobberedRegUnits
.clear();
176 ClobberedRegUnits
.resize(TRI
->getNumRegUnits());
179 /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
180 /// initialize the internal state, and return true.
181 /// If predicate is set try to predicate the block otherwise try to
182 /// speculatively execute it.
183 bool canConvertIf(MachineBasicBlock
*MBB
, bool Predicate
= false);
185 /// convertIf - If-convert the last block passed to canConvertIf(), assuming
186 /// it is possible. Add any erased blocks to RemovedBlocks.
187 void convertIf(SmallVectorImpl
<MachineBasicBlock
*> &RemovedBlocks
,
188 bool Predicate
= false);
190 } // end anonymous namespace
193 /// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
194 /// be speculated. The terminators are not considered.
196 /// If instructions use any values that are defined in the head basic block,
197 /// the defining instructions are added to InsertAfter.
199 /// Any clobbered regunits are added to ClobberedRegUnits.
201 bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock
*MBB
) {
202 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
204 if (!MBB
->livein_empty()) {
205 LLVM_DEBUG(dbgs() << printMBBReference(*MBB
) << " has live-ins.\n");
209 unsigned InstrCount
= 0;
211 // Check all instructions, except the terminators. It is assumed that
212 // terminators never have side effects or define any used register values.
213 for (MachineInstr
&MI
:
214 llvm::make_range(MBB
->begin(), MBB
->getFirstTerminator())) {
215 if (MI
.isDebugInstr())
218 if (++InstrCount
> BlockInstrLimit
&& !Stress
) {
219 LLVM_DEBUG(dbgs() << printMBBReference(*MBB
) << " has more than "
220 << BlockInstrLimit
<< " instructions.\n");
224 // There shouldn't normally be any phis in a single-predecessor block.
226 LLVM_DEBUG(dbgs() << "Can't hoist: " << MI
);
230 // Don't speculate loads. Note that it may be possible and desirable to
231 // speculate GOT or constant pool loads that are guaranteed not to trap,
232 // but we don't support that for now.
234 LLVM_DEBUG(dbgs() << "Won't speculate load: " << MI
);
238 // We never speculate stores, so an AA pointer isn't necessary.
239 bool DontMoveAcrossStore
= true;
240 if (!MI
.isSafeToMove(nullptr, DontMoveAcrossStore
)) {
241 LLVM_DEBUG(dbgs() << "Can't speculate: " << MI
);
245 // Check for any dependencies on Head instructions.
246 if (!InstrDependenciesAllowIfConv(&MI
))
252 /// Check that there is no dependencies preventing if conversion.
254 /// If instruction uses any values that are defined in the head basic block,
255 /// the defining instructions are added to InsertAfter.
256 bool SSAIfConv::InstrDependenciesAllowIfConv(MachineInstr
*I
) {
257 for (const MachineOperand
&MO
: I
->operands()) {
258 if (MO
.isRegMask()) {
259 LLVM_DEBUG(dbgs() << "Won't speculate regmask: " << *I
);
264 Register Reg
= MO
.getReg();
266 // Remember clobbered regunits.
267 if (MO
.isDef() && Register::isPhysicalRegister(Reg
))
268 for (MCRegUnitIterator
Units(Reg
.asMCReg(), TRI
); Units
.isValid();
270 ClobberedRegUnits
.set(*Units
);
272 if (!MO
.readsReg() || !Register::isVirtualRegister(Reg
))
274 MachineInstr
*DefMI
= MRI
->getVRegDef(Reg
);
275 if (!DefMI
|| DefMI
->getParent() != Head
)
277 if (InsertAfter
.insert(DefMI
).second
)
278 LLVM_DEBUG(dbgs() << printMBBReference(*I
->getParent()) << " depends on "
280 if (DefMI
->isTerminator()) {
281 LLVM_DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
288 /// canPredicateInstrs - Returns true if all the instructions in MBB can safely
289 /// be predicates. The terminators are not considered.
291 /// If instructions use any values that are defined in the head basic block,
292 /// the defining instructions are added to InsertAfter.
294 /// Any clobbered regunits are added to ClobberedRegUnits.
296 bool SSAIfConv::canPredicateInstrs(MachineBasicBlock
*MBB
) {
297 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
299 if (!MBB
->livein_empty()) {
300 LLVM_DEBUG(dbgs() << printMBBReference(*MBB
) << " has live-ins.\n");
304 unsigned InstrCount
= 0;
306 // Check all instructions, except the terminators. It is assumed that
307 // terminators never have side effects or define any used register values.
308 for (MachineBasicBlock::iterator I
= MBB
->begin(),
309 E
= MBB
->getFirstTerminator();
311 if (I
->isDebugInstr())
314 if (++InstrCount
> BlockInstrLimit
&& !Stress
) {
315 LLVM_DEBUG(dbgs() << printMBBReference(*MBB
) << " has more than "
316 << BlockInstrLimit
<< " instructions.\n");
320 // There shouldn't normally be any phis in a single-predecessor block.
322 LLVM_DEBUG(dbgs() << "Can't predicate: " << *I
);
326 // Check that instruction is predicable and that it is not already
328 if (!TII
->isPredicable(*I
) || TII
->isPredicated(*I
)) {
332 // Check for any dependencies on Head instructions.
333 if (!InstrDependenciesAllowIfConv(&(*I
)))
339 // Apply predicate to all instructions in the machine block.
340 void SSAIfConv::PredicateBlock(MachineBasicBlock
*MBB
, bool ReversePredicate
) {
341 auto Condition
= Cond
;
342 if (ReversePredicate
)
343 TII
->reverseBranchCondition(Condition
);
344 // Terminators don't need to be predicated as they will be removed.
345 for (MachineBasicBlock::iterator I
= MBB
->begin(),
346 E
= MBB
->getFirstTerminator();
348 if (I
->isDebugInstr())
350 TII
->PredicateInstruction(*I
, Condition
);
354 /// Find an insertion point in Head for the speculated instructions. The
355 /// insertion point must be:
357 /// 1. Before any terminators.
358 /// 2. After any instructions in InsertAfter.
359 /// 3. Not have any clobbered regunits live.
361 /// This function sets InsertionPoint and returns true when successful, it
362 /// returns false if no valid insertion point could be found.
364 bool SSAIfConv::findInsertionPoint() {
365 // Keep track of live regunits before the current position.
366 // Only track RegUnits that are also in ClobberedRegUnits.
367 LiveRegUnits
.clear();
368 SmallVector
<MCRegister
, 8> Reads
;
369 MachineBasicBlock::iterator FirstTerm
= Head
->getFirstTerminator();
370 MachineBasicBlock::iterator I
= Head
->end();
371 MachineBasicBlock::iterator B
= Head
->begin();
374 // Some of the conditional code depends in I.
375 if (InsertAfter
.count(&*I
)) {
376 LLVM_DEBUG(dbgs() << "Can't insert code after " << *I
);
380 // Update live regunits.
381 for (const MachineOperand
&MO
: I
->operands()) {
382 // We're ignoring regmask operands. That is conservatively correct.
385 Register Reg
= MO
.getReg();
386 if (!Register::isPhysicalRegister(Reg
))
388 // I clobbers Reg, so it isn't live before I.
390 for (MCRegUnitIterator
Units(Reg
.asMCReg(), TRI
); Units
.isValid();
392 LiveRegUnits
.erase(*Units
);
393 // Unless I reads Reg.
395 Reads
.push_back(Reg
.asMCReg());
397 // Anything read by I is live before I.
398 while (!Reads
.empty())
399 for (MCRegUnitIterator
Units(Reads
.pop_back_val(), TRI
); Units
.isValid();
401 if (ClobberedRegUnits
.test(*Units
))
402 LiveRegUnits
.insert(*Units
);
404 // We can't insert before a terminator.
405 if (I
!= FirstTerm
&& I
->isTerminator())
408 // Some of the clobbered registers are live before I, not a valid insertion
410 if (!LiveRegUnits
.empty()) {
412 dbgs() << "Would clobber";
413 for (unsigned LRU
: LiveRegUnits
)
414 dbgs() << ' ' << printRegUnit(LRU
, TRI
);
415 dbgs() << " live before " << *I
;
420 // This is a valid insertion point.
422 LLVM_DEBUG(dbgs() << "Can insert before " << *I
);
425 LLVM_DEBUG(dbgs() << "No legal insertion point found.\n");
431 /// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
432 /// a potential candidate for if-conversion. Fill out the internal state.
434 bool SSAIfConv::canConvertIf(MachineBasicBlock
*MBB
, bool Predicate
) {
436 TBB
= FBB
= Tail
= nullptr;
438 if (Head
->succ_size() != 2)
440 MachineBasicBlock
*Succ0
= Head
->succ_begin()[0];
441 MachineBasicBlock
*Succ1
= Head
->succ_begin()[1];
443 // Canonicalize so Succ0 has MBB as its single predecessor.
444 if (Succ0
->pred_size() != 1)
445 std::swap(Succ0
, Succ1
);
447 if (Succ0
->pred_size() != 1 || Succ0
->succ_size() != 1)
450 Tail
= Succ0
->succ_begin()[0];
452 // This is not a triangle.
454 // Check for a diamond. We won't deal with any critical edges.
455 if (Succ1
->pred_size() != 1 || Succ1
->succ_size() != 1 ||
456 Succ1
->succ_begin()[0] != Tail
)
458 LLVM_DEBUG(dbgs() << "\nDiamond: " << printMBBReference(*Head
) << " -> "
459 << printMBBReference(*Succ0
) << "/"
460 << printMBBReference(*Succ1
) << " -> "
461 << printMBBReference(*Tail
) << '\n');
463 // Live-in physregs are tricky to get right when speculating code.
464 if (!Tail
->livein_empty()) {
465 LLVM_DEBUG(dbgs() << "Tail has live-ins.\n");
469 LLVM_DEBUG(dbgs() << "\nTriangle: " << printMBBReference(*Head
) << " -> "
470 << printMBBReference(*Succ0
) << " -> "
471 << printMBBReference(*Tail
) << '\n');
474 // This is a triangle or a diamond.
475 // Skip if we cannot predicate and there are no phis skip as there must be
476 // side effects that can only be handled with predication.
477 if (!Predicate
&& (Tail
->empty() || !Tail
->front().isPHI())) {
478 LLVM_DEBUG(dbgs() << "No phis in tail.\n");
482 // The branch we're looking to eliminate must be analyzable.
484 if (TII
->analyzeBranch(*Head
, TBB
, FBB
, Cond
)) {
485 LLVM_DEBUG(dbgs() << "Branch not analyzable.\n");
489 // This is weird, probably some sort of degenerate CFG.
491 LLVM_DEBUG(dbgs() << "analyzeBranch didn't find conditional branch.\n");
495 // Make sure the analyzed branch is conditional; one of the successors
496 // could be a landing pad. (Empty landing pads can be generated on Windows.)
498 LLVM_DEBUG(dbgs() << "analyzeBranch found an unconditional branch.\n");
502 // analyzeBranch doesn't set FBB on a fall-through branch.
503 // Make sure it is always set.
504 FBB
= TBB
== Succ0
? Succ1
: Succ0
;
506 // Any phis in the tail block must be convertible to selects.
508 MachineBasicBlock
*TPred
= getTPred();
509 MachineBasicBlock
*FPred
= getFPred();
510 for (MachineBasicBlock::iterator I
= Tail
->begin(), E
= Tail
->end();
511 I
!= E
&& I
->isPHI(); ++I
) {
513 PHIInfo
&PI
= PHIs
.back();
514 // Find PHI operands corresponding to TPred and FPred.
515 for (unsigned i
= 1; i
!= PI
.PHI
->getNumOperands(); i
+= 2) {
516 if (PI
.PHI
->getOperand(i
+1).getMBB() == TPred
)
517 PI
.TReg
= PI
.PHI
->getOperand(i
).getReg();
518 if (PI
.PHI
->getOperand(i
+1).getMBB() == FPred
)
519 PI
.FReg
= PI
.PHI
->getOperand(i
).getReg();
521 assert(Register::isVirtualRegister(PI
.TReg
) && "Bad PHI");
522 assert(Register::isVirtualRegister(PI
.FReg
) && "Bad PHI");
524 // Get target information.
525 if (!TII
->canInsertSelect(*Head
, Cond
, PI
.PHI
->getOperand(0).getReg(),
526 PI
.TReg
, PI
.FReg
, PI
.CondCycles
, PI
.TCycles
,
528 LLVM_DEBUG(dbgs() << "Can't convert: " << *PI
.PHI
);
533 // Check that the conditional instructions can be speculated.
535 ClobberedRegUnits
.reset();
537 if (TBB
!= Tail
&& !canPredicateInstrs(TBB
))
539 if (FBB
!= Tail
&& !canPredicateInstrs(FBB
))
542 if (TBB
!= Tail
&& !canSpeculateInstrs(TBB
))
544 if (FBB
!= Tail
&& !canSpeculateInstrs(FBB
))
548 // Try to find a valid insertion point for the speculated instructions in the
550 if (!findInsertionPoint())
560 /// \return true iff the two registers are known to have the same value.
561 static bool hasSameValue(const MachineRegisterInfo
&MRI
,
562 const TargetInstrInfo
*TII
, Register TReg
,
567 if (!TReg
.isVirtual() || !FReg
.isVirtual())
570 const MachineInstr
*TDef
= MRI
.getUniqueVRegDef(TReg
);
571 const MachineInstr
*FDef
= MRI
.getUniqueVRegDef(FReg
);
575 // If there are side-effects, all bets are off.
576 if (TDef
->hasUnmodeledSideEffects())
579 // If the instruction could modify memory, or there may be some intervening
580 // store between the two, we can't consider them to be equal.
581 if (TDef
->mayLoadOrStore() && !TDef
->isDereferenceableInvariantLoad(nullptr))
584 // We also can't guarantee that they are the same if, for example, the
585 // instructions are both a copy from a physical reg, because some other
586 // instruction may have modified the value in that reg between the two
588 if (any_of(TDef
->uses(), [](const MachineOperand
&MO
) {
589 return MO
.isReg() && MO
.getReg().isPhysical();
593 // Check whether the two defining instructions produce the same value(s).
594 if (!TII
->produceSameValue(*TDef
, *FDef
, &MRI
))
597 // Further, check that the two defs come from corresponding operands.
598 int TIdx
= TDef
->findRegisterDefOperandIdx(TReg
);
599 int FIdx
= FDef
->findRegisterDefOperandIdx(FReg
);
600 if (TIdx
== -1 || FIdx
== -1)
606 /// replacePHIInstrs - Completely replace PHI instructions with selects.
607 /// This is possible when the only Tail predecessors are the if-converted
609 void SSAIfConv::replacePHIInstrs() {
610 assert(Tail
->pred_size() == 2 && "Cannot replace PHIs");
611 MachineBasicBlock::iterator FirstTerm
= Head
->getFirstTerminator();
612 assert(FirstTerm
!= Head
->end() && "No terminators");
613 DebugLoc HeadDL
= FirstTerm
->getDebugLoc();
615 // Convert all PHIs to select instructions inserted before FirstTerm.
616 for (unsigned i
= 0, e
= PHIs
.size(); i
!= e
; ++i
) {
617 PHIInfo
&PI
= PHIs
[i
];
618 LLVM_DEBUG(dbgs() << "If-converting " << *PI
.PHI
);
619 Register DstReg
= PI
.PHI
->getOperand(0).getReg();
620 if (hasSameValue(*MRI
, TII
, PI
.TReg
, PI
.FReg
)) {
621 // We do not need the select instruction if both incoming values are
622 // equal, but we do need a COPY.
623 BuildMI(*Head
, FirstTerm
, HeadDL
, TII
->get(TargetOpcode::COPY
), DstReg
)
626 TII
->insertSelect(*Head
, FirstTerm
, HeadDL
, DstReg
, Cond
, PI
.TReg
,
629 LLVM_DEBUG(dbgs() << " --> " << *std::prev(FirstTerm
));
630 PI
.PHI
->eraseFromParent();
635 /// rewritePHIOperands - When there are additional Tail predecessors, insert
636 /// select instructions in Head and rewrite PHI operands to use the selects.
637 /// Keep the PHI instructions in Tail to handle the other predecessors.
638 void SSAIfConv::rewritePHIOperands() {
639 MachineBasicBlock::iterator FirstTerm
= Head
->getFirstTerminator();
640 assert(FirstTerm
!= Head
->end() && "No terminators");
641 DebugLoc HeadDL
= FirstTerm
->getDebugLoc();
643 // Convert all PHIs to select instructions inserted before FirstTerm.
644 for (unsigned i
= 0, e
= PHIs
.size(); i
!= e
; ++i
) {
645 PHIInfo
&PI
= PHIs
[i
];
648 LLVM_DEBUG(dbgs() << "If-converting " << *PI
.PHI
);
649 if (hasSameValue(*MRI
, TII
, PI
.TReg
, PI
.FReg
)) {
650 // We do not need the select instruction if both incoming values are
654 Register PHIDst
= PI
.PHI
->getOperand(0).getReg();
655 DstReg
= MRI
->createVirtualRegister(MRI
->getRegClass(PHIDst
));
656 TII
->insertSelect(*Head
, FirstTerm
, HeadDL
,
657 DstReg
, Cond
, PI
.TReg
, PI
.FReg
);
658 LLVM_DEBUG(dbgs() << " --> " << *std::prev(FirstTerm
));
661 // Rewrite PHI operands TPred -> (DstReg, Head), remove FPred.
662 for (unsigned i
= PI
.PHI
->getNumOperands(); i
!= 1; i
-= 2) {
663 MachineBasicBlock
*MBB
= PI
.PHI
->getOperand(i
-1).getMBB();
664 if (MBB
== getTPred()) {
665 PI
.PHI
->getOperand(i
-1).setMBB(Head
);
666 PI
.PHI
->getOperand(i
-2).setReg(DstReg
);
667 } else if (MBB
== getFPred()) {
668 PI
.PHI
->RemoveOperand(i
-1);
669 PI
.PHI
->RemoveOperand(i
-2);
672 LLVM_DEBUG(dbgs() << " --> " << *PI
.PHI
);
676 /// convertIf - Execute the if conversion after canConvertIf has determined the
679 /// Any basic blocks erased will be added to RemovedBlocks.
681 void SSAIfConv::convertIf(SmallVectorImpl
<MachineBasicBlock
*> &RemovedBlocks
,
683 assert(Head
&& Tail
&& TBB
&& FBB
&& "Call canConvertIf first.");
685 // Update statistics.
691 // Move all instructions into Head, except for the terminators.
694 PredicateBlock(TBB
, /*ReversePredicate=*/false);
695 Head
->splice(InsertionPoint
, TBB
, TBB
->begin(), TBB
->getFirstTerminator());
699 PredicateBlock(FBB
, /*ReversePredicate=*/true);
700 Head
->splice(InsertionPoint
, FBB
, FBB
->begin(), FBB
->getFirstTerminator());
702 // Are there extra Tail predecessors?
703 bool ExtraPreds
= Tail
->pred_size() != 2;
705 rewritePHIOperands();
709 // Fix up the CFG, temporarily leave Head without any successors.
710 Head
->removeSuccessor(TBB
);
711 Head
->removeSuccessor(FBB
, true);
713 TBB
->removeSuccessor(Tail
, true);
715 FBB
->removeSuccessor(Tail
, true);
717 // Fix up Head's terminators.
718 // It should become a single branch or a fallthrough.
719 DebugLoc HeadDL
= Head
->getFirstTerminator()->getDebugLoc();
720 TII
->removeBranch(*Head
);
722 // Erase the now empty conditional blocks. It is likely that Head can fall
723 // through to Tail, and we can join the two blocks.
725 RemovedBlocks
.push_back(TBB
);
726 TBB
->eraseFromParent();
729 RemovedBlocks
.push_back(FBB
);
730 FBB
->eraseFromParent();
733 assert(Head
->succ_empty() && "Additional head successors?");
734 if (!ExtraPreds
&& Head
->isLayoutSuccessor(Tail
)) {
735 // Splice Tail onto the end of Head.
736 LLVM_DEBUG(dbgs() << "Joining tail " << printMBBReference(*Tail
)
737 << " into head " << printMBBReference(*Head
) << '\n');
738 Head
->splice(Head
->end(), Tail
,
739 Tail
->begin(), Tail
->end());
740 Head
->transferSuccessorsAndUpdatePHIs(Tail
);
741 RemovedBlocks
.push_back(Tail
);
742 Tail
->eraseFromParent();
744 // We need a branch to Tail, let code placement work it out later.
745 LLVM_DEBUG(dbgs() << "Converting to unconditional branch.\n");
746 SmallVector
<MachineOperand
, 0> EmptyCond
;
747 TII
->insertBranch(*Head
, Tail
, nullptr, EmptyCond
, HeadDL
);
748 Head
->addSuccessor(Tail
);
750 LLVM_DEBUG(dbgs() << *Head
);
753 //===----------------------------------------------------------------------===//
754 // EarlyIfConverter Pass
755 //===----------------------------------------------------------------------===//
758 class EarlyIfConverter
: public MachineFunctionPass
{
759 const TargetInstrInfo
*TII
;
760 const TargetRegisterInfo
*TRI
;
761 MCSchedModel SchedModel
;
762 MachineRegisterInfo
*MRI
;
763 MachineDominatorTree
*DomTree
;
764 MachineLoopInfo
*Loops
;
765 MachineTraceMetrics
*Traces
;
766 MachineTraceMetrics::Ensemble
*MinInstr
;
771 EarlyIfConverter() : MachineFunctionPass(ID
) {}
772 void getAnalysisUsage(AnalysisUsage
&AU
) const override
;
773 bool runOnMachineFunction(MachineFunction
&MF
) override
;
774 StringRef
getPassName() const override
{ return "Early If-Conversion"; }
777 bool tryConvertIf(MachineBasicBlock
*);
778 void invalidateTraces();
779 bool shouldConvertIf();
781 } // end anonymous namespace
783 char EarlyIfConverter::ID
= 0;
784 char &llvm::EarlyIfConverterID
= EarlyIfConverter::ID
;
786 INITIALIZE_PASS_BEGIN(EarlyIfConverter
, DEBUG_TYPE
,
787 "Early If Converter", false, false)
788 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo
)
789 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
790 INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics
)
791 INITIALIZE_PASS_END(EarlyIfConverter
, DEBUG_TYPE
,
792 "Early If Converter", false, false)
794 void EarlyIfConverter::getAnalysisUsage(AnalysisUsage
&AU
) const {
795 AU
.addRequired
<MachineBranchProbabilityInfo
>();
796 AU
.addRequired
<MachineDominatorTree
>();
797 AU
.addPreserved
<MachineDominatorTree
>();
798 AU
.addRequired
<MachineLoopInfo
>();
799 AU
.addPreserved
<MachineLoopInfo
>();
800 AU
.addRequired
<MachineTraceMetrics
>();
801 AU
.addPreserved
<MachineTraceMetrics
>();
802 MachineFunctionPass::getAnalysisUsage(AU
);
806 /// Update the dominator tree after if-conversion erased some blocks.
807 void updateDomTree(MachineDominatorTree
*DomTree
, const SSAIfConv
&IfConv
,
808 ArrayRef
<MachineBasicBlock
*> Removed
) {
809 // convertIf can remove TBB, FBB, and Tail can be merged into Head.
810 // TBB and FBB should not dominate any blocks.
811 // Tail children should be transferred to Head.
812 MachineDomTreeNode
*HeadNode
= DomTree
->getNode(IfConv
.Head
);
813 for (auto B
: Removed
) {
814 MachineDomTreeNode
*Node
= DomTree
->getNode(B
);
815 assert(Node
!= HeadNode
&& "Cannot erase the head node");
816 while (Node
->getNumChildren()) {
817 assert(Node
->getBlock() == IfConv
.Tail
&& "Unexpected children");
818 DomTree
->changeImmediateDominator(Node
->back(), HeadNode
);
820 DomTree
->eraseNode(B
);
824 /// Update LoopInfo after if-conversion.
825 void updateLoops(MachineLoopInfo
*Loops
,
826 ArrayRef
<MachineBasicBlock
*> Removed
) {
829 // If-conversion doesn't change loop structure, and it doesn't mess with back
830 // edges, so updating LoopInfo is simply removing the dead blocks.
831 for (auto B
: Removed
)
832 Loops
->removeBlock(B
);
836 /// Invalidate MachineTraceMetrics before if-conversion.
837 void EarlyIfConverter::invalidateTraces() {
838 Traces
->verifyAnalysis();
839 Traces
->invalidate(IfConv
.Head
);
840 Traces
->invalidate(IfConv
.Tail
);
841 Traces
->invalidate(IfConv
.TBB
);
842 Traces
->invalidate(IfConv
.FBB
);
843 Traces
->verifyAnalysis();
846 // Adjust cycles with downward saturation.
847 static unsigned adjCycles(unsigned Cyc
, int Delta
) {
848 if (Delta
< 0 && Cyc
+ Delta
> Cyc
)
854 /// Helper class to simplify emission of cycle counts into optimization remarks.
859 template <typename Remark
> Remark
&operator<<(Remark
&R
, Cycles C
) {
860 return R
<< ore::NV(C
.Key
, C
.Value
) << (C
.Value
== 1 ? " cycle" : " cycles");
862 } // anonymous namespace
864 /// Apply cost model and heuristics to the if-conversion in IfConv.
865 /// Return true if the conversion is a good idea.
867 bool EarlyIfConverter::shouldConvertIf() {
868 // Stress testing mode disables all cost considerations.
873 MinInstr
= Traces
->getEnsemble(MachineTraceMetrics::TS_MinInstrCount
);
875 MachineTraceMetrics::Trace TBBTrace
= MinInstr
->getTrace(IfConv
.getTPred());
876 MachineTraceMetrics::Trace FBBTrace
= MinInstr
->getTrace(IfConv
.getFPred());
877 LLVM_DEBUG(dbgs() << "TBB: " << TBBTrace
<< "FBB: " << FBBTrace
);
878 unsigned MinCrit
= std::min(TBBTrace
.getCriticalPath(),
879 FBBTrace
.getCriticalPath());
881 // Set a somewhat arbitrary limit on the critical path extension we accept.
882 unsigned CritLimit
= SchedModel
.MispredictPenalty
/2;
884 MachineBasicBlock
&MBB
= *IfConv
.Head
;
885 MachineOptimizationRemarkEmitter
MORE(*MBB
.getParent(), nullptr);
887 // If-conversion only makes sense when there is unexploited ILP. Compute the
888 // maximum-ILP resource length of the trace after if-conversion. Compare it
889 // to the shortest critical path.
890 SmallVector
<const MachineBasicBlock
*, 1> ExtraBlocks
;
891 if (IfConv
.TBB
!= IfConv
.Tail
)
892 ExtraBlocks
.push_back(IfConv
.TBB
);
893 unsigned ResLength
= FBBTrace
.getResourceLength(ExtraBlocks
);
894 LLVM_DEBUG(dbgs() << "Resource length " << ResLength
895 << ", minimal critical path " << MinCrit
<< '\n');
896 if (ResLength
> MinCrit
+ CritLimit
) {
897 LLVM_DEBUG(dbgs() << "Not enough available ILP.\n");
899 MachineOptimizationRemarkMissed
R(DEBUG_TYPE
, "IfConversion",
900 MBB
.findDebugLoc(MBB
.back()), &MBB
);
901 R
<< "did not if-convert branch: the resulting critical path ("
902 << Cycles
{"ResLength", ResLength
}
903 << ") would extend the shorter leg's critical path ("
904 << Cycles
{"MinCrit", MinCrit
} << ") by more than the threshold of "
905 << Cycles
{"CritLimit", CritLimit
}
906 << ", which cannot be hidden by available ILP.";
912 // Assume that the depth of the first head terminator will also be the depth
913 // of the select instruction inserted, as determined by the flag dependency.
914 // TBB / FBB data dependencies may delay the select even more.
915 MachineTraceMetrics::Trace HeadTrace
= MinInstr
->getTrace(IfConv
.Head
);
916 unsigned BranchDepth
=
917 HeadTrace
.getInstrCycles(*IfConv
.Head
->getFirstTerminator()).Depth
;
918 LLVM_DEBUG(dbgs() << "Branch depth: " << BranchDepth
<< '\n');
920 // Look at all the tail phis, and compute the critical path extension caused
921 // by inserting select instructions.
922 MachineTraceMetrics::Trace TailTrace
= MinInstr
->getTrace(IfConv
.Tail
);
923 struct CriticalPathInfo
{
924 unsigned Extra
; // Count of extra cycles that the component adds.
925 unsigned Depth
; // Absolute depth of the component in cycles.
927 CriticalPathInfo Cond
{};
928 CriticalPathInfo TBlock
{};
929 CriticalPathInfo FBlock
{};
930 bool ShouldConvert
= true;
931 for (unsigned i
= 0, e
= IfConv
.PHIs
.size(); i
!= e
; ++i
) {
932 SSAIfConv::PHIInfo
&PI
= IfConv
.PHIs
[i
];
933 unsigned Slack
= TailTrace
.getInstrSlack(*PI
.PHI
);
934 unsigned MaxDepth
= Slack
+ TailTrace
.getInstrCycles(*PI
.PHI
).Depth
;
935 LLVM_DEBUG(dbgs() << "Slack " << Slack
<< ":\t" << *PI
.PHI
);
937 // The condition is pulled into the critical path.
938 unsigned CondDepth
= adjCycles(BranchDepth
, PI
.CondCycles
);
939 if (CondDepth
> MaxDepth
) {
940 unsigned Extra
= CondDepth
- MaxDepth
;
941 LLVM_DEBUG(dbgs() << "Condition adds " << Extra
<< " cycles.\n");
942 if (Extra
> Cond
.Extra
)
943 Cond
= {Extra
, CondDepth
};
944 if (Extra
> CritLimit
) {
945 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit
<< '\n');
946 ShouldConvert
= false;
950 // The TBB value is pulled into the critical path.
951 unsigned TDepth
= adjCycles(TBBTrace
.getPHIDepth(*PI
.PHI
), PI
.TCycles
);
952 if (TDepth
> MaxDepth
) {
953 unsigned Extra
= TDepth
- MaxDepth
;
954 LLVM_DEBUG(dbgs() << "TBB data adds " << Extra
<< " cycles.\n");
955 if (Extra
> TBlock
.Extra
)
956 TBlock
= {Extra
, TDepth
};
957 if (Extra
> CritLimit
) {
958 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit
<< '\n');
959 ShouldConvert
= false;
963 // The FBB value is pulled into the critical path.
964 unsigned FDepth
= adjCycles(FBBTrace
.getPHIDepth(*PI
.PHI
), PI
.FCycles
);
965 if (FDepth
> MaxDepth
) {
966 unsigned Extra
= FDepth
- MaxDepth
;
967 LLVM_DEBUG(dbgs() << "FBB data adds " << Extra
<< " cycles.\n");
968 if (Extra
> FBlock
.Extra
)
969 FBlock
= {Extra
, FDepth
};
970 if (Extra
> CritLimit
) {
971 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit
<< '\n');
972 ShouldConvert
= false;
977 // Organize by "short" and "long" legs, since the diagnostics get confusing
978 // when referring to the "true" and "false" sides of the branch, given that
979 // those don't always correlate with what the user wrote in source-terms.
980 const CriticalPathInfo Short
= TBlock
.Extra
> FBlock
.Extra
? FBlock
: TBlock
;
981 const CriticalPathInfo Long
= TBlock
.Extra
> FBlock
.Extra
? TBlock
: FBlock
;
985 MachineOptimizationRemark
R(DEBUG_TYPE
, "IfConversion",
986 MBB
.back().getDebugLoc(), &MBB
);
987 R
<< "performing if-conversion on branch: the condition adds "
988 << Cycles
{"CondCycles", Cond
.Extra
} << " to the critical path";
990 R
<< ", and the short leg adds another "
991 << Cycles
{"ShortCycles", Short
.Extra
};
993 R
<< ", and the long leg adds another "
994 << Cycles
{"LongCycles", Long
.Extra
};
995 R
<< ", each staying under the threshold of "
996 << Cycles
{"CritLimit", CritLimit
} << ".";
1001 MachineOptimizationRemarkMissed
R(DEBUG_TYPE
, "IfConversion",
1002 MBB
.back().getDebugLoc(), &MBB
);
1003 R
<< "did not if-convert branch: the condition would add "
1004 << Cycles
{"CondCycles", Cond
.Extra
} << " to the critical path";
1005 if (Cond
.Extra
> CritLimit
)
1006 R
<< " exceeding the limit of " << Cycles
{"CritLimit", CritLimit
};
1007 if (Short
.Extra
> 0) {
1008 R
<< ", and the short leg would add another "
1009 << Cycles
{"ShortCycles", Short
.Extra
};
1010 if (Short
.Extra
> CritLimit
)
1011 R
<< " exceeding the limit of " << Cycles
{"CritLimit", CritLimit
};
1013 if (Long
.Extra
> 0) {
1014 R
<< ", and the long leg would add another "
1015 << Cycles
{"LongCycles", Long
.Extra
};
1016 if (Long
.Extra
> CritLimit
)
1017 R
<< " exceeding the limit of " << Cycles
{"CritLimit", CritLimit
};
1024 return ShouldConvert
;
1027 /// Attempt repeated if-conversion on MBB, return true if successful.
1029 bool EarlyIfConverter::tryConvertIf(MachineBasicBlock
*MBB
) {
1030 bool Changed
= false;
1031 while (IfConv
.canConvertIf(MBB
) && shouldConvertIf()) {
1032 // If-convert MBB and update analyses.
1034 SmallVector
<MachineBasicBlock
*, 4> RemovedBlocks
;
1035 IfConv
.convertIf(RemovedBlocks
);
1037 updateDomTree(DomTree
, IfConv
, RemovedBlocks
);
1038 updateLoops(Loops
, RemovedBlocks
);
1043 bool EarlyIfConverter::runOnMachineFunction(MachineFunction
&MF
) {
1044 LLVM_DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
1045 << "********** Function: " << MF
.getName() << '\n');
1046 if (skipFunction(MF
.getFunction()))
1049 // Only run if conversion if the target wants it.
1050 const TargetSubtargetInfo
&STI
= MF
.getSubtarget();
1051 if (!STI
.enableEarlyIfConversion())
1054 TII
= STI
.getInstrInfo();
1055 TRI
= STI
.getRegisterInfo();
1056 SchedModel
= STI
.getSchedModel();
1057 MRI
= &MF
.getRegInfo();
1058 DomTree
= &getAnalysis
<MachineDominatorTree
>();
1059 Loops
= getAnalysisIfAvailable
<MachineLoopInfo
>();
1060 Traces
= &getAnalysis
<MachineTraceMetrics
>();
1063 bool Changed
= false;
1064 IfConv
.runOnMachineFunction(MF
);
1066 // Visit blocks in dominator tree post-order. The post-order enables nested
1067 // if-conversion in a single pass. The tryConvertIf() function may erase
1068 // blocks, but only blocks dominated by the head block. This makes it safe to
1069 // update the dominator tree while the post-order iterator is still active.
1070 for (auto DomNode
: post_order(DomTree
))
1071 if (tryConvertIf(DomNode
->getBlock()))
1077 //===----------------------------------------------------------------------===//
1078 // EarlyIfPredicator Pass
1079 //===----------------------------------------------------------------------===//
1082 class EarlyIfPredicator
: public MachineFunctionPass
{
1083 const TargetInstrInfo
*TII
;
1084 const TargetRegisterInfo
*TRI
;
1085 TargetSchedModel SchedModel
;
1086 MachineRegisterInfo
*MRI
;
1087 MachineDominatorTree
*DomTree
;
1088 MachineBranchProbabilityInfo
*MBPI
;
1089 MachineLoopInfo
*Loops
;
1094 EarlyIfPredicator() : MachineFunctionPass(ID
) {}
1095 void getAnalysisUsage(AnalysisUsage
&AU
) const override
;
1096 bool runOnMachineFunction(MachineFunction
&MF
) override
;
1097 StringRef
getPassName() const override
{ return "Early If-predicator"; }
1100 bool tryConvertIf(MachineBasicBlock
*);
1101 bool shouldConvertIf();
1103 } // end anonymous namespace
1106 #define DEBUG_TYPE "early-if-predicator"
1108 char EarlyIfPredicator::ID
= 0;
1109 char &llvm::EarlyIfPredicatorID
= EarlyIfPredicator::ID
;
1111 INITIALIZE_PASS_BEGIN(EarlyIfPredicator
, DEBUG_TYPE
, "Early If Predicator",
1113 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
1114 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo
)
1115 INITIALIZE_PASS_END(EarlyIfPredicator
, DEBUG_TYPE
, "Early If Predicator", false,
1118 void EarlyIfPredicator::getAnalysisUsage(AnalysisUsage
&AU
) const {
1119 AU
.addRequired
<MachineBranchProbabilityInfo
>();
1120 AU
.addRequired
<MachineDominatorTree
>();
1121 AU
.addPreserved
<MachineDominatorTree
>();
1122 AU
.addRequired
<MachineLoopInfo
>();
1123 AU
.addPreserved
<MachineLoopInfo
>();
1124 MachineFunctionPass::getAnalysisUsage(AU
);
1127 /// Apply the target heuristic to decide if the transformation is profitable.
1128 bool EarlyIfPredicator::shouldConvertIf() {
1129 auto TrueProbability
= MBPI
->getEdgeProbability(IfConv
.Head
, IfConv
.TBB
);
1130 if (IfConv
.isTriangle()) {
1131 MachineBasicBlock
&IfBlock
=
1132 (IfConv
.TBB
== IfConv
.Tail
) ? *IfConv
.FBB
: *IfConv
.TBB
;
1134 unsigned ExtraPredCost
= 0;
1135 unsigned Cycles
= 0;
1136 for (MachineInstr
&I
: IfBlock
) {
1137 unsigned NumCycles
= SchedModel
.computeInstrLatency(&I
, false);
1139 Cycles
+= NumCycles
- 1;
1140 ExtraPredCost
+= TII
->getPredicationCost(I
);
1143 return TII
->isProfitableToIfCvt(IfBlock
, Cycles
, ExtraPredCost
,
1146 unsigned TExtra
= 0;
1147 unsigned FExtra
= 0;
1148 unsigned TCycle
= 0;
1149 unsigned FCycle
= 0;
1150 for (MachineInstr
&I
: *IfConv
.TBB
) {
1151 unsigned NumCycles
= SchedModel
.computeInstrLatency(&I
, false);
1153 TCycle
+= NumCycles
- 1;
1154 TExtra
+= TII
->getPredicationCost(I
);
1156 for (MachineInstr
&I
: *IfConv
.FBB
) {
1157 unsigned NumCycles
= SchedModel
.computeInstrLatency(&I
, false);
1159 FCycle
+= NumCycles
- 1;
1160 FExtra
+= TII
->getPredicationCost(I
);
1162 return TII
->isProfitableToIfCvt(*IfConv
.TBB
, TCycle
, TExtra
, *IfConv
.FBB
,
1163 FCycle
, FExtra
, TrueProbability
);
1166 /// Attempt repeated if-conversion on MBB, return true if successful.
1168 bool EarlyIfPredicator::tryConvertIf(MachineBasicBlock
*MBB
) {
1169 bool Changed
= false;
1170 while (IfConv
.canConvertIf(MBB
, /*Predicate*/ true) && shouldConvertIf()) {
1171 // If-convert MBB and update analyses.
1172 SmallVector
<MachineBasicBlock
*, 4> RemovedBlocks
;
1173 IfConv
.convertIf(RemovedBlocks
, /*Predicate*/ true);
1175 updateDomTree(DomTree
, IfConv
, RemovedBlocks
);
1176 updateLoops(Loops
, RemovedBlocks
);
1181 bool EarlyIfPredicator::runOnMachineFunction(MachineFunction
&MF
) {
1182 LLVM_DEBUG(dbgs() << "********** EARLY IF-PREDICATOR **********\n"
1183 << "********** Function: " << MF
.getName() << '\n');
1184 if (skipFunction(MF
.getFunction()))
1187 const TargetSubtargetInfo
&STI
= MF
.getSubtarget();
1188 TII
= STI
.getInstrInfo();
1189 TRI
= STI
.getRegisterInfo();
1190 MRI
= &MF
.getRegInfo();
1191 SchedModel
.init(&STI
);
1192 DomTree
= &getAnalysis
<MachineDominatorTree
>();
1193 Loops
= getAnalysisIfAvailable
<MachineLoopInfo
>();
1194 MBPI
= &getAnalysis
<MachineBranchProbabilityInfo
>();
1196 bool Changed
= false;
1197 IfConv
.runOnMachineFunction(MF
);
1199 // Visit blocks in dominator tree post-order. The post-order enables nested
1200 // if-conversion in a single pass. The tryConvertIf() function may erase
1201 // blocks, but only blocks dominated by the head block. This makes it safe to
1202 // update the dominator tree while the post-order iterator is still active.
1203 for (auto DomNode
: post_order(DomTree
))
1204 if (tryConvertIf(DomNode
->getBlock()))