LLVM  3.7.0
SimplifyCFGPass.cpp
Go to the documentation of this file.
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 
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/CFG.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/Pass.h"
40 #include "llvm/Transforms/Scalar.h"
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "simplifycfg"
44 
45 static cl::opt<unsigned>
46 UserBonusInstThreshold("bonus-inst-threshold", cl::Hidden, cl::init(1),
47  cl::desc("Control the number of bonus instructions (default = 1)"));
48 
49 STATISTIC(NumSimpl, "Number of blocks simplified");
50 
51 /// If we have more than one empty (other than phi node) return blocks,
52 /// merge them together to promote recursive block merging.
54  bool Changed = false;
55 
56  BasicBlock *RetBlock = nullptr;
57 
58  // Scan all the blocks in the function, looking for empty return blocks.
59  for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; ) {
60  BasicBlock &BB = *BBI++;
61 
62  // Only look at return blocks.
64  if (!Ret) continue;
65 
66  // Only look at the block if it is empty or the only other thing in it is a
67  // single PHI node that is the operand to the return.
68  if (Ret != &BB.front()) {
69  // Check for something else in the block.
71  --I;
72  // Skip over debug info.
73  while (isa<DbgInfoIntrinsic>(I) && I != BB.begin())
74  --I;
75  if (!isa<DbgInfoIntrinsic>(I) &&
76  (!isa<PHINode>(I) || I != BB.begin() ||
77  Ret->getNumOperands() == 0 ||
78  Ret->getOperand(0) != I))
79  continue;
80  }
81 
82  // If this is the first returning block, remember it and keep going.
83  if (!RetBlock) {
84  RetBlock = &BB;
85  continue;
86  }
87 
88  // Otherwise, we found a duplicate return block. Merge the two.
89  Changed = true;
90 
91  // Case when there is no input to the return or when the returned values
92  // agree is trivial. Note that they can't agree if there are phis in the
93  // blocks.
94  if (Ret->getNumOperands() == 0 ||
95  Ret->getOperand(0) ==
96  cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0)) {
97  BB.replaceAllUsesWith(RetBlock);
98  BB.eraseFromParent();
99  continue;
100  }
101 
102  // If the canonical return block has no PHI node, create one now.
103  PHINode *RetBlockPHI = dyn_cast<PHINode>(RetBlock->begin());
104  if (!RetBlockPHI) {
105  Value *InVal = cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0);
106  pred_iterator PB = pred_begin(RetBlock), PE = pred_end(RetBlock);
107  RetBlockPHI = PHINode::Create(Ret->getOperand(0)->getType(),
108  std::distance(PB, PE), "merge",
109  &RetBlock->front());
110 
111  for (pred_iterator PI = PB; PI != PE; ++PI)
112  RetBlockPHI->addIncoming(InVal, *PI);
113  RetBlock->getTerminator()->setOperand(0, RetBlockPHI);
114  }
115 
116  // Turn BB into a block that just unconditionally branches to the return
117  // block. This handles the case when the two return blocks have a common
118  // predecessor but that return different things.
119  RetBlockPHI->addIncoming(Ret->getOperand(0), &BB);
121  BranchInst::Create(RetBlock, &BB);
122  }
123 
124  return Changed;
125 }
126 
127 /// Call SimplifyCFG on all the blocks in the function,
128 /// iterating until no more changes are made.
130  AssumptionCache *AC,
131  unsigned BonusInstThreshold) {
132  bool Changed = false;
133  bool LocalChange = true;
134  while (LocalChange) {
135  LocalChange = false;
136 
137  // Loop over all of the basic blocks and remove them if they are unneeded.
138  for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
139  if (SimplifyCFG(BBIt++, TTI, BonusInstThreshold, AC)) {
140  LocalChange = true;
141  ++NumSimpl;
142  }
143  }
144  Changed |= LocalChange;
145  }
146  return Changed;
147 }
148 
150  AssumptionCache *AC, int BonusInstThreshold) {
151  bool EverChanged = removeUnreachableBlocks(F);
152  EverChanged |= mergeEmptyReturnBlocks(F);
153  EverChanged |= iterativelySimplifyCFG(F, TTI, AC, BonusInstThreshold);
154 
155  // If neither pass changed anything, we're done.
156  if (!EverChanged) return false;
157 
158  // iterativelySimplifyCFG can (rarely) make some loops dead. If this happens,
159  // removeUnreachableBlocks is needed to nuke them, which means we should
160  // iterate between the two optimizations. We structure the code like this to
161  // avoid rerunning iterativelySimplifyCFG if the second pass of
162  // removeUnreachableBlocks doesn't do anything.
163  if (!removeUnreachableBlocks(F))
164  return true;
165 
166  do {
167  EverChanged = iterativelySimplifyCFG(F, TTI, AC, BonusInstThreshold);
168  EverChanged |= removeUnreachableBlocks(F);
169  } while (EverChanged);
170 
171  return true;
172 }
173 
175  : BonusInstThreshold(UserBonusInstThreshold) {}
176 
177 SimplifyCFGPass::SimplifyCFGPass(int BonusInstThreshold)
178  : BonusInstThreshold(BonusInstThreshold) {}
179 
182  auto &TTI = AM->getResult<TargetIRAnalysis>(F);
183  auto &AC = AM->getResult<AssumptionAnalysis>(F);
184 
185  if (!simplifyFunctionCFG(F, TTI, &AC, BonusInstThreshold))
186  return PreservedAnalyses::none();
187 
188  return PreservedAnalyses::all();
189 }
190 
191 namespace {
192 struct CFGSimplifyPass : public FunctionPass {
193  static char ID; // Pass identification, replacement for typeid
194  unsigned BonusInstThreshold;
195  std::function<bool(const Function &)> PredicateFtor;
196 
197  CFGSimplifyPass(int T = -1,
198  std::function<bool(const Function &)> Ftor = nullptr)
199  : FunctionPass(ID), PredicateFtor(Ftor) {
200  BonusInstThreshold = (T == -1) ? UserBonusInstThreshold : unsigned(T);
202  }
203  bool runOnFunction(Function &F) override {
204  if (PredicateFtor && !PredicateFtor(F))
205  return false;
206 
207  if (skipOptnoneFunction(F))
208  return false;
209 
210  AssumptionCache *AC =
211  &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
212  const TargetTransformInfo &TTI =
213  getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
214  return simplifyFunctionCFG(F, TTI, AC, BonusInstThreshold);
215  }
216 
217  void getAnalysisUsage(AnalysisUsage &AU) const override {
220  }
221 };
222 }
223 
224 char CFGSimplifyPass::ID = 0;
225 INITIALIZE_PASS_BEGIN(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
226  false)
229 INITIALIZE_PASS_END(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
230  false)
231 
232 // Public interface to the CFGSimplification pass
233 FunctionPass *
235  std::function<bool(const Function &)> Ftor) {
236  return new CFGSimplifyPass(Threshold, Ftor);
237 }
238 
This file provides the interface for the pass responsible for both simplifying and canonicalizing the...
ReturnInst - Return a value (possibly void), from a function.
iplist< Instruction >::iterator eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing basic block and deletes it...
Definition: Instruction.cpp:70
void addIncoming(Value *V, BasicBlock *BB)
addIncoming - Add an incoming value to the end of the PHI list
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
STATISTIC(NumFunctions,"Total number of functions")
iterator end()
Definition: Function.h:459
unsigned getNumOperands() const
Definition: User.h:138
An immutable pass that tracks lazily created AssumptionCache objects.
static cl::opt< unsigned > UserBonusInstThreshold("bonus-inst-threshold", cl::Hidden, cl::init(1), cl::desc("Control the number of bonus instructions (default = 1)"))
static bool simplifyFunctionCFG(Function &F, const TargetTransformInfo &TTI, AssumptionCache *AC, int BonusInstThreshold)
A cache of .assume calls within a function.
Analysis pass providing the TargetTransformInfo.
const Instruction & front() const
Definition: BasicBlock.h:243
F(f)
Simplify the CFG
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:231
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:70
Simplify the false
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:75
This file contains the simple types necessary to represent the attributes associated with functions a...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:351
iterator begin()
Definition: Function.h:457
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:88
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:325
simplifycfg
Wrapper pass for TargetTransformInfo.
An abstract set of preserved analyses following a transformation pass run.
Definition: PassManager.h:69
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
This file contains the declarations for the subclasses of Constant, which represent the different fla...
FunctionPass * createCFGSimplificationPass(int Threshold=-1, std::function< bool(const Function &)> Ftor=nullptr)
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:114
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:294
Value * getOperand(unsigned i) const
Definition: User.h:118
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:117
bool SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, unsigned BonusInstThreshold, AssumptionCache *AC=nullptr)
SimplifyCFG - This function is used to do simplification of a CFG.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:91
A function analysis which provides an AssumptionCache.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:222
PassT::Result & getResult(IRUnitT &IR)
Get the result of an analysis pass for this module.
Definition: PassManager.h:311
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
void setOperand(unsigned i, Value *Val)
Definition: User.h:122
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:285
PreservedAnalyses run(Function &F, AnalysisManager< Function > *AM)
Run the pass over the function.
iplist< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
Definition: BasicBlock.cpp:97
#define I(x, y, z)
Definition: MD5.cpp:54
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:124
INITIALIZE_PASS_BEGIN(CFGSimplifyPass,"simplifycfg","Simplify the CFG", false, false) INITIALIZE_PASS_END(CFGSimplifyPass
static bool mergeEmptyReturnBlocks(Function &F)
If we have more than one empty (other than phi node) return blocks, merge them together to promote re...
static int const Threshold
TODO: Write a new FunctionPass AliasAnalysis so that it can keep a cache.
void initializeCFGSimplifyPassPass(PassRegistry &)
aarch64 promote const
SimplifyCFGPass()
Construct a pass with the default thresholds.
LLVM Value Representation.
Definition: Value.h:69
print Print MemDeps of function
bool removeUnreachableBlocks(Function &F)
Remove all blocks that can not be reached from the function's entry.
Definition: Local.cpp:1254
A generic analysis pass manager with lazy running and caching of results.
This pass exposes codegen information to IR-level passes.
static bool iterativelySimplifyCFG(Function &F, const TargetTransformInfo &TTI, AssumptionCache *AC, unsigned BonusInstThreshold)
Call SimplifyCFG on all the blocks in the function, iterating until no more changes are made...