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