1 //===- FlatternCFG.cpp - Code to perform CFG flattening -------------------===//
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 // Reduce conditional branches in CFG.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/SmallPtrSet.h"
14 #include "llvm/Analysis/AliasAnalysis.h"
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Analysis/ValueTracking.h"
17 #include "llvm/IR/BasicBlock.h"
18 #include "llvm/IR/IRBuilder.h"
19 #include "llvm/IR/InstrTypes.h"
20 #include "llvm/IR/Instruction.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/Value.h"
23 #include "llvm/Support/Casting.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
31 #define DEBUG_TYPE "flattencfg"
38 /// Use parallel-and or parallel-or to generate conditions for
39 /// conditional branches.
40 bool FlattenParallelAndOr(BasicBlock
*BB
, IRBuilder
<> &Builder
);
42 /// If \param BB is the merge block of an if-region, attempt to merge
43 /// the if-region with an adjacent if-region upstream if two if-regions
44 /// contain identical instructions.
45 bool MergeIfRegion(BasicBlock
*BB
, IRBuilder
<> &Builder
);
47 /// Compare a pair of blocks: \p Block1 and \p Block2, which
48 /// are from two if-regions whose entry blocks are \p Head1 and \p
49 /// Head2. \returns true if \p Block1 and \p Block2 contain identical
50 /// instructions, and have no memory reference alias with \p Head2.
51 /// This is used as a legality check for merging if-regions.
52 bool CompareIfRegionBlock(BasicBlock
*Head1
, BasicBlock
*Head2
,
53 BasicBlock
*Block1
, BasicBlock
*Block2
);
56 FlattenCFGOpt(AliasAnalysis
*AA
) : AA(AA
) {}
58 bool run(BasicBlock
*BB
);
61 } // end anonymous namespace
63 /// If \param [in] BB has more than one predecessor that is a conditional
64 /// branch, attempt to use parallel and/or for the branch condition. \returns
69 /// %cmp10 = fcmp une float %tmp1, %tmp2
70 /// br i1 %cmp1, label %if.then, label %lor.rhs
74 /// %cmp11 = fcmp une float %tmp3, %tmp4
75 /// br i1 %cmp11, label %if.then, label %ifend
77 /// if.end: // the merge block
80 /// if.then: // has two predecessors, both of them contains conditional branch.
86 /// %cmp10 = fcmp une float %tmp1, %tmp2
88 /// %cmp11 = fcmp une float %tmp3, %tmp4
89 /// %cmp12 = or i1 %cmp10, %cmp11 // parallel-or mode.
90 /// br i1 %cmp12, label %if.then, label %ifend
99 /// Current implementation handles two cases.
100 /// Case 1: \param BB is on the else-path.
106 /// BB3 \ | where, BB1, BB2 contain conditional branches.
107 /// \ | / BB3 contains unconditional branch.
108 /// \ | / BB4 corresponds to \param BB which is also the merge.
112 /// Corresponding source code:
114 /// if (a == b && c == d)
115 /// statement; // BB3
117 /// Case 2: \param BB BB is on the then-path.
122 /// \ / | where BB1, BB2 contain conditional branches.
123 /// BB => BB3 | BB3 contains unconditiona branch and corresponds
124 /// \ / to \param BB. BB4 is the merge.
127 /// Corresponding source code:
129 /// if (a == b || c == d)
130 /// statement; // BB3
132 /// In both cases, \param BB is the common successor of conditional branches.
133 /// In Case 1, \param BB (BB4) has an unconditional branch (BB3) as
134 /// its predecessor. In Case 2, \param BB (BB3) only has conditional branches
135 /// as its predecessors.
136 bool FlattenCFGOpt::FlattenParallelAndOr(BasicBlock
*BB
, IRBuilder
<> &Builder
) {
137 PHINode
*PHI
= dyn_cast
<PHINode
>(BB
->begin());
139 return false; // For simplicity, avoid cases containing PHI nodes.
141 BasicBlock
*LastCondBlock
= nullptr;
142 BasicBlock
*FirstCondBlock
= nullptr;
143 BasicBlock
*UnCondBlock
= nullptr;
146 // Check predecessors of \param BB.
147 SmallPtrSet
<BasicBlock
*, 16> Preds(pred_begin(BB
), pred_end(BB
));
148 for (SmallPtrSetIterator
<BasicBlock
*> PI
= Preds
.begin(), PE
= Preds
.end();
150 BasicBlock
*Pred
= *PI
;
151 BranchInst
*PBI
= dyn_cast
<BranchInst
>(Pred
->getTerminator());
153 // All predecessors should terminate with a branch.
157 BasicBlock
*PP
= Pred
->getSinglePredecessor();
159 if (PBI
->isUnconditional()) {
160 // Case 1: Pred (BB3) is an unconditional block, it should
161 // have a single predecessor (BB2) that is also a predecessor
162 // of \param BB (BB4) and should not have address-taken.
163 // There should exist only one such unconditional
164 // branch among the predecessors.
165 if (UnCondBlock
|| !PP
|| (Preds
.count(PP
) == 0) ||
166 Pred
->hasAddressTaken())
173 // Only conditional branches are allowed beyond this point.
174 assert(PBI
->isConditional());
176 // Condition's unique use should be the branch instruction.
177 Value
*PC
= PBI
->getCondition();
178 if (!PC
|| !PC
->hasOneUse())
181 if (PP
&& Preds
.count(PP
)) {
182 // These are internal condition blocks to be merged from, e.g.,
183 // BB2 in both cases.
184 // Should not be address-taken.
185 if (Pred
->hasAddressTaken())
188 // Instructions in the internal condition blocks should be safe
190 for (BasicBlock::iterator BI
= Pred
->begin(), BE
= PBI
->getIterator();
192 Instruction
*CI
= &*BI
++;
193 if (isa
<PHINode
>(CI
) || !isSafeToSpeculativelyExecute(CI
))
197 // This is the condition block to be merged into, e.g. BB1 in
201 FirstCondBlock
= Pred
;
204 // Find whether BB is uniformly on the true (or false) path
205 // for all of its predecessors.
206 BasicBlock
*PS1
= PBI
->getSuccessor(0);
207 BasicBlock
*PS2
= PBI
->getSuccessor(1);
208 BasicBlock
*PS
= (PS1
== BB
) ? PS2
: PS1
;
209 int CIdx
= (PS1
== BB
) ? 0 : 1;
213 else if (CIdx
!= Idx
)
216 // PS is the successor which is not BB. Check successors to identify
217 // the last conditional branch.
218 if (Preds
.count(PS
) == 0) {
220 LastCondBlock
= Pred
;
223 BranchInst
*BPS
= dyn_cast
<BranchInst
>(PS
->getTerminator());
224 if (BPS
&& BPS
->isUnconditional()) {
225 // Case 1: PS(BB3) should be an unconditional branch.
226 LastCondBlock
= Pred
;
231 if (!FirstCondBlock
|| !LastCondBlock
|| (FirstCondBlock
== LastCondBlock
))
234 Instruction
*TBB
= LastCondBlock
->getTerminator();
235 BasicBlock
*PS1
= TBB
->getSuccessor(0);
236 BasicBlock
*PS2
= TBB
->getSuccessor(1);
237 BranchInst
*PBI1
= dyn_cast
<BranchInst
>(PS1
->getTerminator());
238 BranchInst
*PBI2
= dyn_cast
<BranchInst
>(PS2
->getTerminator());
240 // If PS1 does not jump into PS2, but PS2 jumps into PS1,
241 // attempt branch inversion.
242 if (!PBI1
|| !PBI1
->isUnconditional() ||
243 (PS1
->getTerminator()->getSuccessor(0) != PS2
)) {
244 // Check whether PS2 jumps into PS1.
245 if (!PBI2
|| !PBI2
->isUnconditional() ||
246 (PS2
->getTerminator()->getSuccessor(0) != PS1
))
249 // Do branch inversion.
250 BasicBlock
*CurrBlock
= LastCondBlock
;
251 bool EverChanged
= false;
252 for (; CurrBlock
!= FirstCondBlock
;
253 CurrBlock
= CurrBlock
->getSinglePredecessor()) {
254 BranchInst
*BI
= dyn_cast
<BranchInst
>(CurrBlock
->getTerminator());
255 CmpInst
*CI
= dyn_cast
<CmpInst
>(BI
->getCondition());
259 CmpInst::Predicate Predicate
= CI
->getPredicate();
260 // Canonicalize icmp_ne -> icmp_eq, fcmp_one -> fcmp_oeq
261 if ((Predicate
== CmpInst::ICMP_NE
) || (Predicate
== CmpInst::FCMP_ONE
)) {
262 CI
->setPredicate(ICmpInst::getInversePredicate(Predicate
));
263 BI
->swapSuccessors();
270 // PS1 must have a conditional branch.
271 if (!PBI1
|| !PBI1
->isUnconditional())
274 // PS2 should not contain PHI node.
275 PHI
= dyn_cast
<PHINode
>(PS2
->begin());
279 // Do the transformation.
281 BranchInst
*PBI
= dyn_cast
<BranchInst
>(FirstCondBlock
->getTerminator());
282 bool Iteration
= true;
283 IRBuilder
<>::InsertPointGuard
Guard(Builder
);
284 Value
*PC
= PBI
->getCondition();
287 CB
= PBI
->getSuccessor(1 - Idx
);
288 // Delete the conditional branch.
289 FirstCondBlock
->getInstList().pop_back();
290 FirstCondBlock
->getInstList()
291 .splice(FirstCondBlock
->end(), CB
->getInstList());
292 PBI
= cast
<BranchInst
>(FirstCondBlock
->getTerminator());
293 Value
*CC
= PBI
->getCondition();
295 Builder
.SetInsertPoint(PBI
);
298 // Case 2, use parallel or.
299 NC
= Builder
.CreateOr(PC
, CC
);
301 // Case 1, use parallel and.
302 NC
= Builder
.CreateAnd(PC
, CC
);
304 PBI
->replaceUsesOfWith(CC
, NC
);
306 if (CB
== LastCondBlock
)
308 // Remove internal conditional branches.
309 CB
->dropAllReferences();
310 // make CB unreachable and let downstream to delete the block.
311 new UnreachableInst(CB
->getContext(), CB
);
314 LLVM_DEBUG(dbgs() << "Use parallel and/or in:\n" << *FirstCondBlock
);
318 /// Compare blocks from two if-regions, where \param Head1 is the entry of the
319 /// 1st if-region. \param Head2 is the entry of the 2nd if-region. \param
320 /// Block1 is a block in the 1st if-region to compare. \param Block2 is a block
321 // in the 2nd if-region to compare. \returns true if \param Block1 and \param
322 /// Block2 have identical instructions and do not have memory reference alias
323 /// with \param Head2.
324 bool FlattenCFGOpt::CompareIfRegionBlock(BasicBlock
*Head1
, BasicBlock
*Head2
,
326 BasicBlock
*Block2
) {
327 Instruction
*PTI2
= Head2
->getTerminator();
328 Instruction
*PBI2
= &Head2
->front();
330 bool eq1
= (Block1
== Head1
);
331 bool eq2
= (Block2
== Head2
);
333 // An empty then-path or else-path.
337 // Check whether instructions in Block1 and Block2 are identical
338 // and do not alias with instructions in Head2.
339 BasicBlock::iterator iter1
= Block1
->begin();
340 BasicBlock::iterator end1
= Block1
->getTerminator()->getIterator();
341 BasicBlock::iterator iter2
= Block2
->begin();
342 BasicBlock::iterator end2
= Block2
->getTerminator()->getIterator();
351 if (!iter1
->isIdenticalTo(&*iter2
))
354 // Illegal to remove instructions with side effects except
355 // non-volatile stores.
356 if (iter1
->mayHaveSideEffects()) {
357 Instruction
*CurI
= &*iter1
;
358 StoreInst
*SI
= dyn_cast
<StoreInst
>(CurI
);
359 if (!SI
|| SI
->isVolatile())
363 // For simplicity and speed, data dependency check can be
364 // avoided if read from memory doesn't exist.
365 if (iter1
->mayReadFromMemory())
368 if (iter1
->mayWriteToMemory()) {
369 for (BasicBlock::iterator
BI(PBI2
), BE(PTI2
); BI
!= BE
; ++BI
) {
370 if (BI
->mayReadFromMemory() || BI
->mayWriteToMemory()) {
371 // Check alias with Head2.
372 if (!AA
|| AA
->alias(&*iter1
, &*BI
))
384 /// Check whether \param BB is the merge block of a if-region. If yes, check
385 /// whether there exists an adjacent if-region upstream, the two if-regions
386 /// contain identical instructions and can be legally merged. \returns true if
387 /// the two if-regions are merged.
398 bool FlattenCFGOpt::MergeIfRegion(BasicBlock
*BB
, IRBuilder
<> &Builder
) {
399 BasicBlock
*IfTrue2
, *IfFalse2
;
400 Value
*IfCond2
= GetIfCondition(BB
, IfTrue2
, IfFalse2
);
401 Instruction
*CInst2
= dyn_cast_or_null
<Instruction
>(IfCond2
);
405 BasicBlock
*SecondEntryBlock
= CInst2
->getParent();
406 if (SecondEntryBlock
->hasAddressTaken())
409 BasicBlock
*IfTrue1
, *IfFalse1
;
410 Value
*IfCond1
= GetIfCondition(SecondEntryBlock
, IfTrue1
, IfFalse1
);
411 Instruction
*CInst1
= dyn_cast_or_null
<Instruction
>(IfCond1
);
415 BasicBlock
*FirstEntryBlock
= CInst1
->getParent();
417 // Either then-path or else-path should be empty.
418 if ((IfTrue1
!= FirstEntryBlock
) && (IfFalse1
!= FirstEntryBlock
))
420 if ((IfTrue2
!= SecondEntryBlock
) && (IfFalse2
!= SecondEntryBlock
))
423 Instruction
*PTI2
= SecondEntryBlock
->getTerminator();
424 Instruction
*PBI2
= &SecondEntryBlock
->front();
426 if (!CompareIfRegionBlock(FirstEntryBlock
, SecondEntryBlock
, IfTrue1
,
430 if (!CompareIfRegionBlock(FirstEntryBlock
, SecondEntryBlock
, IfFalse1
,
434 // Check whether \param SecondEntryBlock has side-effect and is safe to
436 for (BasicBlock::iterator
BI(PBI2
), BE(PTI2
); BI
!= BE
; ++BI
) {
437 Instruction
*CI
= &*BI
;
438 if (isa
<PHINode
>(CI
) || CI
->mayHaveSideEffects() ||
439 !isSafeToSpeculativelyExecute(CI
))
443 // Merge \param SecondEntryBlock into \param FirstEntryBlock.
444 FirstEntryBlock
->getInstList().pop_back();
445 FirstEntryBlock
->getInstList()
446 .splice(FirstEntryBlock
->end(), SecondEntryBlock
->getInstList());
447 BranchInst
*PBI
= dyn_cast
<BranchInst
>(FirstEntryBlock
->getTerminator());
448 Value
*CC
= PBI
->getCondition();
449 BasicBlock
*SaveInsertBB
= Builder
.GetInsertBlock();
450 BasicBlock::iterator SaveInsertPt
= Builder
.GetInsertPoint();
451 Builder
.SetInsertPoint(PBI
);
452 Value
*NC
= Builder
.CreateOr(CInst1
, CC
);
453 PBI
->replaceUsesOfWith(CC
, NC
);
454 Builder
.SetInsertPoint(SaveInsertBB
, SaveInsertPt
);
457 if (IfTrue1
!= FirstEntryBlock
) {
458 IfTrue1
->dropAllReferences();
459 IfTrue1
->eraseFromParent();
463 if (IfFalse1
!= FirstEntryBlock
) {
464 IfFalse1
->dropAllReferences();
465 IfFalse1
->eraseFromParent();
468 // Remove \param SecondEntryBlock
469 SecondEntryBlock
->dropAllReferences();
470 SecondEntryBlock
->eraseFromParent();
471 LLVM_DEBUG(dbgs() << "If conditions merged into:\n" << *FirstEntryBlock
);
475 bool FlattenCFGOpt::run(BasicBlock
*BB
) {
476 assert(BB
&& BB
->getParent() && "Block not embedded in function!");
477 assert(BB
->getTerminator() && "Degenerate basic block encountered!");
479 IRBuilder
<> Builder(BB
);
481 if (FlattenParallelAndOr(BB
, Builder
) || MergeIfRegion(BB
, Builder
))
486 /// FlattenCFG - This function is used to flatten a CFG. For
487 /// example, it uses parallel-and and parallel-or mode to collapse
488 /// if-conditions and merge if-regions with identical statements.
489 bool llvm::FlattenCFG(BasicBlock
*BB
, AliasAnalysis
*AA
) {
490 return FlattenCFGOpt(AA
).run(BB
);