FlattenCFG.cpp 15 KB

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