blob: ffdfacdc59f21efb442bbd73d514c81759bfb016 [file] [log] [blame]
Tom Stellardaa664d92013-08-06 02:43:45 +00001//===- FlatternCFG.cpp - Code to perform CFG flattening ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Reduce conditional branches in CFG.
11//
12//===----------------------------------------------------------------------===//
13
Tom Stellardaa664d92013-08-06 02:43:45 +000014#include "llvm/Transforms/Utils/Local.h"
15#include "llvm/ADT/SmallPtrSet.h"
16#include "llvm/Analysis/AliasAnalysis.h"
17#include "llvm/Analysis/ValueTracking.h"
18#include "llvm/IR/IRBuilder.h"
19#include "llvm/Support/Debug.h"
Serge Pavlov71044cb2013-08-06 08:44:18 +000020#include "llvm/Support/raw_ostream.h"
Tom Stellardaa664d92013-08-06 02:43:45 +000021#include "llvm/Transforms/Utils/BasicBlockUtils.h"
22using namespace llvm;
23
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "flattencfg"
25
Tom Stellardaa664d92013-08-06 02:43:45 +000026namespace {
27class FlattenCFGOpt {
28 AliasAnalysis *AA;
29 /// \brief Use parallel-and or parallel-or to generate conditions for
30 /// conditional branches.
31 bool FlattenParallelAndOr(BasicBlock *BB, IRBuilder<> &Builder, Pass *P = 0);
32 /// \brief If \param BB is the merge block of an if-region, attempt to merge
33 /// the if-region with an adjacent if-region upstream if two if-regions
34 /// contain identical instructions.
35 bool MergeIfRegion(BasicBlock *BB, IRBuilder<> &Builder, Pass *P = 0);
36 /// \brief Compare a pair of blocks: \p Block1 and \p Block2, which
37 /// are from two if-regions whose entry blocks are \p Head1 and \p
38 /// Head2. \returns true if \p Block1 and \p Block2 contain identical
39 /// instructions, and have no memory reference alias with \p Head2.
40 /// This is used as a legality check for merging if-regions.
41 bool CompareIfRegionBlock(BasicBlock *Head1, BasicBlock *Head2,
42 BasicBlock *Block1, BasicBlock *Block2);
43
44public:
45 FlattenCFGOpt(AliasAnalysis *AA) : AA(AA) {}
46 bool run(BasicBlock *BB);
47};
48}
49
50/// If \param [in] BB has more than one predecessor that is a conditional
51/// branch, attempt to use parallel and/or for the branch condition. \returns
52/// true on success.
53///
54/// Before:
55/// ......
56/// %cmp10 = fcmp une float %tmp1, %tmp2
57/// br i1 %cmp1, label %if.then, label %lor.rhs
58///
59/// lor.rhs:
60/// ......
61/// %cmp11 = fcmp une float %tmp3, %tmp4
62/// br i1 %cmp11, label %if.then, label %ifend
63///
64/// if.end: // the merge block
65/// ......
66///
67/// if.then: // has two predecessors, both of them contains conditional branch.
68/// ......
69/// br label %if.end;
70///
71/// After:
72/// ......
73/// %cmp10 = fcmp une float %tmp1, %tmp2
74/// ......
75/// %cmp11 = fcmp une float %tmp3, %tmp4
76/// %cmp12 = or i1 %cmp10, %cmp11 // parallel-or mode.
77/// br i1 %cmp12, label %if.then, label %ifend
78///
79/// if.end:
80/// ......
81///
82/// if.then:
83/// ......
84/// br label %if.end;
85///
86/// Current implementation handles two cases.
87/// Case 1: \param BB is on the else-path.
88///
89/// BB1
90/// / |
91/// BB2 |
92/// / \ |
93/// BB3 \ | where, BB1, BB2 contain conditional branches.
94/// \ | / BB3 contains unconditional branch.
95/// \ | / BB4 corresponds to \param BB which is also the merge.
96/// BB => BB4
97///
98///
99/// Corresponding source code:
100///
101/// if (a == b && c == d)
102/// statement; // BB3
103///
104/// Case 2: \param BB BB is on the then-path.
105///
106/// BB1
107/// / |
108/// | BB2
109/// \ / | where BB1, BB2 contain conditional branches.
110/// BB => BB3 | BB3 contains unconditiona branch and corresponds
111/// \ / to \param BB. BB4 is the merge.
112/// BB4
113///
114/// Corresponding source code:
115///
116/// if (a == b || c == d)
117/// statement; // BB3
118///
119/// In both cases, \param BB is the common successor of conditional branches.
120/// In Case 1, \param BB (BB4) has an unconditional branch (BB3) as
121/// its predecessor. In Case 2, \param BB (BB3) only has conditional branches
122/// as its predecessors.
123///
124bool FlattenCFGOpt::FlattenParallelAndOr(BasicBlock *BB, IRBuilder<> &Builder,
125 Pass *P) {
126 PHINode *PHI = dyn_cast<PHINode>(BB->begin());
127 if (PHI)
128 return false; // For simplicity, avoid cases containing PHI nodes.
129
130 BasicBlock *LastCondBlock = NULL;
131 BasicBlock *FirstCondBlock = NULL;
132 BasicBlock *UnCondBlock = NULL;
133 int Idx = -1;
134
135 // Check predecessors of \param BB.
136 SmallPtrSet<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
137 for (SmallPtrSetIterator<BasicBlock *> PI = Preds.begin(), PE = Preds.end();
138 PI != PE; ++PI) {
139 BasicBlock *Pred = *PI;
140 BranchInst *PBI = dyn_cast<BranchInst>(Pred->getTerminator());
141
142 // All predecessors should terminate with a branch.
143 if (!PBI)
144 return false;
145
146 BasicBlock *PP = Pred->getSinglePredecessor();
147
148 if (PBI->isUnconditional()) {
149 // Case 1: Pred (BB3) is an unconditional block, it should
150 // have a single predecessor (BB2) that is also a predecessor
151 // of \param BB (BB4) and should not have address-taken.
152 // There should exist only one such unconditional
153 // branch among the predecessors.
154 if (UnCondBlock || !PP || (Preds.count(PP) == 0) ||
155 Pred->hasAddressTaken())
156 return false;
157
158 UnCondBlock = Pred;
159 continue;
160 }
161
162 // Only conditional branches are allowed beyond this point.
163 assert(PBI->isConditional());
164
165 // Condition's unique use should be the branch instruction.
166 Value *PC = PBI->getCondition();
167 if (!PC || !PC->hasOneUse())
168 return false;
169
170 if (PP && Preds.count(PP)) {
171 // These are internal condition blocks to be merged from, e.g.,
172 // BB2 in both cases.
173 // Should not be address-taken.
174 if (Pred->hasAddressTaken())
175 return false;
176
177 // Instructions in the internal condition blocks should be safe
178 // to hoist up.
179 for (BasicBlock::iterator BI = Pred->begin(), BE = PBI; BI != BE;) {
180 Instruction *CI = BI++;
181 if (isa<PHINode>(CI) || !isSafeToSpeculativelyExecute(CI))
182 return false;
183 }
184 } else {
185 // This is the condition block to be merged into, e.g. BB1 in
186 // both cases.
187 if (FirstCondBlock)
188 return false;
189 FirstCondBlock = Pred;
190 }
191
192 // Find whether BB is uniformly on the true (or false) path
193 // for all of its predecessors.
194 BasicBlock *PS1 = PBI->getSuccessor(0);
195 BasicBlock *PS2 = PBI->getSuccessor(1);
196 BasicBlock *PS = (PS1 == BB) ? PS2 : PS1;
197 int CIdx = (PS1 == BB) ? 0 : 1;
198
199 if (Idx == -1)
200 Idx = CIdx;
201 else if (CIdx != Idx)
202 return false;
203
204 // PS is the successor which is not BB. Check successors to identify
205 // the last conditional branch.
206 if (Preds.count(PS) == 0) {
207 // Case 2.
208 LastCondBlock = Pred;
209 } else {
210 // Case 1
211 BranchInst *BPS = dyn_cast<BranchInst>(PS->getTerminator());
212 if (BPS && BPS->isUnconditional()) {
213 // Case 1: PS(BB3) should be an unconditional branch.
214 LastCondBlock = Pred;
215 }
216 }
217 }
218
219 if (!FirstCondBlock || !LastCondBlock || (FirstCondBlock == LastCondBlock))
220 return false;
221
222 TerminatorInst *TBB = LastCondBlock->getTerminator();
223 BasicBlock *PS1 = TBB->getSuccessor(0);
224 BasicBlock *PS2 = TBB->getSuccessor(1);
225 BranchInst *PBI1 = dyn_cast<BranchInst>(PS1->getTerminator());
226 BranchInst *PBI2 = dyn_cast<BranchInst>(PS2->getTerminator());
227
228 // If PS1 does not jump into PS2, but PS2 jumps into PS1,
229 // attempt branch inversion.
230 if (!PBI1 || !PBI1->isUnconditional() ||
231 (PS1->getTerminator()->getSuccessor(0) != PS2)) {
232 // Check whether PS2 jumps into PS1.
233 if (!PBI2 || !PBI2->isUnconditional() ||
234 (PS2->getTerminator()->getSuccessor(0) != PS1))
235 return false;
236
237 // Do branch inversion.
238 BasicBlock *CurrBlock = LastCondBlock;
239 bool EverChanged = false;
240 while (1) {
241 BranchInst *BI = dyn_cast<BranchInst>(CurrBlock->getTerminator());
242 CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
243 CmpInst::Predicate Predicate = CI->getPredicate();
Alp Tokercb402912014-01-24 17:20:08 +0000244 // Canonicalize icmp_ne -> icmp_eq, fcmp_one -> fcmp_oeq
Tom Stellardaa664d92013-08-06 02:43:45 +0000245 if ((Predicate == CmpInst::ICMP_NE) || (Predicate == CmpInst::FCMP_ONE)) {
246 CI->setPredicate(ICmpInst::getInversePredicate(Predicate));
247 BI->swapSuccessors();
248 EverChanged = true;
249 }
250 if (CurrBlock == FirstCondBlock)
251 break;
252 CurrBlock = CurrBlock->getSinglePredecessor();
253 }
254 return EverChanged;
255 }
256
257 // PS1 must have a conditional branch.
258 if (!PBI1 || !PBI1->isUnconditional())
259 return false;
260
261 // PS2 should not contain PHI node.
262 PHI = dyn_cast<PHINode>(PS2->begin());
263 if (PHI)
264 return false;
265
266 // Do the transformation.
267 BasicBlock *CB;
268 BranchInst *PBI = dyn_cast<BranchInst>(FirstCondBlock->getTerminator());
269 bool Iteration = true;
Benjamin Kramer6e931522013-09-30 15:40:17 +0000270 IRBuilder<>::InsertPointGuard Guard(Builder);
Tom Stellardaa664d92013-08-06 02:43:45 +0000271 Value *PC = PBI->getCondition();
272
273 do {
274 CB = PBI->getSuccessor(1 - Idx);
275 // Delete the conditional branch.
276 FirstCondBlock->getInstList().pop_back();
277 FirstCondBlock->getInstList()
278 .splice(FirstCondBlock->end(), CB->getInstList());
279 PBI = cast<BranchInst>(FirstCondBlock->getTerminator());
280 Value *CC = PBI->getCondition();
281 // Merge conditions.
282 Builder.SetInsertPoint(PBI);
283 Value *NC;
284 if (Idx == 0)
285 // Case 2, use parallel or.
286 NC = Builder.CreateOr(PC, CC);
287 else
288 // Case 1, use parallel and.
289 NC = Builder.CreateAnd(PC, CC);
290
291 PBI->replaceUsesOfWith(CC, NC);
292 PC = NC;
293 if (CB == LastCondBlock)
294 Iteration = false;
295 // Remove internal conditional branches.
296 CB->dropAllReferences();
297 // make CB unreachable and let downstream to delete the block.
298 new UnreachableInst(CB->getContext(), CB);
299 } while (Iteration);
300
Tom Stellardaa664d92013-08-06 02:43:45 +0000301 DEBUG(dbgs() << "Use parallel and/or in:\n" << *FirstCondBlock);
302 return true;
303}
304
305/// Compare blocks from two if-regions, where \param Head1 is the entry of the
306/// 1st if-region. \param Head2 is the entry of the 2nd if-region. \param
307/// Block1 is a block in the 1st if-region to compare. \param Block2 is a block
308// in the 2nd if-region to compare. \returns true if \param Block1 and \param
309/// Block2 have identical instructions and do not have memory reference alias
310/// with \param Head2.
311///
312bool FlattenCFGOpt::CompareIfRegionBlock(BasicBlock *Head1, BasicBlock *Head2,
313 BasicBlock *Block1,
314 BasicBlock *Block2) {
315 TerminatorInst *PTI2 = Head2->getTerminator();
316 Instruction *PBI2 = Head2->begin();
317
318 bool eq1 = (Block1 == Head1);
319 bool eq2 = (Block2 == Head2);
320 if (eq1 || eq2) {
321 // An empty then-path or else-path.
322 return (eq1 == eq2);
323 }
324
325 // Check whether instructions in Block1 and Block2 are identical
326 // and do not alias with instructions in Head2.
327 BasicBlock::iterator iter1 = Block1->begin();
328 BasicBlock::iterator end1 = Block1->getTerminator();
329 BasicBlock::iterator iter2 = Block2->begin();
330 BasicBlock::iterator end2 = Block2->getTerminator();
331
332 while (1) {
333 if (iter1 == end1) {
334 if (iter2 != end2)
335 return false;
336 break;
337 }
338
339 if (!iter1->isIdenticalTo(iter2))
340 return false;
341
342 // Illegal to remove instructions with side effects except
343 // non-volatile stores.
344 if (iter1->mayHaveSideEffects()) {
345 Instruction *CurI = &*iter1;
346 StoreInst *SI = dyn_cast<StoreInst>(CurI);
347 if (!SI || SI->isVolatile())
348 return false;
349 }
350
351 // For simplicity and speed, data dependency check can be
352 // avoided if read from memory doesn't exist.
353 if (iter1->mayReadFromMemory())
354 return false;
355
356 if (iter1->mayWriteToMemory()) {
357 for (BasicBlock::iterator BI = PBI2, BE = PTI2; BI != BE; ++BI) {
358 if (BI->mayReadFromMemory() || BI->mayWriteToMemory()) {
359 // Check alias with Head2.
360 if (!AA || AA->alias(iter1, BI))
361 return false;
362 }
363 }
364 }
365 ++iter1;
366 ++iter2;
367 }
368
369 return true;
370}
371
372/// Check whether \param BB is the merge block of a if-region. If yes, check
373/// whether there exists an adjacent if-region upstream, the two if-regions
Robert Wilhelm042f10c2013-09-14 09:34:59 +0000374/// contain identical instructions and can be legally merged. \returns true if
Tom Stellardaa664d92013-08-06 02:43:45 +0000375/// the two if-regions are merged.
376///
377/// From:
378/// if (a)
379/// statement;
380/// if (b)
381/// statement;
382///
383/// To:
384/// if (a || b)
385/// statement;
386///
387bool FlattenCFGOpt::MergeIfRegion(BasicBlock *BB, IRBuilder<> &Builder,
388 Pass *P) {
389 BasicBlock *IfTrue2, *IfFalse2;
390 Value *IfCond2 = GetIfCondition(BB, IfTrue2, IfFalse2);
391 Instruction *CInst2 = dyn_cast_or_null<Instruction>(IfCond2);
392 if (!CInst2)
393 return false;
394
395 BasicBlock *SecondEntryBlock = CInst2->getParent();
396 if (SecondEntryBlock->hasAddressTaken())
397 return false;
398
399 BasicBlock *IfTrue1, *IfFalse1;
400 Value *IfCond1 = GetIfCondition(SecondEntryBlock, IfTrue1, IfFalse1);
401 Instruction *CInst1 = dyn_cast_or_null<Instruction>(IfCond1);
402 if (!CInst1)
403 return false;
404
405 BasicBlock *FirstEntryBlock = CInst1->getParent();
406
407 // Either then-path or else-path should be empty.
408 if ((IfTrue1 != FirstEntryBlock) && (IfFalse1 != FirstEntryBlock))
409 return false;
410 if ((IfTrue2 != SecondEntryBlock) && (IfFalse2 != SecondEntryBlock))
411 return false;
412
413 TerminatorInst *PTI2 = SecondEntryBlock->getTerminator();
414 Instruction *PBI2 = SecondEntryBlock->begin();
415
416 if (!CompareIfRegionBlock(FirstEntryBlock, SecondEntryBlock, IfTrue1,
417 IfTrue2))
418 return false;
419
420 if (!CompareIfRegionBlock(FirstEntryBlock, SecondEntryBlock, IfFalse1,
421 IfFalse2))
422 return false;
423
424 // Check whether \param SecondEntryBlock has side-effect and is safe to
425 // speculate.
426 for (BasicBlock::iterator BI = PBI2, BE = PTI2; BI != BE; ++BI) {
427 Instruction *CI = BI;
428 if (isa<PHINode>(CI) || CI->mayHaveSideEffects() ||
429 !isSafeToSpeculativelyExecute(CI))
430 return false;
431 }
432
433 // Merge \param SecondEntryBlock into \param FirstEntryBlock.
434 FirstEntryBlock->getInstList().pop_back();
435 FirstEntryBlock->getInstList()
436 .splice(FirstEntryBlock->end(), SecondEntryBlock->getInstList());
437 BranchInst *PBI = dyn_cast<BranchInst>(FirstEntryBlock->getTerminator());
438 Value *CC = PBI->getCondition();
439 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
440 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
441 Builder.SetInsertPoint(PBI);
442 Value *NC = Builder.CreateOr(CInst1, CC);
443 PBI->replaceUsesOfWith(CC, NC);
444 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
445
446 // Remove IfTrue1
447 if (IfTrue1 != FirstEntryBlock) {
448 IfTrue1->dropAllReferences();
449 IfTrue1->eraseFromParent();
450 }
451
452 // Remove IfFalse1
453 if (IfFalse1 != FirstEntryBlock) {
454 IfFalse1->dropAllReferences();
455 IfFalse1->eraseFromParent();
456 }
457
458 // Remove \param SecondEntryBlock
459 SecondEntryBlock->dropAllReferences();
460 SecondEntryBlock->eraseFromParent();
461 DEBUG(dbgs() << "If conditions merged into:\n" << *FirstEntryBlock);
462 return true;
463}
464
465bool FlattenCFGOpt::run(BasicBlock *BB) {
466 bool Changed = false;
467 assert(BB && BB->getParent() && "Block not embedded in function!");
468 assert(BB->getTerminator() && "Degenerate basic block encountered!");
469
470 IRBuilder<> Builder(BB);
471
472 if (FlattenParallelAndOr(BB, Builder))
473 return true;
474
475 if (MergeIfRegion(BB, Builder))
476 return true;
477
478 return Changed;
479}
480
481/// FlattenCFG - This function is used to flatten a CFG. For
482/// example, it uses parallel-and and parallel-or mode to collapse
483// if-conditions and merge if-regions with identical statements.
484///
485bool llvm::FlattenCFG(BasicBlock *BB, AliasAnalysis *AA) {
486 return FlattenCFGOpt(AA).run(BB);
487}