Don't use 'using std::error_code' in include/llvm.
[oota-llvm.git] / lib / Transforms / Scalar / SimplifyCFGPass.cpp
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
24 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.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/Transforms/Utils/Local.h"
38 using namespace llvm;
39 using std::error_code;
40
41 #define DEBUG_TYPE "simplifycfg"
42
43 STATISTIC(NumSimpl, "Number of blocks simplified");
44
45 namespace {
46 struct CFGSimplifyPass : public FunctionPass {
47   static char ID; // Pass identification, replacement for typeid
48   CFGSimplifyPass() : FunctionPass(ID) {
49     initializeCFGSimplifyPassPass(*PassRegistry::getPassRegistry());
50   }
51   bool runOnFunction(Function &F) override;
52
53   void getAnalysisUsage(AnalysisUsage &AU) const override {
54     AU.addRequired<TargetTransformInfo>();
55   }
56 };
57 }
58
59 char CFGSimplifyPass::ID = 0;
60 INITIALIZE_PASS_BEGIN(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
61                       false)
62 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
63 INITIALIZE_PASS_END(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
64                     false)
65
66 // Public interface to the CFGSimplification pass
67 FunctionPass *llvm::createCFGSimplificationPass() {
68   return new CFGSimplifyPass();
69 }
70
71 /// mergeEmptyReturnBlocks - If we have more than one empty (other than phi
72 /// node) return blocks, merge them together to promote recursive block merging.
73 static bool mergeEmptyReturnBlocks(Function &F) {
74   bool Changed = false;
75
76   BasicBlock *RetBlock = nullptr;
77
78   // Scan all the blocks in the function, looking for empty return blocks.
79   for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; ) {
80     BasicBlock &BB = *BBI++;
81
82     // Only look at return blocks.
83     ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
84     if (!Ret) continue;
85
86     // Only look at the block if it is empty or the only other thing in it is a
87     // single PHI node that is the operand to the return.
88     if (Ret != &BB.front()) {
89       // Check for something else in the block.
90       BasicBlock::iterator I = Ret;
91       --I;
92       // Skip over debug info.
93       while (isa<DbgInfoIntrinsic>(I) && I != BB.begin())
94         --I;
95       if (!isa<DbgInfoIntrinsic>(I) &&
96           (!isa<PHINode>(I) || I != BB.begin() ||
97            Ret->getNumOperands() == 0 ||
98            Ret->getOperand(0) != I))
99         continue;
100     }
101
102     // If this is the first returning block, remember it and keep going.
103     if (!RetBlock) {
104       RetBlock = &BB;
105       continue;
106     }
107
108     // Otherwise, we found a duplicate return block.  Merge the two.
109     Changed = true;
110
111     // Case when there is no input to the return or when the returned values
112     // agree is trivial.  Note that they can't agree if there are phis in the
113     // blocks.
114     if (Ret->getNumOperands() == 0 ||
115         Ret->getOperand(0) ==
116           cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0)) {
117       BB.replaceAllUsesWith(RetBlock);
118       BB.eraseFromParent();
119       continue;
120     }
121
122     // If the canonical return block has no PHI node, create one now.
123     PHINode *RetBlockPHI = dyn_cast<PHINode>(RetBlock->begin());
124     if (!RetBlockPHI) {
125       Value *InVal = cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0);
126       pred_iterator PB = pred_begin(RetBlock), PE = pred_end(RetBlock);
127       RetBlockPHI = PHINode::Create(Ret->getOperand(0)->getType(),
128                                     std::distance(PB, PE), "merge",
129                                     &RetBlock->front());
130
131       for (pred_iterator PI = PB; PI != PE; ++PI)
132         RetBlockPHI->addIncoming(InVal, *PI);
133       RetBlock->getTerminator()->setOperand(0, RetBlockPHI);
134     }
135
136     // Turn BB into a block that just unconditionally branches to the return
137     // block.  This handles the case when the two return blocks have a common
138     // predecessor but that return different things.
139     RetBlockPHI->addIncoming(Ret->getOperand(0), &BB);
140     BB.getTerminator()->eraseFromParent();
141     BranchInst::Create(RetBlock, &BB);
142   }
143
144   return Changed;
145 }
146
147 /// iterativelySimplifyCFG - Call SimplifyCFG on all the blocks in the function,
148 /// iterating until no more changes are made.
149 static bool iterativelySimplifyCFG(Function &F, const TargetTransformInfo &TTI,
150                                    const DataLayout *DL) {
151   bool Changed = false;
152   bool LocalChange = true;
153   while (LocalChange) {
154     LocalChange = false;
155
156     // Loop over all of the basic blocks and remove them if they are unneeded...
157     //
158     for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
159       if (SimplifyCFG(BBIt++, TTI, DL)) {
160         LocalChange = true;
161         ++NumSimpl;
162       }
163     }
164     Changed |= LocalChange;
165   }
166   return Changed;
167 }
168
169 // It is possible that we may require multiple passes over the code to fully
170 // simplify the CFG.
171 //
172 bool CFGSimplifyPass::runOnFunction(Function &F) {
173   if (skipOptnoneFunction(F))
174     return false;
175
176   const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
177   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
178   const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
179   bool EverChanged = removeUnreachableBlocks(F);
180   EverChanged |= mergeEmptyReturnBlocks(F);
181   EverChanged |= iterativelySimplifyCFG(F, TTI, DL);
182
183   // If neither pass changed anything, we're done.
184   if (!EverChanged) return false;
185
186   // iterativelySimplifyCFG can (rarely) make some loops dead.  If this happens,
187   // removeUnreachableBlocks is needed to nuke them, which means we should
188   // iterate between the two optimizations.  We structure the code like this to
189   // avoid reruning iterativelySimplifyCFG if the second pass of
190   // removeUnreachableBlocks doesn't do anything.
191   if (!removeUnreachableBlocks(F))
192     return true;
193
194   do {
195     EverChanged = iterativelySimplifyCFG(F, TTI, DL);
196     EverChanged |= removeUnreachableBlocks(F);
197   } while (EverChanged);
198
199   return true;
200 }