SimplifyCFGPass.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. //===- SimplifyCFGPass.cpp - CFG Simplification Pass ----------------------===//
  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. // This file implements dead code elimination and basic block merging, along
  11. // with a collection of other peephole control flow optimizations. For example:
  12. //
  13. // * Removes basic blocks with no predecessors.
  14. // * Merges a basic block into its predecessor if there is only one and the
  15. // predecessor only has one successor.
  16. // * Eliminates PHI nodes for basic blocks with a single predecessor.
  17. // * Eliminates a basic block that only contains an unconditional branch.
  18. // * Changes invoke instructions to nounwind functions to be calls.
  19. // * Change things like "if (x) if (y)" into "if (x&y)".
  20. // * etc..
  21. //
  22. //===----------------------------------------------------------------------===//
  23. #include "llvm/Transforms/Scalar/SimplifyCFG.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/Statistic.h"
  27. #include "llvm/Analysis/AssumptionCache.h"
  28. #include "llvm/Analysis/TargetTransformInfo.h"
  29. #include "llvm/IR/Attributes.h"
  30. #include "llvm/IR/CFG.h"
  31. #include "llvm/IR/Constants.h"
  32. #include "llvm/IR/DataLayout.h"
  33. #include "llvm/IR/Instructions.h"
  34. #include "llvm/IR/IntrinsicInst.h"
  35. #include "llvm/IR/Module.h"
  36. #include "llvm/Pass.h"
  37. #include "llvm/Support/CommandLine.h"
  38. #include "llvm/Transforms/Utils/Local.h"
  39. #include "llvm/Transforms/Scalar.h"
  40. using namespace llvm;
  41. #define DEBUG_TYPE "simplifycfg"
  42. static cl::opt<unsigned>
  43. UserBonusInstThreshold("bonus-inst-threshold", cl::Hidden, cl::init(1),
  44. cl::desc("Control the number of bonus instructions (default = 1)"));
  45. STATISTIC(NumSimpl, "Number of blocks simplified");
  46. /// If we have more than one empty (other than phi node) return blocks,
  47. /// merge them together to promote recursive block merging.
  48. static bool mergeEmptyReturnBlocks(Function &F) {
  49. bool Changed = false;
  50. BasicBlock *RetBlock = nullptr;
  51. // Scan all the blocks in the function, looking for empty return blocks.
  52. for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; ) {
  53. BasicBlock &BB = *BBI++;
  54. // Only look at return blocks.
  55. ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
  56. if (!Ret) continue;
  57. // Only look at the block if it is empty or the only other thing in it is a
  58. // single PHI node that is the operand to the return.
  59. if (Ret != &BB.front()) {
  60. // Check for something else in the block.
  61. BasicBlock::iterator I = Ret;
  62. --I;
  63. // Skip over debug info.
  64. while (isa<DbgInfoIntrinsic>(I) && I != BB.begin())
  65. --I;
  66. if (!isa<DbgInfoIntrinsic>(I) &&
  67. (!isa<PHINode>(I) || I != BB.begin() ||
  68. Ret->getNumOperands() == 0 ||
  69. Ret->getOperand(0) != I))
  70. continue;
  71. }
  72. // If this is the first returning block, remember it and keep going.
  73. if (!RetBlock) {
  74. RetBlock = &BB;
  75. continue;
  76. }
  77. // Otherwise, we found a duplicate return block. Merge the two.
  78. Changed = true;
  79. // Case when there is no input to the return or when the returned values
  80. // agree is trivial. Note that they can't agree if there are phis in the
  81. // blocks.
  82. if (Ret->getNumOperands() == 0 ||
  83. Ret->getOperand(0) ==
  84. cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0)) {
  85. BB.replaceAllUsesWith(RetBlock);
  86. BB.eraseFromParent();
  87. continue;
  88. }
  89. // If the canonical return block has no PHI node, create one now.
  90. PHINode *RetBlockPHI = dyn_cast<PHINode>(RetBlock->begin());
  91. if (!RetBlockPHI) {
  92. Value *InVal = cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0);
  93. pred_iterator PB = pred_begin(RetBlock), PE = pred_end(RetBlock);
  94. RetBlockPHI = PHINode::Create(Ret->getOperand(0)->getType(),
  95. std::distance(PB, PE), "merge",
  96. &RetBlock->front());
  97. for (pred_iterator PI = PB; PI != PE; ++PI)
  98. RetBlockPHI->addIncoming(InVal, *PI);
  99. RetBlock->getTerminator()->setOperand(0, RetBlockPHI);
  100. }
  101. // Turn BB into a block that just unconditionally branches to the return
  102. // block. This handles the case when the two return blocks have a common
  103. // predecessor but that return different things.
  104. RetBlockPHI->addIncoming(Ret->getOperand(0), &BB);
  105. BB.getTerminator()->eraseFromParent();
  106. BranchInst::Create(RetBlock, &BB);
  107. }
  108. return Changed;
  109. }
  110. /// Call SimplifyCFG on all the blocks in the function,
  111. /// iterating until no more changes are made.
  112. static bool iterativelySimplifyCFG(Function &F, const TargetTransformInfo &TTI,
  113. AssumptionCache *AC,
  114. unsigned BonusInstThreshold) {
  115. bool Changed = false;
  116. bool LocalChange = true;
  117. while (LocalChange) {
  118. LocalChange = false;
  119. // Loop over all of the basic blocks and remove them if they are unneeded.
  120. for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
  121. if (SimplifyCFG(BBIt++, TTI, BonusInstThreshold, AC)) {
  122. LocalChange = true;
  123. ++NumSimpl;
  124. }
  125. }
  126. Changed |= LocalChange;
  127. }
  128. return Changed;
  129. }
  130. static bool simplifyFunctionCFG(Function &F, const TargetTransformInfo &TTI,
  131. AssumptionCache *AC, int BonusInstThreshold) {
  132. bool EverChanged = removeUnreachableBlocks(F);
  133. EverChanged |= mergeEmptyReturnBlocks(F);
  134. EverChanged |= iterativelySimplifyCFG(F, TTI, AC, BonusInstThreshold);
  135. // If neither pass changed anything, we're done.
  136. if (!EverChanged) return false;
  137. // iterativelySimplifyCFG can (rarely) make some loops dead. If this happens,
  138. // removeUnreachableBlocks is needed to nuke them, which means we should
  139. // iterate between the two optimizations. We structure the code like this to
  140. // avoid rerunning iterativelySimplifyCFG if the second pass of
  141. // removeUnreachableBlocks doesn't do anything.
  142. if (!removeUnreachableBlocks(F))
  143. return true;
  144. do {
  145. EverChanged = iterativelySimplifyCFG(F, TTI, AC, BonusInstThreshold);
  146. EverChanged |= removeUnreachableBlocks(F);
  147. } while (EverChanged);
  148. return true;
  149. }
  150. SimplifyCFGPass::SimplifyCFGPass()
  151. : BonusInstThreshold(UserBonusInstThreshold) {}
  152. SimplifyCFGPass::SimplifyCFGPass(int BonusInstThreshold)
  153. : BonusInstThreshold(BonusInstThreshold) {}
  154. PreservedAnalyses SimplifyCFGPass::run(Function &F,
  155. AnalysisManager<Function> *AM) {
  156. auto &TTI = AM->getResult<TargetIRAnalysis>(F);
  157. auto &AC = AM->getResult<AssumptionAnalysis>(F);
  158. if (!simplifyFunctionCFG(F, TTI, &AC, BonusInstThreshold))
  159. return PreservedAnalyses::none();
  160. return PreservedAnalyses::all();
  161. }
  162. namespace {
  163. struct CFGSimplifyPass : public FunctionPass {
  164. static char ID; // Pass identification, replacement for typeid
  165. unsigned BonusInstThreshold;
  166. std::function<bool(const Function &)> PredicateFtor;
  167. CFGSimplifyPass(int T = -1,
  168. std::function<bool(const Function &)> Ftor = nullptr)
  169. : FunctionPass(ID), PredicateFtor(Ftor) {
  170. BonusInstThreshold = (T == -1) ? UserBonusInstThreshold : unsigned(T);
  171. initializeCFGSimplifyPassPass(*PassRegistry::getPassRegistry());
  172. }
  173. bool runOnFunction(Function &F) override {
  174. if (PredicateFtor && !PredicateFtor(F))
  175. return false;
  176. if (skipOptnoneFunction(F))
  177. return false;
  178. AssumptionCache *AC =
  179. &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  180. const TargetTransformInfo &TTI =
  181. getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  182. return simplifyFunctionCFG(F, TTI, AC, BonusInstThreshold);
  183. }
  184. void getAnalysisUsage(AnalysisUsage &AU) const override {
  185. AU.addRequired<AssumptionCacheTracker>();
  186. AU.addRequired<TargetTransformInfoWrapperPass>();
  187. }
  188. };
  189. }
  190. char CFGSimplifyPass::ID = 0;
  191. INITIALIZE_PASS_BEGIN(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
  192. false)
  193. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  194. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  195. INITIALIZE_PASS_END(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
  196. false)
  197. // Public interface to the CFGSimplification pass
  198. FunctionPass *
  199. llvm::createCFGSimplificationPass(int Threshold,
  200. std::function<bool(const Function &)> Ftor) {
  201. return new CFGSimplifyPass(Threshold, Ftor);
  202. }