1 //===- IfConversion.cpp - Machine code if conversion 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 // This file implements the machine instruction level if-conversion pass, which
10 // tries to convert conditional branches into predicated instructions.
12 //===----------------------------------------------------------------------===//
14 #include "BranchFolding.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/ScopeExit.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/SparseSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/CodeGen/LivePhysRegs.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
25 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineOperand.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/TargetInstrInfo.h"
34 #include "llvm/CodeGen/TargetLowering.h"
35 #include "llvm/CodeGen/TargetRegisterInfo.h"
36 #include "llvm/CodeGen/TargetSchedule.h"
37 #include "llvm/CodeGen/TargetSubtargetInfo.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/MC/MCRegisterInfo.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Support/BranchProbability.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/raw_ostream.h"
56 #define DEBUG_TYPE "if-converter"
58 // Hidden options for help debugging.
59 static cl::opt
<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden
);
60 static cl::opt
<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden
);
61 static cl::opt
<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden
);
62 static cl::opt
<bool> DisableSimple("disable-ifcvt-simple",
63 cl::init(false), cl::Hidden
);
64 static cl::opt
<bool> DisableSimpleF("disable-ifcvt-simple-false",
65 cl::init(false), cl::Hidden
);
66 static cl::opt
<bool> DisableTriangle("disable-ifcvt-triangle",
67 cl::init(false), cl::Hidden
);
68 static cl::opt
<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
69 cl::init(false), cl::Hidden
);
70 static cl::opt
<bool> DisableTriangleF("disable-ifcvt-triangle-false",
71 cl::init(false), cl::Hidden
);
72 static cl::opt
<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
73 cl::init(false), cl::Hidden
);
74 static cl::opt
<bool> DisableDiamond("disable-ifcvt-diamond",
75 cl::init(false), cl::Hidden
);
76 static cl::opt
<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
77 cl::init(false), cl::Hidden
);
78 static cl::opt
<bool> IfCvtBranchFold("ifcvt-branch-fold",
79 cl::init(true), cl::Hidden
);
81 STATISTIC(NumSimple
, "Number of simple if-conversions performed");
82 STATISTIC(NumSimpleFalse
, "Number of simple (F) if-conversions performed");
83 STATISTIC(NumTriangle
, "Number of triangle if-conversions performed");
84 STATISTIC(NumTriangleRev
, "Number of triangle (R) if-conversions performed");
85 STATISTIC(NumTriangleFalse
,"Number of triangle (F) if-conversions performed");
86 STATISTIC(NumTriangleFRev
, "Number of triangle (F/R) if-conversions performed");
87 STATISTIC(NumDiamonds
, "Number of diamond if-conversions performed");
88 STATISTIC(NumForkedDiamonds
, "Number of forked-diamond if-conversions performed");
89 STATISTIC(NumIfConvBBs
, "Number of if-converted blocks");
90 STATISTIC(NumDupBBs
, "Number of duplicated blocks");
91 STATISTIC(NumUnpred
, "Number of true blocks of diamonds unpredicated");
95 class IfConverter
: public MachineFunctionPass
{
97 ICNotClassfied
, // BB data valid, but not classified.
98 ICSimpleFalse
, // Same as ICSimple, but on the false path.
99 ICSimple
, // BB is entry of an one split, no rejoin sub-CFG.
100 ICTriangleFRev
, // Same as ICTriangleFalse, but false path rev condition.
101 ICTriangleRev
, // Same as ICTriangle, but true path rev condition.
102 ICTriangleFalse
, // Same as ICTriangle, but on the false path.
103 ICTriangle
, // BB is entry of a triangle sub-CFG.
104 ICDiamond
, // BB is entry of a diamond sub-CFG.
105 ICForkedDiamond
// BB is entry of an almost diamond sub-CFG, with a
106 // common tail that can be shared.
109 /// One per MachineBasicBlock, this is used to cache the result
110 /// if-conversion feasibility analysis. This includes results from
111 /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
112 /// classification, and common tail block of its successors (if it's a
113 /// diamond shape), its size, whether it's predicable, and whether any
114 /// instruction can clobber the 'would-be' predicate.
116 /// IsDone - True if BB is not to be considered for ifcvt.
117 /// IsBeingAnalyzed - True if BB is currently being analyzed.
118 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
119 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
120 /// IsBrAnalyzable - True if analyzeBranch() returns false.
121 /// HasFallThrough - True if BB may fallthrough to the following BB.
122 /// IsUnpredicable - True if BB is known to be unpredicable.
123 /// ClobbersPred - True if BB could modify predicates (e.g. has
125 /// NonPredSize - Number of non-predicated instructions.
126 /// ExtraCost - Extra cost for multi-cycle instructions.
127 /// ExtraCost2 - Some instructions are slower when predicated
128 /// BB - Corresponding MachineBasicBlock.
129 /// TrueBB / FalseBB- See analyzeBranch().
130 /// BrCond - Conditions for end of block conditional branches.
131 /// Predicate - Predicate used in the BB.
134 bool IsBeingAnalyzed
: 1;
137 bool IsBrAnalyzable
: 1;
138 bool IsBrReversible
: 1;
139 bool HasFallThrough
: 1;
140 bool IsUnpredicable
: 1;
141 bool CannotBeCopied
: 1;
142 bool ClobbersPred
: 1;
143 unsigned NonPredSize
= 0;
144 unsigned ExtraCost
= 0;
145 unsigned ExtraCost2
= 0;
146 MachineBasicBlock
*BB
= nullptr;
147 MachineBasicBlock
*TrueBB
= nullptr;
148 MachineBasicBlock
*FalseBB
= nullptr;
149 SmallVector
<MachineOperand
, 4> BrCond
;
150 SmallVector
<MachineOperand
, 4> Predicate
;
152 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
153 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
154 IsBrReversible(false), HasFallThrough(false),
155 IsUnpredicable(false), CannotBeCopied(false),
156 ClobbersPred(false) {}
159 /// Record information about pending if-conversions to attempt:
160 /// BBI - Corresponding BBInfo.
161 /// Kind - Type of block. See IfcvtKind.
162 /// NeedSubsumption - True if the to-be-predicated BB has already been
164 /// NumDups - Number of instructions that would be duplicated due
165 /// to this if-conversion. (For diamonds, the number of
166 /// identical instructions at the beginnings of both
168 /// NumDups2 - For diamonds, the number of identical instructions
169 /// at the ends of both paths.
175 bool NeedSubsumption
: 1;
176 bool TClobbersPred
: 1;
177 bool FClobbersPred
: 1;
179 IfcvtToken(BBInfo
&b
, IfcvtKind k
, bool s
, unsigned d
, unsigned d2
= 0,
180 bool tc
= false, bool fc
= false)
181 : BBI(b
), Kind(k
), NumDups(d
), NumDups2(d2
), NeedSubsumption(s
),
182 TClobbersPred(tc
), FClobbersPred(fc
) {}
185 /// Results of if-conversion feasibility analysis indexed by basic block
187 std::vector
<BBInfo
> BBAnalysis
;
188 TargetSchedModel SchedModel
;
190 const TargetLoweringBase
*TLI
;
191 const TargetInstrInfo
*TII
;
192 const TargetRegisterInfo
*TRI
;
193 const MachineBranchProbabilityInfo
*MBPI
;
194 MachineRegisterInfo
*MRI
;
201 std::function
<bool(const MachineFunction
&)> PredicateFtor
;
206 IfConverter(std::function
<bool(const MachineFunction
&)> Ftor
= nullptr)
207 : MachineFunctionPass(ID
), PredicateFtor(std::move(Ftor
)) {
208 initializeIfConverterPass(*PassRegistry::getPassRegistry());
211 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
212 AU
.addRequired
<MachineBlockFrequencyInfo
>();
213 AU
.addRequired
<MachineBranchProbabilityInfo
>();
214 MachineFunctionPass::getAnalysisUsage(AU
);
217 bool runOnMachineFunction(MachineFunction
&MF
) override
;
219 MachineFunctionProperties
getRequiredProperties() const override
{
220 return MachineFunctionProperties().set(
221 MachineFunctionProperties::Property::NoVRegs
);
225 bool reverseBranchCondition(BBInfo
&BBI
) const;
226 bool ValidSimple(BBInfo
&TrueBBI
, unsigned &Dups
,
227 BranchProbability Prediction
) const;
228 bool ValidTriangle(BBInfo
&TrueBBI
, BBInfo
&FalseBBI
,
229 bool FalseBranch
, unsigned &Dups
,
230 BranchProbability Prediction
) const;
231 bool CountDuplicatedInstructions(
232 MachineBasicBlock::iterator
&TIB
, MachineBasicBlock::iterator
&FIB
,
233 MachineBasicBlock::iterator
&TIE
, MachineBasicBlock::iterator
&FIE
,
234 unsigned &Dups1
, unsigned &Dups2
,
235 MachineBasicBlock
&TBB
, MachineBasicBlock
&FBB
,
236 bool SkipUnconditionalBranches
) const;
237 bool ValidDiamond(BBInfo
&TrueBBI
, BBInfo
&FalseBBI
,
238 unsigned &Dups1
, unsigned &Dups2
,
239 BBInfo
&TrueBBICalc
, BBInfo
&FalseBBICalc
) const;
240 bool ValidForkedDiamond(BBInfo
&TrueBBI
, BBInfo
&FalseBBI
,
241 unsigned &Dups1
, unsigned &Dups2
,
242 BBInfo
&TrueBBICalc
, BBInfo
&FalseBBICalc
) const;
243 void AnalyzeBranches(BBInfo
&BBI
);
244 void ScanInstructions(BBInfo
&BBI
,
245 MachineBasicBlock::iterator
&Begin
,
246 MachineBasicBlock::iterator
&End
,
247 bool BranchUnpredicable
= false) const;
248 bool RescanInstructions(
249 MachineBasicBlock::iterator
&TIB
, MachineBasicBlock::iterator
&FIB
,
250 MachineBasicBlock::iterator
&TIE
, MachineBasicBlock::iterator
&FIE
,
251 BBInfo
&TrueBBI
, BBInfo
&FalseBBI
) const;
252 void AnalyzeBlock(MachineBasicBlock
&MBB
,
253 std::vector
<std::unique_ptr
<IfcvtToken
>> &Tokens
);
254 bool FeasibilityAnalysis(BBInfo
&BBI
, SmallVectorImpl
<MachineOperand
> &Pred
,
255 bool isTriangle
= false, bool RevBranch
= false,
256 bool hasCommonTail
= false);
257 void AnalyzeBlocks(MachineFunction
&MF
,
258 std::vector
<std::unique_ptr
<IfcvtToken
>> &Tokens
);
259 void InvalidatePreds(MachineBasicBlock
&MBB
);
260 bool IfConvertSimple(BBInfo
&BBI
, IfcvtKind Kind
);
261 bool IfConvertTriangle(BBInfo
&BBI
, IfcvtKind Kind
);
262 bool IfConvertDiamondCommon(BBInfo
&BBI
, BBInfo
&TrueBBI
, BBInfo
&FalseBBI
,
263 unsigned NumDups1
, unsigned NumDups2
,
264 bool TClobbersPred
, bool FClobbersPred
,
265 bool RemoveBranch
, bool MergeAddEdges
);
266 bool IfConvertDiamond(BBInfo
&BBI
, IfcvtKind Kind
,
267 unsigned NumDups1
, unsigned NumDups2
,
268 bool TClobbers
, bool FClobbers
);
269 bool IfConvertForkedDiamond(BBInfo
&BBI
, IfcvtKind Kind
,
270 unsigned NumDups1
, unsigned NumDups2
,
271 bool TClobbers
, bool FClobbers
);
272 void PredicateBlock(BBInfo
&BBI
,
273 MachineBasicBlock::iterator E
,
274 SmallVectorImpl
<MachineOperand
> &Cond
,
275 SmallSet
<MCPhysReg
, 4> *LaterRedefs
= nullptr);
276 void CopyAndPredicateBlock(BBInfo
&ToBBI
, BBInfo
&FromBBI
,
277 SmallVectorImpl
<MachineOperand
> &Cond
,
278 bool IgnoreBr
= false);
279 void MergeBlocks(BBInfo
&ToBBI
, BBInfo
&FromBBI
, bool AddEdges
= true);
281 bool MeetIfcvtSizeLimit(MachineBasicBlock
&BB
,
282 unsigned Cycle
, unsigned Extra
,
283 BranchProbability Prediction
) const {
284 return Cycle
> 0 && TII
->isProfitableToIfCvt(BB
, Cycle
, Extra
,
288 bool MeetIfcvtSizeLimit(BBInfo
&TBBInfo
, BBInfo
&FBBInfo
,
289 MachineBasicBlock
&CommBB
, unsigned Dups
,
290 BranchProbability Prediction
, bool Forked
) const {
291 const MachineFunction
&MF
= *TBBInfo
.BB
->getParent();
292 if (MF
.getFunction().hasMinSize()) {
293 MachineBasicBlock::iterator TIB
= TBBInfo
.BB
->begin();
294 MachineBasicBlock::iterator FIB
= FBBInfo
.BB
->begin();
295 MachineBasicBlock::iterator TIE
= TBBInfo
.BB
->end();
296 MachineBasicBlock::iterator FIE
= FBBInfo
.BB
->end();
298 unsigned Dups1
, Dups2
;
299 if (!CountDuplicatedInstructions(TIB
, FIB
, TIE
, FIE
, Dups1
, Dups2
,
300 *TBBInfo
.BB
, *FBBInfo
.BB
,
301 /*SkipUnconditionalBranches*/ true))
302 llvm_unreachable("should already have been checked by ValidDiamond");
304 unsigned BranchBytes
= 0;
305 unsigned CommonBytes
= 0;
307 // Count common instructions at the start of the true and false blocks.
308 for (auto &I
: make_range(TBBInfo
.BB
->begin(), TIB
)) {
309 LLVM_DEBUG(dbgs() << "Common inst: " << I
);
310 CommonBytes
+= TII
->getInstSizeInBytes(I
);
312 for (auto &I
: make_range(FBBInfo
.BB
->begin(), FIB
)) {
313 LLVM_DEBUG(dbgs() << "Common inst: " << I
);
314 CommonBytes
+= TII
->getInstSizeInBytes(I
);
317 // Count instructions at the end of the true and false blocks, after
318 // the ones we plan to predicate. Analyzable branches will be removed
319 // (unless this is a forked diamond), and all other instructions are
320 // common between the two blocks.
321 for (auto &I
: make_range(TIE
, TBBInfo
.BB
->end())) {
322 if (I
.isBranch() && TBBInfo
.IsBrAnalyzable
&& !Forked
) {
323 LLVM_DEBUG(dbgs() << "Saving branch: " << I
);
324 BranchBytes
+= TII
->predictBranchSizeForIfCvt(I
);
326 LLVM_DEBUG(dbgs() << "Common inst: " << I
);
327 CommonBytes
+= TII
->getInstSizeInBytes(I
);
330 for (auto &I
: make_range(FIE
, FBBInfo
.BB
->end())) {
331 if (I
.isBranch() && FBBInfo
.IsBrAnalyzable
&& !Forked
) {
332 LLVM_DEBUG(dbgs() << "Saving branch: " << I
);
333 BranchBytes
+= TII
->predictBranchSizeForIfCvt(I
);
335 LLVM_DEBUG(dbgs() << "Common inst: " << I
);
336 CommonBytes
+= TII
->getInstSizeInBytes(I
);
339 for (auto &I
: CommBB
.terminators()) {
341 LLVM_DEBUG(dbgs() << "Saving branch: " << I
);
342 BranchBytes
+= TII
->predictBranchSizeForIfCvt(I
);
346 // The common instructions in one branch will be eliminated, halving
350 // Count the instructions which we need to predicate.
351 unsigned NumPredicatedInstructions
= 0;
352 for (auto &I
: make_range(TIB
, TIE
)) {
353 if (!I
.isDebugInstr()) {
354 LLVM_DEBUG(dbgs() << "Predicating: " << I
);
355 NumPredicatedInstructions
++;
358 for (auto &I
: make_range(FIB
, FIE
)) {
359 if (!I
.isDebugInstr()) {
360 LLVM_DEBUG(dbgs() << "Predicating: " << I
);
361 NumPredicatedInstructions
++;
365 // Even though we're optimising for size at the expense of performance,
366 // avoid creating really long predicated blocks.
367 if (NumPredicatedInstructions
> 15)
370 // Some targets (e.g. Thumb2) need to insert extra instructions to
371 // start predicated blocks.
372 unsigned ExtraPredicateBytes
= TII
->extraSizeToPredicateInstructions(
373 MF
, NumPredicatedInstructions
);
375 LLVM_DEBUG(dbgs() << "MeetIfcvtSizeLimit(BranchBytes=" << BranchBytes
376 << ", CommonBytes=" << CommonBytes
377 << ", NumPredicatedInstructions="
378 << NumPredicatedInstructions
379 << ", ExtraPredicateBytes=" << ExtraPredicateBytes
381 return (BranchBytes
+ CommonBytes
) > ExtraPredicateBytes
;
383 unsigned TCycle
= TBBInfo
.NonPredSize
+ TBBInfo
.ExtraCost
- Dups
;
384 unsigned FCycle
= FBBInfo
.NonPredSize
+ FBBInfo
.ExtraCost
- Dups
;
385 bool Res
= TCycle
> 0 && FCycle
> 0 &&
386 TII
->isProfitableToIfCvt(
387 *TBBInfo
.BB
, TCycle
, TBBInfo
.ExtraCost2
, *FBBInfo
.BB
,
388 FCycle
, FBBInfo
.ExtraCost2
, Prediction
);
389 LLVM_DEBUG(dbgs() << "MeetIfcvtSizeLimit(TCycle=" << TCycle
390 << ", FCycle=" << FCycle
391 << ", TExtra=" << TBBInfo
.ExtraCost2
<< ", FExtra="
392 << FBBInfo
.ExtraCost2
<< ") = " << Res
<< "\n");
397 /// Returns true if Block ends without a terminator.
398 bool blockAlwaysFallThrough(BBInfo
&BBI
) const {
399 return BBI
.IsBrAnalyzable
&& BBI
.TrueBB
== nullptr;
402 /// Used to sort if-conversion candidates.
403 static bool IfcvtTokenCmp(const std::unique_ptr
<IfcvtToken
> &C1
,
404 const std::unique_ptr
<IfcvtToken
> &C2
) {
405 int Incr1
= (C1
->Kind
== ICDiamond
)
406 ? -(int)(C1
->NumDups
+ C1
->NumDups2
) : (int)C1
->NumDups
;
407 int Incr2
= (C2
->Kind
== ICDiamond
)
408 ? -(int)(C2
->NumDups
+ C2
->NumDups2
) : (int)C2
->NumDups
;
411 else if (Incr1
== Incr2
) {
412 // Favors subsumption.
413 if (!C1
->NeedSubsumption
&& C2
->NeedSubsumption
)
415 else if (C1
->NeedSubsumption
== C2
->NeedSubsumption
) {
416 // Favors diamond over triangle, etc.
417 if ((unsigned)C1
->Kind
< (unsigned)C2
->Kind
)
419 else if (C1
->Kind
== C2
->Kind
)
420 return C1
->BBI
.BB
->getNumber() < C2
->BBI
.BB
->getNumber();
427 } // end anonymous namespace
429 char IfConverter::ID
= 0;
431 char &llvm::IfConverterID
= IfConverter::ID
;
433 INITIALIZE_PASS_BEGIN(IfConverter
, DEBUG_TYPE
, "If Converter", false, false)
434 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo
)
435 INITIALIZE_PASS_END(IfConverter
, DEBUG_TYPE
, "If Converter", false, false)
437 bool IfConverter::runOnMachineFunction(MachineFunction
&MF
) {
438 if (skipFunction(MF
.getFunction()) || (PredicateFtor
&& !PredicateFtor(MF
)))
441 const TargetSubtargetInfo
&ST
= MF
.getSubtarget();
442 TLI
= ST
.getTargetLowering();
443 TII
= ST
.getInstrInfo();
444 TRI
= ST
.getRegisterInfo();
445 BranchFolder::MBFIWrapper
MBFI(getAnalysis
<MachineBlockFrequencyInfo
>());
446 MBPI
= &getAnalysis
<MachineBranchProbabilityInfo
>();
447 MRI
= &MF
.getRegInfo();
448 SchedModel
.init(&ST
);
450 if (!TII
) return false;
452 PreRegAlloc
= MRI
->isSSA();
454 bool BFChange
= false;
456 // Tail merge tend to expose more if-conversion opportunities.
457 BranchFolder
BF(true, false, MBFI
, *MBPI
);
458 auto *MMIWP
= getAnalysisIfAvailable
<MachineModuleInfoWrapperPass
>();
459 BFChange
= BF
.OptimizeFunction(
460 MF
, TII
, ST
.getRegisterInfo(),
461 MMIWP
? &MMIWP
->getMMI() : nullptr);
464 LLVM_DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum
<< ") \'"
465 << MF
.getName() << "\'");
467 if (FnNum
< IfCvtFnStart
|| (IfCvtFnStop
!= -1 && FnNum
> IfCvtFnStop
)) {
468 LLVM_DEBUG(dbgs() << " skipped\n");
471 LLVM_DEBUG(dbgs() << "\n");
474 BBAnalysis
.resize(MF
.getNumBlockIDs());
476 std::vector
<std::unique_ptr
<IfcvtToken
>> Tokens
;
478 unsigned NumIfCvts
= NumSimple
+ NumSimpleFalse
+ NumTriangle
+
479 NumTriangleRev
+ NumTriangleFalse
+ NumTriangleFRev
+ NumDiamonds
;
480 while (IfCvtLimit
== -1 || (int)NumIfCvts
< IfCvtLimit
) {
481 // Do an initial analysis for each basic block and find all the potential
482 // candidates to perform if-conversion.
484 AnalyzeBlocks(MF
, Tokens
);
485 while (!Tokens
.empty()) {
486 std::unique_ptr
<IfcvtToken
> Token
= std::move(Tokens
.back());
488 BBInfo
&BBI
= Token
->BBI
;
489 IfcvtKind Kind
= Token
->Kind
;
490 unsigned NumDups
= Token
->NumDups
;
491 unsigned NumDups2
= Token
->NumDups2
;
493 // If the block has been evicted out of the queue or it has already been
494 // marked dead (due to it being predicated), then skip it.
496 BBI
.IsEnqueued
= false;
500 BBI
.IsEnqueued
= false;
504 default: llvm_unreachable("Unexpected!");
506 case ICSimpleFalse
: {
507 bool isFalse
= Kind
== ICSimpleFalse
;
508 if ((isFalse
&& DisableSimpleF
) || (!isFalse
&& DisableSimple
)) break;
509 LLVM_DEBUG(dbgs() << "Ifcvt (Simple"
510 << (Kind
== ICSimpleFalse
? " false" : "")
511 << "): " << printMBBReference(*BBI
.BB
) << " ("
512 << ((Kind
== ICSimpleFalse
) ? BBI
.FalseBB
->getNumber()
513 : BBI
.TrueBB
->getNumber())
515 RetVal
= IfConvertSimple(BBI
, Kind
);
516 LLVM_DEBUG(dbgs() << (RetVal
? "succeeded!" : "failed!") << "\n");
518 if (isFalse
) ++NumSimpleFalse
;
525 case ICTriangleFalse
:
526 case ICTriangleFRev
: {
527 bool isFalse
= Kind
== ICTriangleFalse
;
528 bool isRev
= (Kind
== ICTriangleRev
|| Kind
== ICTriangleFRev
);
529 if (DisableTriangle
&& !isFalse
&& !isRev
) break;
530 if (DisableTriangleR
&& !isFalse
&& isRev
) break;
531 if (DisableTriangleF
&& isFalse
&& !isRev
) break;
532 if (DisableTriangleFR
&& isFalse
&& isRev
) break;
533 LLVM_DEBUG(dbgs() << "Ifcvt (Triangle");
535 LLVM_DEBUG(dbgs() << " false");
537 LLVM_DEBUG(dbgs() << " rev");
538 LLVM_DEBUG(dbgs() << "): " << printMBBReference(*BBI
.BB
)
539 << " (T:" << BBI
.TrueBB
->getNumber()
540 << ",F:" << BBI
.FalseBB
->getNumber() << ") ");
541 RetVal
= IfConvertTriangle(BBI
, Kind
);
542 LLVM_DEBUG(dbgs() << (RetVal
? "succeeded!" : "failed!") << "\n");
545 if (isRev
) ++NumTriangleFRev
;
546 else ++NumTriangleFalse
;
548 if (isRev
) ++NumTriangleRev
;
555 if (DisableDiamond
) break;
556 LLVM_DEBUG(dbgs() << "Ifcvt (Diamond): " << printMBBReference(*BBI
.BB
)
557 << " (T:" << BBI
.TrueBB
->getNumber()
558 << ",F:" << BBI
.FalseBB
->getNumber() << ") ");
559 RetVal
= IfConvertDiamond(BBI
, Kind
, NumDups
, NumDups2
,
560 Token
->TClobbersPred
,
561 Token
->FClobbersPred
);
562 LLVM_DEBUG(dbgs() << (RetVal
? "succeeded!" : "failed!") << "\n");
563 if (RetVal
) ++NumDiamonds
;
565 case ICForkedDiamond
:
566 if (DisableForkedDiamond
) break;
567 LLVM_DEBUG(dbgs() << "Ifcvt (Forked Diamond): "
568 << printMBBReference(*BBI
.BB
)
569 << " (T:" << BBI
.TrueBB
->getNumber()
570 << ",F:" << BBI
.FalseBB
->getNumber() << ") ");
571 RetVal
= IfConvertForkedDiamond(BBI
, Kind
, NumDups
, NumDups2
,
572 Token
->TClobbersPred
,
573 Token
->FClobbersPred
);
574 LLVM_DEBUG(dbgs() << (RetVal
? "succeeded!" : "failed!") << "\n");
575 if (RetVal
) ++NumForkedDiamonds
;
579 if (RetVal
&& MRI
->tracksLiveness())
580 recomputeLivenessFlags(*BBI
.BB
);
584 NumIfCvts
= NumSimple
+ NumSimpleFalse
+ NumTriangle
+ NumTriangleRev
+
585 NumTriangleFalse
+ NumTriangleFRev
+ NumDiamonds
;
586 if (IfCvtLimit
!= -1 && (int)NumIfCvts
>= IfCvtLimit
)
592 MadeChange
|= Change
;
598 if (MadeChange
&& IfCvtBranchFold
) {
599 BranchFolder
BF(false, false, MBFI
, *MBPI
);
600 auto *MMIWP
= getAnalysisIfAvailable
<MachineModuleInfoWrapperPass
>();
602 MF
, TII
, MF
.getSubtarget().getRegisterInfo(),
603 MMIWP
? &MMIWP
->getMMI() : nullptr);
606 MadeChange
|= BFChange
;
610 /// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
611 static MachineBasicBlock
*findFalseBlock(MachineBasicBlock
*BB
,
612 MachineBasicBlock
*TrueBB
) {
613 for (MachineBasicBlock
*SuccBB
: BB
->successors()) {
614 if (SuccBB
!= TrueBB
)
620 /// Reverse the condition of the end of the block branch. Swap block's 'true'
621 /// and 'false' successors.
622 bool IfConverter::reverseBranchCondition(BBInfo
&BBI
) const {
623 DebugLoc dl
; // FIXME: this is nowhere
624 if (!TII
->reverseBranchCondition(BBI
.BrCond
)) {
625 TII
->removeBranch(*BBI
.BB
);
626 TII
->insertBranch(*BBI
.BB
, BBI
.FalseBB
, BBI
.TrueBB
, BBI
.BrCond
, dl
);
627 std::swap(BBI
.TrueBB
, BBI
.FalseBB
);
633 /// Returns the next block in the function blocks ordering. If it is the end,
635 static inline MachineBasicBlock
*getNextBlock(MachineBasicBlock
&MBB
) {
636 MachineFunction::iterator I
= MBB
.getIterator();
637 MachineFunction::iterator E
= MBB
.getParent()->end();
643 /// Returns true if the 'true' block (along with its predecessor) forms a valid
644 /// simple shape for ifcvt. It also returns the number of instructions that the
645 /// ifcvt would need to duplicate if performed in Dups.
646 bool IfConverter::ValidSimple(BBInfo
&TrueBBI
, unsigned &Dups
,
647 BranchProbability Prediction
) const {
649 if (TrueBBI
.IsBeingAnalyzed
|| TrueBBI
.IsDone
)
652 if (TrueBBI
.IsBrAnalyzable
)
655 if (TrueBBI
.BB
->pred_size() > 1) {
656 if (TrueBBI
.CannotBeCopied
||
657 !TII
->isProfitableToDupForIfCvt(*TrueBBI
.BB
, TrueBBI
.NonPredSize
,
660 Dups
= TrueBBI
.NonPredSize
;
666 /// Returns true if the 'true' and 'false' blocks (along with their common
667 /// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
668 /// true, it checks if 'true' block's false branch branches to the 'false' block
669 /// rather than the other way around. It also returns the number of instructions
670 /// that the ifcvt would need to duplicate if performed in 'Dups'.
671 bool IfConverter::ValidTriangle(BBInfo
&TrueBBI
, BBInfo
&FalseBBI
,
672 bool FalseBranch
, unsigned &Dups
,
673 BranchProbability Prediction
) const {
675 if (TrueBBI
.BB
== FalseBBI
.BB
)
678 if (TrueBBI
.IsBeingAnalyzed
|| TrueBBI
.IsDone
)
681 if (TrueBBI
.BB
->pred_size() > 1) {
682 if (TrueBBI
.CannotBeCopied
)
685 unsigned Size
= TrueBBI
.NonPredSize
;
686 if (TrueBBI
.IsBrAnalyzable
) {
687 if (TrueBBI
.TrueBB
&& TrueBBI
.BrCond
.empty())
688 // Ends with an unconditional branch. It will be removed.
691 MachineBasicBlock
*FExit
= FalseBranch
692 ? TrueBBI
.TrueBB
: TrueBBI
.FalseBB
;
694 // Require a conditional branch
698 if (!TII
->isProfitableToDupForIfCvt(*TrueBBI
.BB
, Size
, Prediction
))
703 MachineBasicBlock
*TExit
= FalseBranch
? TrueBBI
.FalseBB
: TrueBBI
.TrueBB
;
704 if (!TExit
&& blockAlwaysFallThrough(TrueBBI
)) {
705 MachineFunction::iterator I
= TrueBBI
.BB
->getIterator();
706 if (++I
== TrueBBI
.BB
->getParent()->end())
710 return TExit
&& TExit
== FalseBBI
.BB
;
713 /// Count duplicated instructions and move the iterators to show where they
715 /// @param TIB True Iterator Begin
716 /// @param FIB False Iterator Begin
717 /// These two iterators initially point to the first instruction of the two
718 /// blocks, and finally point to the first non-shared instruction.
719 /// @param TIE True Iterator End
720 /// @param FIE False Iterator End
721 /// These two iterators initially point to End() for the two blocks() and
722 /// finally point to the first shared instruction in the tail.
723 /// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
725 /// @param Dups1 count of duplicated instructions at the beginning of the 2
727 /// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
728 /// @param SkipUnconditionalBranches if true, Don't make sure that
729 /// unconditional branches at the end of the blocks are the same. True is
730 /// passed when the blocks are analyzable to allow for fallthrough to be
732 /// @return false if the shared portion prevents if conversion.
733 bool IfConverter::CountDuplicatedInstructions(
734 MachineBasicBlock::iterator
&TIB
,
735 MachineBasicBlock::iterator
&FIB
,
736 MachineBasicBlock::iterator
&TIE
,
737 MachineBasicBlock::iterator
&FIE
,
738 unsigned &Dups1
, unsigned &Dups2
,
739 MachineBasicBlock
&TBB
, MachineBasicBlock
&FBB
,
740 bool SkipUnconditionalBranches
) const {
741 while (TIB
!= TIE
&& FIB
!= FIE
) {
742 // Skip dbg_value instructions. These do not count.
743 TIB
= skipDebugInstructionsForward(TIB
, TIE
);
744 FIB
= skipDebugInstructionsForward(FIB
, FIE
);
745 if (TIB
== TIE
|| FIB
== FIE
)
747 if (!TIB
->isIdenticalTo(*FIB
))
749 // A pred-clobbering instruction in the shared portion prevents
751 std::vector
<MachineOperand
> PredDefs
;
752 if (TII
->DefinesPredicate(*TIB
, PredDefs
))
754 // If we get all the way to the branch instructions, don't count them.
755 if (!TIB
->isBranch())
761 // Check for already containing all of the block.
762 if (TIB
== TIE
|| FIB
== FIE
)
764 // Now, in preparation for counting duplicate instructions at the ends of the
765 // blocks, switch to reverse_iterators. Note that getReverse() returns an
766 // iterator that points to the same instruction, unlike std::reverse_iterator.
767 // We have to do our own shifting so that we get the same range.
768 MachineBasicBlock::reverse_iterator RTIE
= std::next(TIE
.getReverse());
769 MachineBasicBlock::reverse_iterator RFIE
= std::next(FIE
.getReverse());
770 const MachineBasicBlock::reverse_iterator RTIB
= std::next(TIB
.getReverse());
771 const MachineBasicBlock::reverse_iterator RFIB
= std::next(FIB
.getReverse());
773 if (!TBB
.succ_empty() || !FBB
.succ_empty()) {
774 if (SkipUnconditionalBranches
) {
775 while (RTIE
!= RTIB
&& RTIE
->isUnconditionalBranch())
777 while (RFIE
!= RFIB
&& RFIE
->isUnconditionalBranch())
782 // Count duplicate instructions at the ends of the blocks.
783 while (RTIE
!= RTIB
&& RFIE
!= RFIB
) {
784 // Skip dbg_value instructions. These do not count.
785 // Note that these are reverse iterators going forward.
786 RTIE
= skipDebugInstructionsForward(RTIE
, RTIB
);
787 RFIE
= skipDebugInstructionsForward(RFIE
, RFIB
);
788 if (RTIE
== RTIB
|| RFIE
== RFIB
)
790 if (!RTIE
->isIdenticalTo(*RFIE
))
792 // We have to verify that any branch instructions are the same, and then we
793 // don't count them toward the # of duplicate instructions.
794 if (!RTIE
->isBranch())
799 TIE
= std::next(RTIE
.getReverse());
800 FIE
= std::next(RFIE
.getReverse());
804 /// RescanInstructions - Run ScanInstructions on a pair of blocks.
805 /// @param TIB - True Iterator Begin, points to first non-shared instruction
806 /// @param FIB - False Iterator Begin, points to first non-shared instruction
807 /// @param TIE - True Iterator End, points past last non-shared instruction
808 /// @param FIE - False Iterator End, points past last non-shared instruction
809 /// @param TrueBBI - BBInfo to update for the true block.
810 /// @param FalseBBI - BBInfo to update for the false block.
811 /// @returns - false if either block cannot be predicated or if both blocks end
812 /// with a predicate-clobbering instruction.
813 bool IfConverter::RescanInstructions(
814 MachineBasicBlock::iterator
&TIB
, MachineBasicBlock::iterator
&FIB
,
815 MachineBasicBlock::iterator
&TIE
, MachineBasicBlock::iterator
&FIE
,
816 BBInfo
&TrueBBI
, BBInfo
&FalseBBI
) const {
817 bool BranchUnpredicable
= true;
818 TrueBBI
.IsUnpredicable
= FalseBBI
.IsUnpredicable
= false;
819 ScanInstructions(TrueBBI
, TIB
, TIE
, BranchUnpredicable
);
820 if (TrueBBI
.IsUnpredicable
)
822 ScanInstructions(FalseBBI
, FIB
, FIE
, BranchUnpredicable
);
823 if (FalseBBI
.IsUnpredicable
)
825 if (TrueBBI
.ClobbersPred
&& FalseBBI
.ClobbersPred
)
831 static void verifySameBranchInstructions(
832 MachineBasicBlock
*MBB1
,
833 MachineBasicBlock
*MBB2
) {
834 const MachineBasicBlock::reverse_iterator B1
= MBB1
->rend();
835 const MachineBasicBlock::reverse_iterator B2
= MBB2
->rend();
836 MachineBasicBlock::reverse_iterator E1
= MBB1
->rbegin();
837 MachineBasicBlock::reverse_iterator E2
= MBB2
->rbegin();
838 while (E1
!= B1
&& E2
!= B2
) {
839 skipDebugInstructionsForward(E1
, B1
);
840 skipDebugInstructionsForward(E2
, B2
);
841 if (E1
== B1
&& E2
== B2
)
845 assert(!E2
->isBranch() && "Branch mis-match, one block is empty.");
849 assert(!E1
->isBranch() && "Branch mis-match, one block is empty.");
853 if (E1
->isBranch() || E2
->isBranch())
854 assert(E1
->isIdenticalTo(*E2
) &&
855 "Branch mis-match, branch instructions don't match.");
864 /// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
865 /// with their common predecessor) form a diamond if a common tail block is
867 /// While not strictly a diamond, this pattern would form a diamond if
868 /// tail-merging had merged the shared tails.
874 /// FalseBB TrueBB FalseBB
875 /// Currently only handles analyzable branches.
876 /// Specifically excludes actual diamonds to avoid overlap.
877 bool IfConverter::ValidForkedDiamond(
878 BBInfo
&TrueBBI
, BBInfo
&FalseBBI
,
879 unsigned &Dups1
, unsigned &Dups2
,
880 BBInfo
&TrueBBICalc
, BBInfo
&FalseBBICalc
) const {
882 if (TrueBBI
.IsBeingAnalyzed
|| TrueBBI
.IsDone
||
883 FalseBBI
.IsBeingAnalyzed
|| FalseBBI
.IsDone
)
886 if (!TrueBBI
.IsBrAnalyzable
|| !FalseBBI
.IsBrAnalyzable
)
888 // Don't IfConvert blocks that can't be folded into their predecessor.
889 if (TrueBBI
.BB
->pred_size() > 1 || FalseBBI
.BB
->pred_size() > 1)
892 // This function is specifically looking for conditional tails, as
893 // unconditional tails are already handled by the standard diamond case.
894 if (TrueBBI
.BrCond
.size() == 0 ||
895 FalseBBI
.BrCond
.size() == 0)
898 MachineBasicBlock
*TT
= TrueBBI
.TrueBB
;
899 MachineBasicBlock
*TF
= TrueBBI
.FalseBB
;
900 MachineBasicBlock
*FT
= FalseBBI
.TrueBB
;
901 MachineBasicBlock
*FF
= FalseBBI
.FalseBB
;
904 TT
= getNextBlock(*TrueBBI
.BB
);
906 TF
= getNextBlock(*TrueBBI
.BB
);
908 FT
= getNextBlock(*FalseBBI
.BB
);
910 FF
= getNextBlock(*FalseBBI
.BB
);
915 // Check successors. If they don't match, bail.
916 if (!((TT
== FT
&& TF
== FF
) || (TF
== FT
&& TT
== FF
)))
919 bool FalseReversed
= false;
920 if (TF
== FT
&& TT
== FF
) {
921 // If the branches are opposing, but we can't reverse, don't do it.
922 if (!FalseBBI
.IsBrReversible
)
924 FalseReversed
= true;
925 reverseBranchCondition(FalseBBI
);
927 auto UnReverseOnExit
= make_scope_exit([&]() {
929 reverseBranchCondition(FalseBBI
);
932 // Count duplicate instructions at the beginning of the true and false blocks.
933 MachineBasicBlock::iterator TIB
= TrueBBI
.BB
->begin();
934 MachineBasicBlock::iterator FIB
= FalseBBI
.BB
->begin();
935 MachineBasicBlock::iterator TIE
= TrueBBI
.BB
->end();
936 MachineBasicBlock::iterator FIE
= FalseBBI
.BB
->end();
937 if(!CountDuplicatedInstructions(TIB
, FIB
, TIE
, FIE
, Dups1
, Dups2
,
938 *TrueBBI
.BB
, *FalseBBI
.BB
,
939 /* SkipUnconditionalBranches */ true))
942 TrueBBICalc
.BB
= TrueBBI
.BB
;
943 FalseBBICalc
.BB
= FalseBBI
.BB
;
944 TrueBBICalc
.IsBrAnalyzable
= TrueBBI
.IsBrAnalyzable
;
945 FalseBBICalc
.IsBrAnalyzable
= FalseBBI
.IsBrAnalyzable
;
946 if (!RescanInstructions(TIB
, FIB
, TIE
, FIE
, TrueBBICalc
, FalseBBICalc
))
949 // The size is used to decide whether to if-convert, and the shared portions
950 // are subtracted off. Because of the subtraction, we just use the size that
951 // was calculated by the original ScanInstructions, as it is correct.
952 TrueBBICalc
.NonPredSize
= TrueBBI
.NonPredSize
;
953 FalseBBICalc
.NonPredSize
= FalseBBI
.NonPredSize
;
957 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
958 /// with their common predecessor) forms a valid diamond shape for ifcvt.
959 bool IfConverter::ValidDiamond(
960 BBInfo
&TrueBBI
, BBInfo
&FalseBBI
,
961 unsigned &Dups1
, unsigned &Dups2
,
962 BBInfo
&TrueBBICalc
, BBInfo
&FalseBBICalc
) const {
964 if (TrueBBI
.IsBeingAnalyzed
|| TrueBBI
.IsDone
||
965 FalseBBI
.IsBeingAnalyzed
|| FalseBBI
.IsDone
)
968 MachineBasicBlock
*TT
= TrueBBI
.TrueBB
;
969 MachineBasicBlock
*FT
= FalseBBI
.TrueBB
;
971 if (!TT
&& blockAlwaysFallThrough(TrueBBI
))
972 TT
= getNextBlock(*TrueBBI
.BB
);
973 if (!FT
&& blockAlwaysFallThrough(FalseBBI
))
974 FT
= getNextBlock(*FalseBBI
.BB
);
977 if (!TT
&& (TrueBBI
.IsBrAnalyzable
|| FalseBBI
.IsBrAnalyzable
))
979 if (TrueBBI
.BB
->pred_size() > 1 || FalseBBI
.BB
->pred_size() > 1)
982 // FIXME: Allow true block to have an early exit?
983 if (TrueBBI
.FalseBB
|| FalseBBI
.FalseBB
)
986 // Count duplicate instructions at the beginning and end of the true and
988 // Skip unconditional branches only if we are considering an analyzable
989 // diamond. Otherwise the branches must be the same.
990 bool SkipUnconditionalBranches
=
991 TrueBBI
.IsBrAnalyzable
&& FalseBBI
.IsBrAnalyzable
;
992 MachineBasicBlock::iterator TIB
= TrueBBI
.BB
->begin();
993 MachineBasicBlock::iterator FIB
= FalseBBI
.BB
->begin();
994 MachineBasicBlock::iterator TIE
= TrueBBI
.BB
->end();
995 MachineBasicBlock::iterator FIE
= FalseBBI
.BB
->end();
996 if(!CountDuplicatedInstructions(TIB
, FIB
, TIE
, FIE
, Dups1
, Dups2
,
997 *TrueBBI
.BB
, *FalseBBI
.BB
,
998 SkipUnconditionalBranches
))
1001 TrueBBICalc
.BB
= TrueBBI
.BB
;
1002 FalseBBICalc
.BB
= FalseBBI
.BB
;
1003 TrueBBICalc
.IsBrAnalyzable
= TrueBBI
.IsBrAnalyzable
;
1004 FalseBBICalc
.IsBrAnalyzable
= FalseBBI
.IsBrAnalyzable
;
1005 if (!RescanInstructions(TIB
, FIB
, TIE
, FIE
, TrueBBICalc
, FalseBBICalc
))
1007 // The size is used to decide whether to if-convert, and the shared portions
1008 // are subtracted off. Because of the subtraction, we just use the size that
1009 // was calculated by the original ScanInstructions, as it is correct.
1010 TrueBBICalc
.NonPredSize
= TrueBBI
.NonPredSize
;
1011 FalseBBICalc
.NonPredSize
= FalseBBI
.NonPredSize
;
1015 /// AnalyzeBranches - Look at the branches at the end of a block to determine if
1016 /// the block is predicable.
1017 void IfConverter::AnalyzeBranches(BBInfo
&BBI
) {
1021 BBI
.TrueBB
= BBI
.FalseBB
= nullptr;
1023 BBI
.IsBrAnalyzable
=
1024 !TII
->analyzeBranch(*BBI
.BB
, BBI
.TrueBB
, BBI
.FalseBB
, BBI
.BrCond
);
1025 if (!BBI
.IsBrAnalyzable
) {
1026 BBI
.TrueBB
= nullptr;
1027 BBI
.FalseBB
= nullptr;
1031 SmallVector
<MachineOperand
, 4> RevCond(BBI
.BrCond
.begin(), BBI
.BrCond
.end());
1032 BBI
.IsBrReversible
= (RevCond
.size() == 0) ||
1033 !TII
->reverseBranchCondition(RevCond
);
1034 BBI
.HasFallThrough
= BBI
.IsBrAnalyzable
&& BBI
.FalseBB
== nullptr;
1036 if (BBI
.BrCond
.size()) {
1037 // No false branch. This BB must end with a conditional branch and a
1040 BBI
.FalseBB
= findFalseBlock(BBI
.BB
, BBI
.TrueBB
);
1042 // Malformed bcc? True and false blocks are the same?
1043 BBI
.IsUnpredicable
= true;
1048 /// ScanInstructions - Scan all the instructions in the block to determine if
1049 /// the block is predicable. In most cases, that means all the instructions
1050 /// in the block are isPredicable(). Also checks if the block contains any
1051 /// instruction which can clobber a predicate (e.g. condition code register).
1052 /// If so, the block is not predicable unless it's the last instruction.
1053 void IfConverter::ScanInstructions(BBInfo
&BBI
,
1054 MachineBasicBlock::iterator
&Begin
,
1055 MachineBasicBlock::iterator
&End
,
1056 bool BranchUnpredicable
) const {
1057 if (BBI
.IsDone
|| BBI
.IsUnpredicable
)
1060 bool AlreadyPredicated
= !BBI
.Predicate
.empty();
1062 BBI
.NonPredSize
= 0;
1065 BBI
.ClobbersPred
= false;
1066 for (MachineInstr
&MI
: make_range(Begin
, End
)) {
1067 if (MI
.isDebugInstr())
1070 // It's unsafe to duplicate convergent instructions in this context, so set
1071 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
1072 // following CFG, which is subject to our "simple" transformation.
1074 // BB0 // if (c1) goto BB1; else goto BB2;
1077 // | BB2 // if (c2) goto TBB; else goto FBB;
1086 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
1087 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
1088 // TBB contains a convergent instruction. This is safe iff doing so does
1089 // not add a control-flow dependency to the convergent instruction -- i.e.,
1090 // it's safe iff the set of control flows that leads us to the convergent
1091 // instruction does not get smaller after the transformation.
1093 // Originally we executed TBB if c1 || c2. After the transformation, there
1094 // are two copies of TBB's instructions. We get to the first if c1, and we
1095 // get to the second if !c1 && c2.
1097 // There are clearly fewer ways to satisfy the condition "c1" than
1098 // "c1 || c2". Since we've shrunk the set of control flows which lead to
1099 // our convergent instruction, the transformation is unsafe.
1100 if (MI
.isNotDuplicable() || MI
.isConvergent())
1101 BBI
.CannotBeCopied
= true;
1103 bool isPredicated
= TII
->isPredicated(MI
);
1104 bool isCondBr
= BBI
.IsBrAnalyzable
&& MI
.isConditionalBranch();
1106 if (BranchUnpredicable
&& MI
.isBranch()) {
1107 BBI
.IsUnpredicable
= true;
1111 // A conditional branch is not predicable, but it may be eliminated.
1115 if (!isPredicated
) {
1117 unsigned ExtraPredCost
= TII
->getPredicationCost(MI
);
1118 unsigned NumCycles
= SchedModel
.computeInstrLatency(&MI
, false);
1120 BBI
.ExtraCost
+= NumCycles
-1;
1121 BBI
.ExtraCost2
+= ExtraPredCost
;
1122 } else if (!AlreadyPredicated
) {
1123 // FIXME: This instruction is already predicated before the
1124 // if-conversion pass. It's probably something like a conditional move.
1125 // Mark this block unpredicable for now.
1126 BBI
.IsUnpredicable
= true;
1130 if (BBI
.ClobbersPred
&& !isPredicated
) {
1131 // Predicate modification instruction should end the block (except for
1132 // already predicated instructions and end of block branches).
1133 // Predicate may have been modified, the subsequent (currently)
1134 // unpredicated instructions cannot be correctly predicated.
1135 BBI
.IsUnpredicable
= true;
1139 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
1140 // still potentially predicable.
1141 std::vector
<MachineOperand
> PredDefs
;
1142 if (TII
->DefinesPredicate(MI
, PredDefs
))
1143 BBI
.ClobbersPred
= true;
1145 if (!TII
->isPredicable(MI
)) {
1146 BBI
.IsUnpredicable
= true;
1152 /// Determine if the block is a suitable candidate to be predicated by the
1153 /// specified predicate.
1154 /// @param BBI BBInfo for the block to check
1155 /// @param Pred Predicate array for the branch that leads to BBI
1156 /// @param isTriangle true if the Analysis is for a triangle
1157 /// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
1159 /// @param hasCommonTail true if BBI shares a tail with a sibling block that
1160 /// contains any instruction that would make the block unpredicable.
1161 bool IfConverter::FeasibilityAnalysis(BBInfo
&BBI
,
1162 SmallVectorImpl
<MachineOperand
> &Pred
,
1163 bool isTriangle
, bool RevBranch
,
1164 bool hasCommonTail
) {
1165 // If the block is dead or unpredicable, then it cannot be predicated.
1166 // Two blocks may share a common unpredicable tail, but this doesn't prevent
1167 // them from being if-converted. The non-shared portion is assumed to have
1169 if (BBI
.IsDone
|| (BBI
.IsUnpredicable
&& !hasCommonTail
))
1172 // If it is already predicated but we couldn't analyze its terminator, the
1173 // latter might fallthrough, but we can't determine where to.
1174 // Conservatively avoid if-converting again.
1175 if (BBI
.Predicate
.size() && !BBI
.IsBrAnalyzable
)
1178 // If it is already predicated, check if the new predicate subsumes
1180 if (BBI
.Predicate
.size() && !TII
->SubsumesPredicate(Pred
, BBI
.Predicate
))
1183 if (!hasCommonTail
&& BBI
.BrCond
.size()) {
1187 // Test predicate subsumption.
1188 SmallVector
<MachineOperand
, 4> RevPred(Pred
.begin(), Pred
.end());
1189 SmallVector
<MachineOperand
, 4> Cond(BBI
.BrCond
.begin(), BBI
.BrCond
.end());
1191 if (TII
->reverseBranchCondition(Cond
))
1194 if (TII
->reverseBranchCondition(RevPred
) ||
1195 !TII
->SubsumesPredicate(Cond
, RevPred
))
1202 /// Analyze the structure of the sub-CFG starting from the specified block.
1203 /// Record its successors and whether it looks like an if-conversion candidate.
1204 void IfConverter::AnalyzeBlock(
1205 MachineBasicBlock
&MBB
, std::vector
<std::unique_ptr
<IfcvtToken
>> &Tokens
) {
1207 BBState(MachineBasicBlock
&MBB
) : MBB(&MBB
), SuccsAnalyzed(false) {}
1208 MachineBasicBlock
*MBB
;
1210 /// This flag is true if MBB's successors have been analyzed.
1214 // Push MBB to the stack.
1215 SmallVector
<BBState
, 16> BBStack(1, MBB
);
1217 while (!BBStack
.empty()) {
1218 BBState
&State
= BBStack
.back();
1219 MachineBasicBlock
*BB
= State
.MBB
;
1220 BBInfo
&BBI
= BBAnalysis
[BB
->getNumber()];
1222 if (!State
.SuccsAnalyzed
) {
1223 if (BBI
.IsAnalyzed
|| BBI
.IsBeingAnalyzed
) {
1229 BBI
.IsBeingAnalyzed
= true;
1231 AnalyzeBranches(BBI
);
1232 MachineBasicBlock::iterator Begin
= BBI
.BB
->begin();
1233 MachineBasicBlock::iterator End
= BBI
.BB
->end();
1234 ScanInstructions(BBI
, Begin
, End
);
1236 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1237 // not considered for ifcvt anymore.
1238 if (!BBI
.IsBrAnalyzable
|| BBI
.BrCond
.empty() || BBI
.IsDone
) {
1239 BBI
.IsBeingAnalyzed
= false;
1240 BBI
.IsAnalyzed
= true;
1245 // Do not ifcvt if either path is a back edge to the entry block.
1246 if (BBI
.TrueBB
== BB
|| BBI
.FalseBB
== BB
) {
1247 BBI
.IsBeingAnalyzed
= false;
1248 BBI
.IsAnalyzed
= true;
1253 // Do not ifcvt if true and false fallthrough blocks are the same.
1255 BBI
.IsBeingAnalyzed
= false;
1256 BBI
.IsAnalyzed
= true;
1261 // Push the False and True blocks to the stack.
1262 State
.SuccsAnalyzed
= true;
1263 BBStack
.push_back(*BBI
.FalseBB
);
1264 BBStack
.push_back(*BBI
.TrueBB
);
1268 BBInfo
&TrueBBI
= BBAnalysis
[BBI
.TrueBB
->getNumber()];
1269 BBInfo
&FalseBBI
= BBAnalysis
[BBI
.FalseBB
->getNumber()];
1271 if (TrueBBI
.IsDone
&& FalseBBI
.IsDone
) {
1272 BBI
.IsBeingAnalyzed
= false;
1273 BBI
.IsAnalyzed
= true;
1278 SmallVector
<MachineOperand
, 4>
1279 RevCond(BBI
.BrCond
.begin(), BBI
.BrCond
.end());
1280 bool CanRevCond
= !TII
->reverseBranchCondition(RevCond
);
1284 bool TNeedSub
= !TrueBBI
.Predicate
.empty();
1285 bool FNeedSub
= !FalseBBI
.Predicate
.empty();
1286 bool Enqueued
= false;
1288 BranchProbability Prediction
= MBPI
->getEdgeProbability(BB
, TrueBBI
.BB
);
1291 BBInfo TrueBBICalc
, FalseBBICalc
;
1292 auto feasibleDiamond
= [&](bool Forked
) {
1293 bool MeetsSize
= MeetIfcvtSizeLimit(TrueBBICalc
, FalseBBICalc
, *BB
,
1294 Dups
+ Dups2
, Prediction
, Forked
);
1295 bool TrueFeasible
= FeasibilityAnalysis(TrueBBI
, BBI
.BrCond
,
1296 /* IsTriangle */ false, /* RevCond */ false,
1297 /* hasCommonTail */ true);
1298 bool FalseFeasible
= FeasibilityAnalysis(FalseBBI
, RevCond
,
1299 /* IsTriangle */ false, /* RevCond */ false,
1300 /* hasCommonTail */ true);
1301 return MeetsSize
&& TrueFeasible
&& FalseFeasible
;
1304 if (ValidDiamond(TrueBBI
, FalseBBI
, Dups
, Dups2
,
1305 TrueBBICalc
, FalseBBICalc
)) {
1306 if (feasibleDiamond(false)) {
1314 // Note TailBB can be empty.
1315 Tokens
.push_back(std::make_unique
<IfcvtToken
>(
1316 BBI
, ICDiamond
, TNeedSub
| FNeedSub
, Dups
, Dups2
,
1317 (bool) TrueBBICalc
.ClobbersPred
, (bool) FalseBBICalc
.ClobbersPred
));
1320 } else if (ValidForkedDiamond(TrueBBI
, FalseBBI
, Dups
, Dups2
,
1321 TrueBBICalc
, FalseBBICalc
)) {
1322 if (feasibleDiamond(true)) {
1324 // if TBB and FBB have a common tail that includes their conditional
1325 // branch instructions, then we can If Convert this pattern.
1331 // FalseBB TrueBB FalseBB
1333 Tokens
.push_back(std::make_unique
<IfcvtToken
>(
1334 BBI
, ICForkedDiamond
, TNeedSub
| FNeedSub
, Dups
, Dups2
,
1335 (bool) TrueBBICalc
.ClobbersPred
, (bool) FalseBBICalc
.ClobbersPred
));
1341 if (ValidTriangle(TrueBBI
, FalseBBI
, false, Dups
, Prediction
) &&
1342 MeetIfcvtSizeLimit(*TrueBBI
.BB
, TrueBBI
.NonPredSize
+ TrueBBI
.ExtraCost
,
1343 TrueBBI
.ExtraCost2
, Prediction
) &&
1344 FeasibilityAnalysis(TrueBBI
, BBI
.BrCond
, true)) {
1353 std::make_unique
<IfcvtToken
>(BBI
, ICTriangle
, TNeedSub
, Dups
));
1357 if (ValidTriangle(TrueBBI
, FalseBBI
, true, Dups
, Prediction
) &&
1358 MeetIfcvtSizeLimit(*TrueBBI
.BB
, TrueBBI
.NonPredSize
+ TrueBBI
.ExtraCost
,
1359 TrueBBI
.ExtraCost2
, Prediction
) &&
1360 FeasibilityAnalysis(TrueBBI
, BBI
.BrCond
, true, true)) {
1362 std::make_unique
<IfcvtToken
>(BBI
, ICTriangleRev
, TNeedSub
, Dups
));
1366 if (ValidSimple(TrueBBI
, Dups
, Prediction
) &&
1367 MeetIfcvtSizeLimit(*TrueBBI
.BB
, TrueBBI
.NonPredSize
+ TrueBBI
.ExtraCost
,
1368 TrueBBI
.ExtraCost2
, Prediction
) &&
1369 FeasibilityAnalysis(TrueBBI
, BBI
.BrCond
)) {
1370 // Simple (split, no rejoin):
1378 std::make_unique
<IfcvtToken
>(BBI
, ICSimple
, TNeedSub
, Dups
));
1383 // Try the other path...
1384 if (ValidTriangle(FalseBBI
, TrueBBI
, false, Dups
,
1385 Prediction
.getCompl()) &&
1386 MeetIfcvtSizeLimit(*FalseBBI
.BB
,
1387 FalseBBI
.NonPredSize
+ FalseBBI
.ExtraCost
,
1388 FalseBBI
.ExtraCost2
, Prediction
.getCompl()) &&
1389 FeasibilityAnalysis(FalseBBI
, RevCond
, true)) {
1390 Tokens
.push_back(std::make_unique
<IfcvtToken
>(BBI
, ICTriangleFalse
,
1395 if (ValidTriangle(FalseBBI
, TrueBBI
, true, Dups
,
1396 Prediction
.getCompl()) &&
1397 MeetIfcvtSizeLimit(*FalseBBI
.BB
,
1398 FalseBBI
.NonPredSize
+ FalseBBI
.ExtraCost
,
1399 FalseBBI
.ExtraCost2
, Prediction
.getCompl()) &&
1400 FeasibilityAnalysis(FalseBBI
, RevCond
, true, true)) {
1402 std::make_unique
<IfcvtToken
>(BBI
, ICTriangleFRev
, FNeedSub
, Dups
));
1406 if (ValidSimple(FalseBBI
, Dups
, Prediction
.getCompl()) &&
1407 MeetIfcvtSizeLimit(*FalseBBI
.BB
,
1408 FalseBBI
.NonPredSize
+ FalseBBI
.ExtraCost
,
1409 FalseBBI
.ExtraCost2
, Prediction
.getCompl()) &&
1410 FeasibilityAnalysis(FalseBBI
, RevCond
)) {
1412 std::make_unique
<IfcvtToken
>(BBI
, ICSimpleFalse
, FNeedSub
, Dups
));
1417 BBI
.IsEnqueued
= Enqueued
;
1418 BBI
.IsBeingAnalyzed
= false;
1419 BBI
.IsAnalyzed
= true;
1424 /// Analyze all blocks and find entries for all if-conversion candidates.
1425 void IfConverter::AnalyzeBlocks(
1426 MachineFunction
&MF
, std::vector
<std::unique_ptr
<IfcvtToken
>> &Tokens
) {
1427 for (MachineBasicBlock
&MBB
: MF
)
1428 AnalyzeBlock(MBB
, Tokens
);
1430 // Sort to favor more complex ifcvt scheme.
1431 llvm::stable_sort(Tokens
, IfcvtTokenCmp
);
1434 /// Returns true either if ToMBB is the next block after MBB or that all the
1435 /// intervening blocks are empty (given MBB can fall through to its next block).
1436 static bool canFallThroughTo(MachineBasicBlock
&MBB
, MachineBasicBlock
&ToMBB
) {
1437 MachineFunction::iterator PI
= MBB
.getIterator();
1438 MachineFunction::iterator I
= std::next(PI
);
1439 MachineFunction::iterator TI
= ToMBB
.getIterator();
1440 MachineFunction::iterator E
= MBB
.getParent()->end();
1442 // Check isSuccessor to avoid case where the next block is empty, but
1443 // it's not a successor.
1444 if (I
== E
|| !I
->empty() || !PI
->isSuccessor(&*I
))
1448 // Finally see if the last I is indeed a successor to PI.
1449 return PI
->isSuccessor(&*I
);
1452 /// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1453 /// can be if-converted. If predecessor is already enqueued, dequeue it!
1454 void IfConverter::InvalidatePreds(MachineBasicBlock
&MBB
) {
1455 for (const MachineBasicBlock
*Predecessor
: MBB
.predecessors()) {
1456 BBInfo
&PBBI
= BBAnalysis
[Predecessor
->getNumber()];
1457 if (PBBI
.IsDone
|| PBBI
.BB
== &MBB
)
1459 PBBI
.IsAnalyzed
= false;
1460 PBBI
.IsEnqueued
= false;
1464 /// Inserts an unconditional branch from \p MBB to \p ToMBB.
1465 static void InsertUncondBranch(MachineBasicBlock
&MBB
, MachineBasicBlock
&ToMBB
,
1466 const TargetInstrInfo
*TII
) {
1467 DebugLoc dl
; // FIXME: this is nowhere
1468 SmallVector
<MachineOperand
, 0> NoCond
;
1469 TII
->insertBranch(MBB
, &ToMBB
, nullptr, NoCond
, dl
);
1472 /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1473 /// values defined in MI which are also live/used by MI.
1474 static void UpdatePredRedefs(MachineInstr
&MI
, LivePhysRegs
&Redefs
) {
1475 const TargetRegisterInfo
*TRI
= MI
.getMF()->getSubtarget().getRegisterInfo();
1477 // Before stepping forward past MI, remember which regs were live
1478 // before MI. This is needed to set the Undef flag only when reg is
1480 SparseSet
<MCPhysReg
, identity
<MCPhysReg
>> LiveBeforeMI
;
1481 LiveBeforeMI
.setUniverse(TRI
->getNumRegs());
1482 for (unsigned Reg
: Redefs
)
1483 LiveBeforeMI
.insert(Reg
);
1485 SmallVector
<std::pair
<MCPhysReg
, const MachineOperand
*>, 4> Clobbers
;
1486 Redefs
.stepForward(MI
, Clobbers
);
1488 // Now add the implicit uses for each of the clobbered values.
1489 for (auto Clobber
: Clobbers
) {
1490 // FIXME: Const cast here is nasty, but better than making StepForward
1491 // take a mutable instruction instead of const.
1492 unsigned Reg
= Clobber
.first
;
1493 MachineOperand
&Op
= const_cast<MachineOperand
&>(*Clobber
.second
);
1494 MachineInstr
*OpMI
= Op
.getParent();
1495 MachineInstrBuilder
MIB(*OpMI
->getMF(), OpMI
);
1496 if (Op
.isRegMask()) {
1497 // First handle regmasks. They clobber any entries in the mask which
1498 // means that we need a def for those registers.
1499 if (LiveBeforeMI
.count(Reg
))
1500 MIB
.addReg(Reg
, RegState::Implicit
);
1502 // We also need to add an implicit def of this register for the later
1503 // use to read from.
1504 // For the register allocator to have allocated a register clobbered
1505 // by the call which is used later, it must be the case that
1506 // the call doesn't return.
1507 MIB
.addReg(Reg
, RegState::Implicit
| RegState::Define
);
1510 if (LiveBeforeMI
.count(Reg
))
1511 MIB
.addReg(Reg
, RegState::Implicit
);
1513 bool HasLiveSubReg
= false;
1514 for (MCSubRegIterator
S(Reg
, TRI
); S
.isValid(); ++S
) {
1515 if (!LiveBeforeMI
.count(*S
))
1517 HasLiveSubReg
= true;
1521 MIB
.addReg(Reg
, RegState::Implicit
);
1526 /// If convert a simple (split, no rejoin) sub-CFG.
1527 bool IfConverter::IfConvertSimple(BBInfo
&BBI
, IfcvtKind Kind
) {
1528 BBInfo
&TrueBBI
= BBAnalysis
[BBI
.TrueBB
->getNumber()];
1529 BBInfo
&FalseBBI
= BBAnalysis
[BBI
.FalseBB
->getNumber()];
1530 BBInfo
*CvtBBI
= &TrueBBI
;
1531 BBInfo
*NextBBI
= &FalseBBI
;
1533 SmallVector
<MachineOperand
, 4> Cond(BBI
.BrCond
.begin(), BBI
.BrCond
.end());
1534 if (Kind
== ICSimpleFalse
)
1535 std::swap(CvtBBI
, NextBBI
);
1537 MachineBasicBlock
&CvtMBB
= *CvtBBI
->BB
;
1538 MachineBasicBlock
&NextMBB
= *NextBBI
->BB
;
1539 if (CvtBBI
->IsDone
||
1540 (CvtBBI
->CannotBeCopied
&& CvtMBB
.pred_size() > 1)) {
1541 // Something has changed. It's no longer safe to predicate this block.
1542 BBI
.IsAnalyzed
= false;
1543 CvtBBI
->IsAnalyzed
= false;
1547 if (CvtMBB
.hasAddressTaken())
1548 // Conservatively abort if-conversion if BB's address is taken.
1551 if (Kind
== ICSimpleFalse
)
1552 if (TII
->reverseBranchCondition(Cond
))
1553 llvm_unreachable("Unable to reverse branch condition!");
1557 if (MRI
->tracksLiveness()) {
1558 // Initialize liveins to the first BB. These are potentially redefined by
1559 // predicated instructions.
1560 Redefs
.addLiveIns(CvtMBB
);
1561 Redefs
.addLiveIns(NextMBB
);
1564 // Remove the branches from the entry so we can add the contents of the true
1566 BBI
.NonPredSize
-= TII
->removeBranch(*BBI
.BB
);
1568 if (CvtMBB
.pred_size() > 1) {
1569 // Copy instructions in the true block, predicate them, and add them to
1571 CopyAndPredicateBlock(BBI
, *CvtBBI
, Cond
);
1573 // Keep the CFG updated.
1574 BBI
.BB
->removeSuccessor(&CvtMBB
, true);
1576 // Predicate the instructions in the true block.
1577 PredicateBlock(*CvtBBI
, CvtMBB
.end(), Cond
);
1579 // Merge converted block into entry block. The BB to Cvt edge is removed
1581 MergeBlocks(BBI
, *CvtBBI
);
1584 bool IterIfcvt
= true;
1585 if (!canFallThroughTo(*BBI
.BB
, NextMBB
)) {
1586 InsertUncondBranch(*BBI
.BB
, NextMBB
, TII
);
1587 BBI
.HasFallThrough
= false;
1588 // Now ifcvt'd block will look like this:
1595 // We cannot further ifcvt this block because the unconditional branch
1596 // will have to be predicated on the new condition, that will not be
1597 // available if cmp executes.
1601 // Update block info. BB can be iteratively if-converted.
1604 InvalidatePreds(*BBI
.BB
);
1605 CvtBBI
->IsDone
= true;
1607 // FIXME: Must maintain LiveIns.
1611 /// If convert a triangle sub-CFG.
1612 bool IfConverter::IfConvertTriangle(BBInfo
&BBI
, IfcvtKind Kind
) {
1613 BBInfo
&TrueBBI
= BBAnalysis
[BBI
.TrueBB
->getNumber()];
1614 BBInfo
&FalseBBI
= BBAnalysis
[BBI
.FalseBB
->getNumber()];
1615 BBInfo
*CvtBBI
= &TrueBBI
;
1616 BBInfo
*NextBBI
= &FalseBBI
;
1617 DebugLoc dl
; // FIXME: this is nowhere
1619 SmallVector
<MachineOperand
, 4> Cond(BBI
.BrCond
.begin(), BBI
.BrCond
.end());
1620 if (Kind
== ICTriangleFalse
|| Kind
== ICTriangleFRev
)
1621 std::swap(CvtBBI
, NextBBI
);
1623 MachineBasicBlock
&CvtMBB
= *CvtBBI
->BB
;
1624 MachineBasicBlock
&NextMBB
= *NextBBI
->BB
;
1625 if (CvtBBI
->IsDone
||
1626 (CvtBBI
->CannotBeCopied
&& CvtMBB
.pred_size() > 1)) {
1627 // Something has changed. It's no longer safe to predicate this block.
1628 BBI
.IsAnalyzed
= false;
1629 CvtBBI
->IsAnalyzed
= false;
1633 if (CvtMBB
.hasAddressTaken())
1634 // Conservatively abort if-conversion if BB's address is taken.
1637 if (Kind
== ICTriangleFalse
|| Kind
== ICTriangleFRev
)
1638 if (TII
->reverseBranchCondition(Cond
))
1639 llvm_unreachable("Unable to reverse branch condition!");
1641 if (Kind
== ICTriangleRev
|| Kind
== ICTriangleFRev
) {
1642 if (reverseBranchCondition(*CvtBBI
)) {
1643 // BB has been changed, modify its predecessors (except for this
1644 // one) so they don't get ifcvt'ed based on bad intel.
1645 for (MachineBasicBlock
*PBB
: CvtMBB
.predecessors()) {
1648 BBInfo
&PBBI
= BBAnalysis
[PBB
->getNumber()];
1649 if (PBBI
.IsEnqueued
) {
1650 PBBI
.IsAnalyzed
= false;
1651 PBBI
.IsEnqueued
= false;
1657 // Initialize liveins to the first BB. These are potentially redefined by
1658 // predicated instructions.
1660 if (MRI
->tracksLiveness()) {
1661 Redefs
.addLiveIns(CvtMBB
);
1662 Redefs
.addLiveIns(NextMBB
);
1665 bool HasEarlyExit
= CvtBBI
->FalseBB
!= nullptr;
1666 BranchProbability CvtNext
, CvtFalse
, BBNext
, BBCvt
;
1669 // Get probabilities before modifying CvtMBB and BBI.BB.
1670 CvtNext
= MBPI
->getEdgeProbability(&CvtMBB
, &NextMBB
);
1671 CvtFalse
= MBPI
->getEdgeProbability(&CvtMBB
, CvtBBI
->FalseBB
);
1672 BBNext
= MBPI
->getEdgeProbability(BBI
.BB
, &NextMBB
);
1673 BBCvt
= MBPI
->getEdgeProbability(BBI
.BB
, &CvtMBB
);
1676 // Remove the branches from the entry so we can add the contents of the true
1678 BBI
.NonPredSize
-= TII
->removeBranch(*BBI
.BB
);
1680 if (CvtMBB
.pred_size() > 1) {
1681 // Copy instructions in the true block, predicate them, and add them to
1683 CopyAndPredicateBlock(BBI
, *CvtBBI
, Cond
, true);
1685 // Predicate the 'true' block after removing its branch.
1686 CvtBBI
->NonPredSize
-= TII
->removeBranch(CvtMBB
);
1687 PredicateBlock(*CvtBBI
, CvtMBB
.end(), Cond
);
1689 // Now merge the entry of the triangle with the true block.
1690 MergeBlocks(BBI
, *CvtBBI
, false);
1693 // Keep the CFG updated.
1694 BBI
.BB
->removeSuccessor(&CvtMBB
, true);
1696 // If 'true' block has a 'false' successor, add an exit branch to it.
1698 SmallVector
<MachineOperand
, 4> RevCond(CvtBBI
->BrCond
.begin(),
1699 CvtBBI
->BrCond
.end());
1700 if (TII
->reverseBranchCondition(RevCond
))
1701 llvm_unreachable("Unable to reverse branch condition!");
1703 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1704 // NewNext = New_Prob(BBI.BB, NextMBB) =
1705 // Prob(BBI.BB, NextMBB) +
1706 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
1707 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1708 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1709 auto NewTrueBB
= getNextBlock(*BBI
.BB
);
1710 auto NewNext
= BBNext
+ BBCvt
* CvtNext
;
1711 auto NewTrueBBIter
= find(BBI
.BB
->successors(), NewTrueBB
);
1712 if (NewTrueBBIter
!= BBI
.BB
->succ_end())
1713 BBI
.BB
->setSuccProbability(NewTrueBBIter
, NewNext
);
1715 auto NewFalse
= BBCvt
* CvtFalse
;
1716 TII
->insertBranch(*BBI
.BB
, CvtBBI
->FalseBB
, nullptr, RevCond
, dl
);
1717 BBI
.BB
->addSuccessor(CvtBBI
->FalseBB
, NewFalse
);
1720 // Merge in the 'false' block if the 'false' block has no other
1721 // predecessors. Otherwise, add an unconditional branch to 'false'.
1722 bool FalseBBDead
= false;
1723 bool IterIfcvt
= true;
1724 bool isFallThrough
= canFallThroughTo(*BBI
.BB
, NextMBB
);
1725 if (!isFallThrough
) {
1726 // Only merge them if the true block does not fallthrough to the false
1727 // block. By not merging them, we make it possible to iteratively
1728 // ifcvt the blocks.
1729 if (!HasEarlyExit
&&
1730 NextMBB
.pred_size() == 1 && !NextBBI
->HasFallThrough
&&
1731 !NextMBB
.hasAddressTaken()) {
1732 MergeBlocks(BBI
, *NextBBI
);
1735 InsertUncondBranch(*BBI
.BB
, NextMBB
, TII
);
1736 BBI
.HasFallThrough
= false;
1738 // Mixed predicated and unpredicated code. This cannot be iteratively
1743 // Update block info. BB can be iteratively if-converted.
1746 InvalidatePreds(*BBI
.BB
);
1747 CvtBBI
->IsDone
= true;
1749 NextBBI
->IsDone
= true;
1751 // FIXME: Must maintain LiveIns.
1755 /// Common code shared between diamond conversions.
1756 /// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
1757 /// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
1759 /// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
1761 /// \p RemoveBranch - Remove the common branch of the two blocks before
1762 /// predicating. Only false for unanalyzable fallthrough
1763 /// cases. The caller will replace the branch if necessary.
1764 /// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
1765 /// unanalyzable fallthrough
1766 bool IfConverter::IfConvertDiamondCommon(
1767 BBInfo
&BBI
, BBInfo
&TrueBBI
, BBInfo
&FalseBBI
,
1768 unsigned NumDups1
, unsigned NumDups2
,
1769 bool TClobbersPred
, bool FClobbersPred
,
1770 bool RemoveBranch
, bool MergeAddEdges
) {
1772 if (TrueBBI
.IsDone
|| FalseBBI
.IsDone
||
1773 TrueBBI
.BB
->pred_size() > 1 || FalseBBI
.BB
->pred_size() > 1) {
1774 // Something has changed. It's no longer safe to predicate these blocks.
1775 BBI
.IsAnalyzed
= false;
1776 TrueBBI
.IsAnalyzed
= false;
1777 FalseBBI
.IsAnalyzed
= false;
1781 if (TrueBBI
.BB
->hasAddressTaken() || FalseBBI
.BB
->hasAddressTaken())
1782 // Conservatively abort if-conversion if either BB has its address taken.
1785 // Put the predicated instructions from the 'true' block before the
1786 // instructions from the 'false' block, unless the true block would clobber
1787 // the predicate, in which case, do the opposite.
1788 BBInfo
*BBI1
= &TrueBBI
;
1789 BBInfo
*BBI2
= &FalseBBI
;
1790 SmallVector
<MachineOperand
, 4> RevCond(BBI
.BrCond
.begin(), BBI
.BrCond
.end());
1791 if (TII
->reverseBranchCondition(RevCond
))
1792 llvm_unreachable("Unable to reverse branch condition!");
1793 SmallVector
<MachineOperand
, 4> *Cond1
= &BBI
.BrCond
;
1794 SmallVector
<MachineOperand
, 4> *Cond2
= &RevCond
;
1796 // Figure out the more profitable ordering.
1797 bool DoSwap
= false;
1798 if (TClobbersPred
&& !FClobbersPred
)
1800 else if (!TClobbersPred
&& !FClobbersPred
) {
1801 if (TrueBBI
.NonPredSize
> FalseBBI
.NonPredSize
)
1803 } else if (TClobbersPred
&& FClobbersPred
)
1804 llvm_unreachable("Predicate info cannot be clobbered by both sides.");
1806 std::swap(BBI1
, BBI2
);
1807 std::swap(Cond1
, Cond2
);
1810 // Remove the conditional branch from entry to the blocks.
1811 BBI
.NonPredSize
-= TII
->removeBranch(*BBI
.BB
);
1813 MachineBasicBlock
&MBB1
= *BBI1
->BB
;
1814 MachineBasicBlock
&MBB2
= *BBI2
->BB
;
1816 // Initialize the Redefs:
1817 // - BB2 live-in regs need implicit uses before being redefined by BB1
1819 // - BB1 live-out regs need implicit uses before being redefined by BB2
1820 // instructions. We start with BB1 live-ins so we have the live-out regs
1821 // after tracking the BB1 instructions.
1823 if (MRI
->tracksLiveness()) {
1824 Redefs
.addLiveIns(MBB1
);
1825 Redefs
.addLiveIns(MBB2
);
1828 // Remove the duplicated instructions at the beginnings of both paths.
1829 // Skip dbg_value instructions.
1830 MachineBasicBlock::iterator DI1
= MBB1
.getFirstNonDebugInstr();
1831 MachineBasicBlock::iterator DI2
= MBB2
.getFirstNonDebugInstr();
1832 BBI1
->NonPredSize
-= NumDups1
;
1833 BBI2
->NonPredSize
-= NumDups1
;
1835 // Skip past the dups on each side separately since there may be
1836 // differing dbg_value entries. NumDups1 can include a "return"
1837 // instruction, if it's not marked as "branch".
1838 for (unsigned i
= 0; i
< NumDups1
; ++DI1
) {
1839 if (DI1
== MBB1
.end())
1841 if (!DI1
->isDebugInstr())
1844 while (NumDups1
!= 0) {
1845 // Since this instruction is going to be deleted, update call
1846 // site info state if the instruction is call instruction.
1847 if (DI2
->isCall(MachineInstr::IgnoreBundle
))
1848 MBB2
.getParent()->eraseCallSiteInfo(&*DI2
);
1851 if (DI2
== MBB2
.end())
1853 if (!DI2
->isDebugInstr())
1857 if (MRI
->tracksLiveness()) {
1858 for (const MachineInstr
&MI
: make_range(MBB1
.begin(), DI1
)) {
1859 SmallVector
<std::pair
<MCPhysReg
, const MachineOperand
*>, 4> Dummy
;
1860 Redefs
.stepForward(MI
, Dummy
);
1864 BBI
.BB
->splice(BBI
.BB
->end(), &MBB1
, MBB1
.begin(), DI1
);
1865 MBB2
.erase(MBB2
.begin(), DI2
);
1867 // The branches have been checked to match, so it is safe to remove the
1868 // branch in BB1 and rely on the copy in BB2. The complication is that
1869 // the blocks may end with a return instruction, which may or may not
1870 // be marked as "branch". If it's not, then it could be included in
1871 // "dups1", leaving the blocks potentially empty after moving the common
1874 // Unanalyzable branches must match exactly. Check that now.
1875 if (!BBI1
->IsBrAnalyzable
)
1876 verifySameBranchInstructions(&MBB1
, &MBB2
);
1878 // Remove duplicated instructions from the tail of MBB1: any branch
1879 // instructions, and the common instructions counted by NumDups2.
1881 while (DI1
!= MBB1
.begin()) {
1882 MachineBasicBlock::iterator Prev
= std::prev(DI1
);
1883 if (!Prev
->isBranch() && !Prev
->isDebugInstr())
1887 for (unsigned i
= 0; i
!= NumDups2
; ) {
1888 // NumDups2 only counted non-dbg_value instructions, so this won't
1889 // run off the head of the list.
1890 assert(DI1
!= MBB1
.begin());
1894 // Since this instruction is going to be deleted, update call
1895 // site info state if the instruction is call instruction.
1896 if (DI1
->isCall(MachineInstr::IgnoreBundle
))
1897 MBB1
.getParent()->eraseCallSiteInfo(&*DI1
);
1899 // skip dbg_value instructions
1900 if (!DI1
->isDebugInstr())
1903 MBB1
.erase(DI1
, MBB1
.end());
1905 DI2
= BBI2
->BB
->end();
1906 // The branches have been checked to match. Skip over the branch in the false
1907 // block so that we don't try to predicate it.
1909 BBI2
->NonPredSize
-= TII
->removeBranch(*BBI2
->BB
);
1911 // Make DI2 point to the end of the range where the common "tail"
1912 // instructions could be found.
1913 while (DI2
!= MBB2
.begin()) {
1914 MachineBasicBlock::iterator Prev
= std::prev(DI2
);
1915 if (!Prev
->isBranch() && !Prev
->isDebugInstr())
1920 while (NumDups2
!= 0) {
1921 // NumDups2 only counted non-dbg_value instructions, so this won't
1922 // run off the head of the list.
1923 assert(DI2
!= MBB2
.begin());
1925 // skip dbg_value instructions
1926 if (!DI2
->isDebugInstr())
1930 // Remember which registers would later be defined by the false block.
1931 // This allows us not to predicate instructions in the true block that would
1932 // later be re-defined. That is, rather than
1938 SmallSet
<MCPhysReg
, 4> RedefsByFalse
;
1939 SmallSet
<MCPhysReg
, 4> ExtUses
;
1940 if (TII
->isProfitableToUnpredicate(MBB1
, MBB2
)) {
1941 for (const MachineInstr
&FI
: make_range(MBB2
.begin(), DI2
)) {
1942 if (FI
.isDebugInstr())
1944 SmallVector
<MCPhysReg
, 4> Defs
;
1945 for (const MachineOperand
&MO
: FI
.operands()) {
1948 Register Reg
= MO
.getReg();
1952 Defs
.push_back(Reg
);
1953 } else if (!RedefsByFalse
.count(Reg
)) {
1954 // These are defined before ctrl flow reach the 'false' instructions.
1955 // They cannot be modified by the 'true' instructions.
1956 for (MCSubRegIterator
SubRegs(Reg
, TRI
, /*IncludeSelf=*/true);
1957 SubRegs
.isValid(); ++SubRegs
)
1958 ExtUses
.insert(*SubRegs
);
1962 for (MCPhysReg Reg
: Defs
) {
1963 if (!ExtUses
.count(Reg
)) {
1964 for (MCSubRegIterator
SubRegs(Reg
, TRI
, /*IncludeSelf=*/true);
1965 SubRegs
.isValid(); ++SubRegs
)
1966 RedefsByFalse
.insert(*SubRegs
);
1972 // Predicate the 'true' block.
1973 PredicateBlock(*BBI1
, MBB1
.end(), *Cond1
, &RedefsByFalse
);
1975 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1976 // a non-predicated in BBI2, then we don't want to predicate the one from
1977 // BBI2. The reason is that if we merged these blocks, we would end up with
1978 // two predicated terminators in the same block.
1979 // Also, if the branches in MBB1 and MBB2 were non-analyzable, then don't
1980 // predicate them either. They were checked to be identical, and so the
1981 // same branch would happen regardless of which path was taken.
1982 if (!MBB2
.empty() && (DI2
== MBB2
.end())) {
1983 MachineBasicBlock::iterator BBI1T
= MBB1
.getFirstTerminator();
1984 MachineBasicBlock::iterator BBI2T
= MBB2
.getFirstTerminator();
1985 bool BB1Predicated
= BBI1T
!= MBB1
.end() && TII
->isPredicated(*BBI1T
);
1986 bool BB2NonPredicated
= BBI2T
!= MBB2
.end() && !TII
->isPredicated(*BBI2T
);
1987 if (BB2NonPredicated
&& (BB1Predicated
|| !BBI2
->IsBrAnalyzable
))
1991 // Predicate the 'false' block.
1992 PredicateBlock(*BBI2
, DI2
, *Cond2
);
1994 // Merge the true block into the entry of the diamond.
1995 MergeBlocks(BBI
, *BBI1
, MergeAddEdges
);
1996 MergeBlocks(BBI
, *BBI2
, MergeAddEdges
);
2000 /// If convert an almost-diamond sub-CFG where the true
2001 /// and false blocks share a common tail.
2002 bool IfConverter::IfConvertForkedDiamond(
2003 BBInfo
&BBI
, IfcvtKind Kind
,
2004 unsigned NumDups1
, unsigned NumDups2
,
2005 bool TClobbersPred
, bool FClobbersPred
) {
2006 BBInfo
&TrueBBI
= BBAnalysis
[BBI
.TrueBB
->getNumber()];
2007 BBInfo
&FalseBBI
= BBAnalysis
[BBI
.FalseBB
->getNumber()];
2009 // Save the debug location for later.
2011 MachineBasicBlock::iterator TIE
= TrueBBI
.BB
->getFirstTerminator();
2012 if (TIE
!= TrueBBI
.BB
->end())
2013 dl
= TIE
->getDebugLoc();
2014 // Removing branches from both blocks is safe, because we have already
2015 // determined that both blocks have the same branch instructions. The branch
2016 // will be added back at the end, unpredicated.
2017 if (!IfConvertDiamondCommon(
2018 BBI
, TrueBBI
, FalseBBI
,
2020 TClobbersPred
, FClobbersPred
,
2021 /* RemoveBranch */ true, /* MergeAddEdges */ true))
2024 // Add back the branch.
2025 // Debug location saved above when removing the branch from BBI2
2026 TII
->insertBranch(*BBI
.BB
, TrueBBI
.TrueBB
, TrueBBI
.FalseBB
,
2027 TrueBBI
.BrCond
, dl
);
2029 // Update block info.
2030 BBI
.IsDone
= TrueBBI
.IsDone
= FalseBBI
.IsDone
= true;
2031 InvalidatePreds(*BBI
.BB
);
2033 // FIXME: Must maintain LiveIns.
2037 /// If convert a diamond sub-CFG.
2038 bool IfConverter::IfConvertDiamond(BBInfo
&BBI
, IfcvtKind Kind
,
2039 unsigned NumDups1
, unsigned NumDups2
,
2040 bool TClobbersPred
, bool FClobbersPred
) {
2041 BBInfo
&TrueBBI
= BBAnalysis
[BBI
.TrueBB
->getNumber()];
2042 BBInfo
&FalseBBI
= BBAnalysis
[BBI
.FalseBB
->getNumber()];
2043 MachineBasicBlock
*TailBB
= TrueBBI
.TrueBB
;
2045 // True block must fall through or end with an unanalyzable terminator.
2047 if (blockAlwaysFallThrough(TrueBBI
))
2048 TailBB
= FalseBBI
.TrueBB
;
2049 assert((TailBB
|| !TrueBBI
.IsBrAnalyzable
) && "Unexpected!");
2052 if (!IfConvertDiamondCommon(
2053 BBI
, TrueBBI
, FalseBBI
,
2055 TClobbersPred
, FClobbersPred
,
2056 /* RemoveBranch */ TrueBBI
.IsBrAnalyzable
,
2057 /* MergeAddEdges */ TailBB
== nullptr))
2060 // If the if-converted block falls through or unconditionally branches into
2061 // the tail block, and the tail block does not have other predecessors, then
2062 // fold the tail block in as well. Otherwise, unless it falls through to the
2063 // tail, add a unconditional branch to it.
2065 // We need to remove the edges to the true and false blocks manually since
2066 // we didn't let IfConvertDiamondCommon update the CFG.
2067 BBI
.BB
->removeSuccessor(TrueBBI
.BB
);
2068 BBI
.BB
->removeSuccessor(FalseBBI
.BB
, true);
2070 BBInfo
&TailBBI
= BBAnalysis
[TailBB
->getNumber()];
2071 bool CanMergeTail
= !TailBBI
.HasFallThrough
&&
2072 !TailBBI
.BB
->hasAddressTaken();
2073 // The if-converted block can still have a predicated terminator
2074 // (e.g. a predicated return). If that is the case, we cannot merge
2075 // it with the tail block.
2076 MachineBasicBlock::const_iterator TI
= BBI
.BB
->getFirstTerminator();
2077 if (TI
!= BBI
.BB
->end() && TII
->isPredicated(*TI
))
2078 CanMergeTail
= false;
2079 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
2080 // check if there are any other predecessors besides those.
2081 unsigned NumPreds
= TailBB
->pred_size();
2083 CanMergeTail
= false;
2084 else if (NumPreds
== 1 && CanMergeTail
) {
2085 MachineBasicBlock::pred_iterator PI
= TailBB
->pred_begin();
2086 if (*PI
!= TrueBBI
.BB
&& *PI
!= FalseBBI
.BB
)
2087 CanMergeTail
= false;
2090 MergeBlocks(BBI
, TailBBI
);
2091 TailBBI
.IsDone
= true;
2093 BBI
.BB
->addSuccessor(TailBB
, BranchProbability::getOne());
2094 InsertUncondBranch(*BBI
.BB
, *TailBB
, TII
);
2095 BBI
.HasFallThrough
= false;
2099 // Update block info.
2100 BBI
.IsDone
= TrueBBI
.IsDone
= FalseBBI
.IsDone
= true;
2101 InvalidatePreds(*BBI
.BB
);
2103 // FIXME: Must maintain LiveIns.
2107 static bool MaySpeculate(const MachineInstr
&MI
,
2108 SmallSet
<MCPhysReg
, 4> &LaterRedefs
) {
2109 bool SawStore
= true;
2110 if (!MI
.isSafeToMove(nullptr, SawStore
))
2113 for (const MachineOperand
&MO
: MI
.operands()) {
2116 Register Reg
= MO
.getReg();
2119 if (MO
.isDef() && !LaterRedefs
.count(Reg
))
2126 /// Predicate instructions from the start of the block to the specified end with
2127 /// the specified condition.
2128 void IfConverter::PredicateBlock(BBInfo
&BBI
,
2129 MachineBasicBlock::iterator E
,
2130 SmallVectorImpl
<MachineOperand
> &Cond
,
2131 SmallSet
<MCPhysReg
, 4> *LaterRedefs
) {
2132 bool AnyUnpred
= false;
2133 bool MaySpec
= LaterRedefs
!= nullptr;
2134 for (MachineInstr
&I
: make_range(BBI
.BB
->begin(), E
)) {
2135 if (I
.isDebugInstr() || TII
->isPredicated(I
))
2137 // It may be possible not to predicate an instruction if it's the 'true'
2138 // side of a diamond and the 'false' side may re-define the instruction's
2140 if (MaySpec
&& MaySpeculate(I
, *LaterRedefs
)) {
2144 // If any instruction is predicated, then every instruction after it must
2147 if (!TII
->PredicateInstruction(I
, Cond
)) {
2149 dbgs() << "Unable to predicate " << I
<< "!\n";
2151 llvm_unreachable(nullptr);
2154 // If the predicated instruction now redefines a register as the result of
2155 // if-conversion, add an implicit kill.
2156 UpdatePredRedefs(I
, Redefs
);
2159 BBI
.Predicate
.append(Cond
.begin(), Cond
.end());
2161 BBI
.IsAnalyzed
= false;
2162 BBI
.NonPredSize
= 0;
2169 /// Copy and predicate instructions from source BB to the destination block.
2170 /// Skip end of block branches if IgnoreBr is true.
2171 void IfConverter::CopyAndPredicateBlock(BBInfo
&ToBBI
, BBInfo
&FromBBI
,
2172 SmallVectorImpl
<MachineOperand
> &Cond
,
2174 MachineFunction
&MF
= *ToBBI
.BB
->getParent();
2176 MachineBasicBlock
&FromMBB
= *FromBBI
.BB
;
2177 for (MachineInstr
&I
: FromMBB
) {
2178 // Do not copy the end of the block branches.
2179 if (IgnoreBr
&& I
.isBranch())
2182 MachineInstr
*MI
= MF
.CloneMachineInstr(&I
);
2183 // Make a copy of the call site info.
2184 if (MI
->isCall(MachineInstr::IgnoreBundle
))
2185 MF
.copyCallSiteInfo(&I
,MI
);
2187 ToBBI
.BB
->insert(ToBBI
.BB
->end(), MI
);
2188 ToBBI
.NonPredSize
++;
2189 unsigned ExtraPredCost
= TII
->getPredicationCost(I
);
2190 unsigned NumCycles
= SchedModel
.computeInstrLatency(&I
, false);
2192 ToBBI
.ExtraCost
+= NumCycles
-1;
2193 ToBBI
.ExtraCost2
+= ExtraPredCost
;
2195 if (!TII
->isPredicated(I
) && !MI
->isDebugInstr()) {
2196 if (!TII
->PredicateInstruction(*MI
, Cond
)) {
2198 dbgs() << "Unable to predicate " << I
<< "!\n";
2200 llvm_unreachable(nullptr);
2204 // If the predicated instruction now redefines a register as the result of
2205 // if-conversion, add an implicit kill.
2206 UpdatePredRedefs(*MI
, Redefs
);
2210 std::vector
<MachineBasicBlock
*> Succs(FromMBB
.succ_begin(),
2211 FromMBB
.succ_end());
2212 MachineBasicBlock
*NBB
= getNextBlock(FromMBB
);
2213 MachineBasicBlock
*FallThrough
= FromBBI
.HasFallThrough
? NBB
: nullptr;
2215 for (MachineBasicBlock
*Succ
: Succs
) {
2216 // Fallthrough edge can't be transferred.
2217 if (Succ
== FallThrough
)
2219 ToBBI
.BB
->addSuccessor(Succ
);
2223 ToBBI
.Predicate
.append(FromBBI
.Predicate
.begin(), FromBBI
.Predicate
.end());
2224 ToBBI
.Predicate
.append(Cond
.begin(), Cond
.end());
2226 ToBBI
.ClobbersPred
|= FromBBI
.ClobbersPred
;
2227 ToBBI
.IsAnalyzed
= false;
2232 /// Move all instructions from FromBB to the end of ToBB. This will leave
2233 /// FromBB as an empty block, so remove all of its successor edges except for
2234 /// the fall-through edge. If AddEdges is true, i.e., when FromBBI's branch is
2235 /// being moved, add those successor edges to ToBBI and remove the old edge
2236 /// from ToBBI to FromBBI.
2237 void IfConverter::MergeBlocks(BBInfo
&ToBBI
, BBInfo
&FromBBI
, bool AddEdges
) {
2238 MachineBasicBlock
&FromMBB
= *FromBBI
.BB
;
2239 assert(!FromMBB
.hasAddressTaken() &&
2240 "Removing a BB whose address is taken!");
2242 // In case FromMBB contains terminators (e.g. return instruction),
2243 // first move the non-terminator instructions, then the terminators.
2244 MachineBasicBlock::iterator FromTI
= FromMBB
.getFirstTerminator();
2245 MachineBasicBlock::iterator ToTI
= ToBBI
.BB
->getFirstTerminator();
2246 ToBBI
.BB
->splice(ToTI
, &FromMBB
, FromMBB
.begin(), FromTI
);
2248 // If FromBB has non-predicated terminator we should copy it at the end.
2249 if (FromTI
!= FromMBB
.end() && !TII
->isPredicated(*FromTI
))
2250 ToTI
= ToBBI
.BB
->end();
2251 ToBBI
.BB
->splice(ToTI
, &FromMBB
, FromTI
, FromMBB
.end());
2253 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2254 // unknown probabilities into known ones.
2255 // FIXME: This usage is too tricky and in the future we would like to
2256 // eliminate all unknown probabilities in MBB.
2257 if (ToBBI
.IsBrAnalyzable
)
2258 ToBBI
.BB
->normalizeSuccProbs();
2260 SmallVector
<MachineBasicBlock
*, 4> FromSuccs(FromMBB
.succ_begin(),
2261 FromMBB
.succ_end());
2262 MachineBasicBlock
*NBB
= getNextBlock(FromMBB
);
2263 MachineBasicBlock
*FallThrough
= FromBBI
.HasFallThrough
? NBB
: nullptr;
2264 // The edge probability from ToBBI.BB to FromMBB, which is only needed when
2265 // AddEdges is true and FromMBB is a successor of ToBBI.BB.
2266 auto To2FromProb
= BranchProbability::getZero();
2267 if (AddEdges
&& ToBBI
.BB
->isSuccessor(&FromMBB
)) {
2268 // Remove the old edge but remember the edge probability so we can calculate
2269 // the correct weights on the new edges being added further down.
2270 To2FromProb
= MBPI
->getEdgeProbability(ToBBI
.BB
, &FromMBB
);
2271 ToBBI
.BB
->removeSuccessor(&FromMBB
);
2274 for (MachineBasicBlock
*Succ
: FromSuccs
) {
2275 // Fallthrough edge can't be transferred.
2276 if (Succ
== FallThrough
)
2279 auto NewProb
= BranchProbability::getZero();
2281 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
2282 // which is a portion of the edge probability from FromMBB to Succ. The
2283 // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
2284 // FromBBI is a successor of ToBBI.BB. See comment below for exception).
2285 NewProb
= MBPI
->getEdgeProbability(&FromMBB
, Succ
);
2287 // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
2288 // only happens when if-converting a diamond CFG and FromMBB is the
2289 // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
2290 // could just use the probabilities on FromMBB's out-edges when adding
2292 if (!To2FromProb
.isZero())
2293 NewProb
*= To2FromProb
;
2296 FromMBB
.removeSuccessor(Succ
);
2299 // If the edge from ToBBI.BB to Succ already exists, update the
2300 // probability of this edge by adding NewProb to it. An example is shown
2301 // below, in which A is ToBBI.BB and B is FromMBB. In this case we
2302 // don't have to set C as A's successor as it already is. We only need to
2303 // update the edge probability on A->C. Note that B will not be
2304 // immediately removed from A's successors. It is possible that B->D is
2305 // not removed either if D is a fallthrough of B. Later the edge A->D
2306 // (generated here) and B->D will be combined into one edge. To maintain
2307 // correct edge probability of this combined edge, we need to set the edge
2308 // probability of A->B to zero, which is already done above. The edge
2309 // probability on A->D is calculated by scaling the original probability
2310 // on A->B by the probability of B->D.
2312 // Before ifcvt: After ifcvt (assume B->D is kept):
2321 if (ToBBI
.BB
->isSuccessor(Succ
))
2322 ToBBI
.BB
->setSuccProbability(
2323 find(ToBBI
.BB
->successors(), Succ
),
2324 MBPI
->getEdgeProbability(ToBBI
.BB
, Succ
) + NewProb
);
2326 ToBBI
.BB
->addSuccessor(Succ
, NewProb
);
2330 // Move the now empty FromMBB out of the way to the end of the function so
2331 // it doesn't interfere with fallthrough checks done by canFallThroughTo().
2332 MachineBasicBlock
*Last
= &*FromMBB
.getParent()->rbegin();
2333 if (Last
!= &FromMBB
)
2334 FromMBB
.moveAfter(Last
);
2336 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2337 // we've done above.
2338 if (ToBBI
.IsBrAnalyzable
&& FromBBI
.IsBrAnalyzable
)
2339 ToBBI
.BB
->normalizeSuccProbs();
2341 ToBBI
.Predicate
.append(FromBBI
.Predicate
.begin(), FromBBI
.Predicate
.end());
2342 FromBBI
.Predicate
.clear();
2344 ToBBI
.NonPredSize
+= FromBBI
.NonPredSize
;
2345 ToBBI
.ExtraCost
+= FromBBI
.ExtraCost
;
2346 ToBBI
.ExtraCost2
+= FromBBI
.ExtraCost2
;
2347 FromBBI
.NonPredSize
= 0;
2348 FromBBI
.ExtraCost
= 0;
2349 FromBBI
.ExtraCost2
= 0;
2351 ToBBI
.ClobbersPred
|= FromBBI
.ClobbersPred
;
2352 ToBBI
.HasFallThrough
= FromBBI
.HasFallThrough
;
2353 ToBBI
.IsAnalyzed
= false;
2354 FromBBI
.IsAnalyzed
= false;
2358 llvm::createIfConverter(std::function
<bool(const MachineFunction
&)> Ftor
) {
2359 return new IfConverter(std::move(Ftor
));