Eliminate switch cases that can never match, for example removes all
[oota-llvm.git] / lib / Transforms / Scalar / CorrelatedValuePropagation.cpp
1 //===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===//
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 the Correlated Value Propagation pass.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "correlated-value-propagation"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/LazyValueInfo.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/ADT/Statistic.h"
25 using namespace llvm;
26
27 STATISTIC(NumPhis,      "Number of phis propagated");
28 STATISTIC(NumSelects,   "Number of selects propagated");
29 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
30 STATISTIC(NumCmps,      "Number of comparisons propagated");
31
32 namespace {
33   class CorrelatedValuePropagation : public FunctionPass {
34     LazyValueInfo *LVI;
35
36     bool processSelect(SelectInst *SI);
37     bool processPHI(PHINode *P);
38     bool processMemAccess(Instruction *I);
39     bool processCmp(CmpInst *C);
40     bool processSwitch(SwitchInst *SI);
41
42   public:
43     static char ID;
44     CorrelatedValuePropagation(): FunctionPass(ID) {
45      initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
46     }
47
48     bool runOnFunction(Function &F);
49
50     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51       AU.addRequired<LazyValueInfo>();
52     }
53   };
54 }
55
56 char CorrelatedValuePropagation::ID = 0;
57 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
58                 "Value Propagation", false, false)
59 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
60 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
61                 "Value Propagation", false, false)
62
63 // Public interface to the Value Propagation pass
64 Pass *llvm::createCorrelatedValuePropagationPass() {
65   return new CorrelatedValuePropagation();
66 }
67
68 bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
69   if (S->getType()->isVectorTy()) return false;
70   if (isa<Constant>(S->getOperand(0))) return false;
71
72   Constant *C = LVI->getConstant(S->getOperand(0), S->getParent());
73   if (!C) return false;
74
75   ConstantInt *CI = dyn_cast<ConstantInt>(C);
76   if (!CI) return false;
77
78   Value *ReplaceWith = S->getOperand(1);
79   Value *Other = S->getOperand(2);
80   if (!CI->isOne()) std::swap(ReplaceWith, Other);
81   if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
82
83   S->replaceAllUsesWith(ReplaceWith);
84   S->eraseFromParent();
85
86   ++NumSelects;
87
88   return true;
89 }
90
91 bool CorrelatedValuePropagation::processPHI(PHINode *P) {
92   bool Changed = false;
93
94   BasicBlock *BB = P->getParent();
95   for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
96     Value *Incoming = P->getIncomingValue(i);
97     if (isa<Constant>(Incoming)) continue;
98
99     Constant *C = LVI->getConstantOnEdge(P->getIncomingValue(i),
100                                          P->getIncomingBlock(i),
101                                          BB);
102     if (!C) continue;
103
104     P->setIncomingValue(i, C);
105     Changed = true;
106   }
107
108   if (Value *V = SimplifyInstruction(P)) {
109     P->replaceAllUsesWith(V);
110     P->eraseFromParent();
111     Changed = true;
112   }
113
114   ++NumPhis;
115
116   return Changed;
117 }
118
119 bool CorrelatedValuePropagation::processMemAccess(Instruction *I) {
120   Value *Pointer = 0;
121   if (LoadInst *L = dyn_cast<LoadInst>(I))
122     Pointer = L->getPointerOperand();
123   else
124     Pointer = cast<StoreInst>(I)->getPointerOperand();
125
126   if (isa<Constant>(Pointer)) return false;
127
128   Constant *C = LVI->getConstant(Pointer, I->getParent());
129   if (!C) return false;
130
131   ++NumMemAccess;
132   I->replaceUsesOfWith(Pointer, C);
133   return true;
134 }
135
136 /// processCmp - If the value of this comparison could be determined locally,
137 /// constant propagation would already have figured it out.  Instead, walk
138 /// the predecessors and statically evaluate the comparison based on information
139 /// available on that edge.  If a given static evaluation is true on ALL
140 /// incoming edges, then it's true universally and we can simplify the compare.
141 bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
142   Value *Op0 = C->getOperand(0);
143   if (isa<Instruction>(Op0) &&
144       cast<Instruction>(Op0)->getParent() == C->getParent())
145     return false;
146
147   Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
148   if (!Op1) return false;
149
150   pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent());
151   if (PI == PE) return false;
152
153   LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(),
154                                     C->getOperand(0), Op1, *PI, C->getParent());
155   if (Result == LazyValueInfo::Unknown) return false;
156
157   ++PI;
158   while (PI != PE) {
159     LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(),
160                                     C->getOperand(0), Op1, *PI, C->getParent());
161     if (Res != Result) return false;
162     ++PI;
163   }
164
165   ++NumCmps;
166
167   if (Result == LazyValueInfo::True)
168     C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
169   else
170     C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
171
172   C->eraseFromParent();
173
174   return true;
175 }
176
177 /// processSwitch - Simplify a switch instruction by removing cases which can
178 /// never fire.  If the uselessness of a case could be determined locally then
179 /// constant propagation would already have figured it out.  Instead, walk the
180 /// predecessors and statically evaluate cases based on information available
181 /// on that edge.  Cases that cannot fire no matter what the incoming edge can
182 /// safely be removed.  If a case fires on every incoming edge then the entire
183 /// switch can be removed and replaced with a branch to the case destination.
184 bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
185   Value *Cond = SI->getCondition();
186   BasicBlock *BB = SI->getParent();
187
188   // If the condition was defined in same block as the switch then LazyValueInfo
189   // currently won't say anything useful about it, though in theory it could.
190   if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
191     return false;
192
193   // If the switch is unreachable then trying to improve it is a waste of time.
194   pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
195   if (PB == PE) return false;
196
197   // Analyse each switch case in turn.  This is done in reverse order so that
198   // removing a case doesn't cause trouble for the iteration.
199   bool Changed = false;
200   for (SwitchInst::CaseIt CI = SI->caseEnd(), CE = SI->caseBegin(); CI-- != CE;
201        ) {
202     ConstantInt *Case = CI.getCaseValue();
203
204     // Check to see if the switch condition is equal to/not equal to the case
205     // value on every incoming edge, equal/not equal being the same each time.
206     LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
207     for (pred_iterator PI = PB; PI != PE; ++PI) {
208       // Is the switch condition equal to the case value?
209       LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
210                                                               Cond, Case, *PI, BB);
211       // Give up on this case if nothing is known.
212       if (Value == LazyValueInfo::Unknown) {
213         State = LazyValueInfo::Unknown;
214         break;
215       }
216
217       // If this was the first edge to be visited, record that all other edges
218       // need to give the same result.
219       if (PI == PB) {
220         State = Value;
221         continue;
222       }
223
224       // If this case is known to fire for some edges and known not to fire for
225       // others then there is nothing we can do - give up.
226       if (Value != State) {
227         State = LazyValueInfo::Unknown;
228         break;
229       }
230     }
231
232     if (State == LazyValueInfo::False) {
233       // This case never fires - remove it.
234       CI.getCaseSuccessor()->removePredecessor(BB);
235       SI->removeCase(CI); // Does not invalidate the iterator.
236       Changed = true;
237     } else if (State == LazyValueInfo::True) {
238       // This case always fires.  Arrange for the switch to be turned into an
239       // unconditional branch by replacing the switch condition with the case
240       // value.
241       SI->setCondition(Case);
242       Changed = true;
243       break;
244     }
245   }
246
247   if (Changed)
248     // If the switch has been simplified to the point where it can be replaced
249     // by a branch then do so now.
250     ConstantFoldTerminator(BB);
251
252   return Changed;
253 }
254
255 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
256   LVI = &getAnalysis<LazyValueInfo>();
257
258   bool FnChanged = false;
259
260   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
261     bool BBChanged = false;
262     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
263       Instruction *II = BI++;
264       switch (II->getOpcode()) {
265       case Instruction::Select:
266         BBChanged |= processSelect(cast<SelectInst>(II));
267         break;
268       case Instruction::PHI:
269         BBChanged |= processPHI(cast<PHINode>(II));
270         break;
271       case Instruction::ICmp:
272       case Instruction::FCmp:
273         BBChanged |= processCmp(cast<CmpInst>(II));
274         break;
275       case Instruction::Load:
276       case Instruction::Store:
277         BBChanged |= processMemAccess(II);
278         break;
279       }
280     }
281
282     Instruction *Term = FI->getTerminator();
283     switch (Term->getOpcode()) {
284     case Instruction::Switch:
285       BBChanged |= processSwitch(cast<SwitchInst>(Term));
286       break;
287     }
288
289     FnChanged |= BBChanged;
290   }
291
292   return FnChanged;
293 }