e6acbdf1602502fae88ab88957736b846748cc47
[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 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/GlobalsModRef.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/LazyValueInfo.h"
19 #include "llvm/IR/CFG.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Transforms/Utils/Local.h"
28 using namespace llvm;
29
30 #define DEBUG_TYPE "correlated-value-propagation"
31
32 STATISTIC(NumPhis,      "Number of phis propagated");
33 STATISTIC(NumSelects,   "Number of selects propagated");
34 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
35 STATISTIC(NumCmps,      "Number of comparisons propagated");
36 STATISTIC(NumDeadCases, "Number of switch cases removed");
37
38 namespace {
39   class CorrelatedValuePropagation : public FunctionPass {
40     LazyValueInfo *LVI;
41
42     bool processSelect(SelectInst *SI);
43     bool processPHI(PHINode *P);
44     bool processMemAccess(Instruction *I);
45     bool processCmp(CmpInst *C);
46     bool processSwitch(SwitchInst *SI);
47     bool processCallSite(CallSite CS);
48
49   public:
50     static char ID;
51     CorrelatedValuePropagation(): FunctionPass(ID) {
52      initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
53     }
54
55     bool runOnFunction(Function &F) override;
56
57     void getAnalysisUsage(AnalysisUsage &AU) const override {
58       AU.addRequired<LazyValueInfo>();
59       AU.addPreserved<GlobalsAAWrapperPass>();
60     }
61   };
62 }
63
64 char CorrelatedValuePropagation::ID = 0;
65 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
66                 "Value Propagation", false, false)
67 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
68 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
69                 "Value Propagation", false, false)
70
71 // Public interface to the Value Propagation pass
72 Pass *llvm::createCorrelatedValuePropagationPass() {
73   return new CorrelatedValuePropagation();
74 }
75
76 bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
77   if (S->getType()->isVectorTy()) return false;
78   if (isa<Constant>(S->getOperand(0))) return false;
79
80   Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S);
81   if (!C) return false;
82
83   ConstantInt *CI = dyn_cast<ConstantInt>(C);
84   if (!CI) return false;
85
86   Value *ReplaceWith = S->getOperand(1);
87   Value *Other = S->getOperand(2);
88   if (!CI->isOne()) std::swap(ReplaceWith, Other);
89   if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
90
91   S->replaceAllUsesWith(ReplaceWith);
92   S->eraseFromParent();
93
94   ++NumSelects;
95
96   return true;
97 }
98
99 bool CorrelatedValuePropagation::processPHI(PHINode *P) {
100   bool Changed = false;
101
102   BasicBlock *BB = P->getParent();
103   for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
104     Value *Incoming = P->getIncomingValue(i);
105     if (isa<Constant>(Incoming)) continue;
106
107     Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P);
108
109     // Look if the incoming value is a select with a scalar condition for which
110     // LVI can tells us the value. In that case replace the incoming value with
111     // the appropriate value of the select. This often allows us to remove the
112     // select later.
113     if (!V) {
114       SelectInst *SI = dyn_cast<SelectInst>(Incoming);
115       if (!SI) continue;
116
117       Value *Condition = SI->getCondition();
118       if (!Condition->getType()->isVectorTy()) {
119         if (Constant *C = LVI->getConstantOnEdge(
120                 Condition, P->getIncomingBlock(i), BB, P)) {
121           if (C->isOneValue()) {
122             V = SI->getTrueValue();
123           } else if (C->isZeroValue()) {
124             V = SI->getFalseValue();
125           }
126           // Once LVI learns to handle vector types, we could also add support
127           // for vector type constants that are not all zeroes or all ones.
128         }
129       }
130
131       // Look if the select has a constant but LVI tells us that the incoming
132       // value can never be that constant. In that case replace the incoming
133       // value with the other value of the select. This often allows us to
134       // remove the select later.
135       if (!V) {
136         Constant *C = dyn_cast<Constant>(SI->getFalseValue());
137         if (!C) continue;
138
139         if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
140               P->getIncomingBlock(i), BB, P) !=
141             LazyValueInfo::False)
142           continue;
143         V = SI->getTrueValue();
144       }
145
146       DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
147     }
148
149     P->setIncomingValue(i, V);
150     Changed = true;
151   }
152
153   // FIXME: Provide TLI, DT, AT to SimplifyInstruction.
154   const DataLayout &DL = BB->getModule()->getDataLayout();
155   if (Value *V = SimplifyInstruction(P, DL)) {
156     P->replaceAllUsesWith(V);
157     P->eraseFromParent();
158     Changed = true;
159   }
160
161   if (Changed)
162     ++NumPhis;
163
164   return Changed;
165 }
166
167 bool CorrelatedValuePropagation::processMemAccess(Instruction *I) {
168   Value *Pointer = nullptr;
169   if (LoadInst *L = dyn_cast<LoadInst>(I))
170     Pointer = L->getPointerOperand();
171   else
172     Pointer = cast<StoreInst>(I)->getPointerOperand();
173
174   if (isa<Constant>(Pointer)) return false;
175
176   Constant *C = LVI->getConstant(Pointer, I->getParent(), I);
177   if (!C) return false;
178
179   ++NumMemAccess;
180   I->replaceUsesOfWith(Pointer, C);
181   return true;
182 }
183
184 /// processCmp - If the value of this comparison could be determined locally,
185 /// constant propagation would already have figured it out.  Instead, walk
186 /// the predecessors and statically evaluate the comparison based on information
187 /// available on that edge.  If a given static evaluation is true on ALL
188 /// incoming edges, then it's true universally and we can simplify the compare.
189 bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
190   Value *Op0 = C->getOperand(0);
191   if (isa<Instruction>(Op0) &&
192       cast<Instruction>(Op0)->getParent() == C->getParent())
193     return false;
194
195   Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
196   if (!Op1) return false;
197
198   pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent());
199   if (PI == PE) return false;
200
201   LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(),
202                                     C->getOperand(0), Op1, *PI,
203                                     C->getParent(), C);
204   if (Result == LazyValueInfo::Unknown) return false;
205
206   ++PI;
207   while (PI != PE) {
208     LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(),
209                                     C->getOperand(0), Op1, *PI,
210                                     C->getParent(), C);
211     if (Res != Result) return false;
212     ++PI;
213   }
214
215   ++NumCmps;
216
217   if (Result == LazyValueInfo::True)
218     C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
219   else
220     C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
221
222   C->eraseFromParent();
223
224   return true;
225 }
226
227 /// processSwitch - Simplify a switch instruction by removing cases which can
228 /// never fire.  If the uselessness of a case could be determined locally then
229 /// constant propagation would already have figured it out.  Instead, walk the
230 /// predecessors and statically evaluate cases based on information available
231 /// on that edge.  Cases that cannot fire no matter what the incoming edge can
232 /// safely be removed.  If a case fires on every incoming edge then the entire
233 /// switch can be removed and replaced with a branch to the case destination.
234 bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
235   Value *Cond = SI->getCondition();
236   BasicBlock *BB = SI->getParent();
237
238   // If the condition was defined in same block as the switch then LazyValueInfo
239   // currently won't say anything useful about it, though in theory it could.
240   if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
241     return false;
242
243   // If the switch is unreachable then trying to improve it is a waste of time.
244   pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
245   if (PB == PE) return false;
246
247   // Analyse each switch case in turn.  This is done in reverse order so that
248   // removing a case doesn't cause trouble for the iteration.
249   bool Changed = false;
250   for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE;
251        ) {
252     ConstantInt *Case = CI.getCaseValue();
253
254     // Check to see if the switch condition is equal to/not equal to the case
255     // value on every incoming edge, equal/not equal being the same each time.
256     LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
257     for (pred_iterator PI = PB; PI != PE; ++PI) {
258       // Is the switch condition equal to the case value?
259       LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
260                                                               Cond, Case, *PI,
261                                                               BB, SI);
262       // Give up on this case if nothing is known.
263       if (Value == LazyValueInfo::Unknown) {
264         State = LazyValueInfo::Unknown;
265         break;
266       }
267
268       // If this was the first edge to be visited, record that all other edges
269       // need to give the same result.
270       if (PI == PB) {
271         State = Value;
272         continue;
273       }
274
275       // If this case is known to fire for some edges and known not to fire for
276       // others then there is nothing we can do - give up.
277       if (Value != State) {
278         State = LazyValueInfo::Unknown;
279         break;
280       }
281     }
282
283     if (State == LazyValueInfo::False) {
284       // This case never fires - remove it.
285       CI.getCaseSuccessor()->removePredecessor(BB);
286       SI->removeCase(CI); // Does not invalidate the iterator.
287
288       // The condition can be modified by removePredecessor's PHI simplification
289       // logic.
290       Cond = SI->getCondition();
291
292       ++NumDeadCases;
293       Changed = true;
294     } else if (State == LazyValueInfo::True) {
295       // This case always fires.  Arrange for the switch to be turned into an
296       // unconditional branch by replacing the switch condition with the case
297       // value.
298       SI->setCondition(Case);
299       NumDeadCases += SI->getNumCases();
300       Changed = true;
301       break;
302     }
303   }
304
305   if (Changed)
306     // If the switch has been simplified to the point where it can be replaced
307     // by a branch then do so now.
308     ConstantFoldTerminator(BB);
309
310   return Changed;
311 }
312
313 /// processCallSite - Infer nonnull attributes for the arguments at the
314 /// specified callsite.
315 bool CorrelatedValuePropagation::processCallSite(CallSite CS) {
316   bool Changed = false;
317
318   unsigned ArgNo = 0;
319   for (Value *V : CS.args()) {
320     PointerType *Type = dyn_cast<PointerType>(V->getType());
321
322     if (Type && !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
323         LVI->getPredicateAt(ICmpInst::ICMP_EQ, V,
324                             ConstantPointerNull::get(Type),
325                             CS.getInstruction()) == LazyValueInfo::False) {
326       AttributeSet AS = CS.getAttributes();
327       AS = AS.addAttribute(CS.getInstruction()->getContext(), ArgNo + 1,
328                            Attribute::NonNull);
329       CS.setAttributes(AS);
330       Changed = true;
331     }
332     ArgNo++;
333   }
334   assert(ArgNo == CS.arg_size() && "sanity check");
335
336   return Changed;
337 }
338
339 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
340   if (skipOptnoneFunction(F))
341     return false;
342
343   LVI = &getAnalysis<LazyValueInfo>();
344
345   bool FnChanged = false;
346
347   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
348     bool BBChanged = false;
349     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
350       Instruction *II = &*BI++;
351       switch (II->getOpcode()) {
352       case Instruction::Select:
353         BBChanged |= processSelect(cast<SelectInst>(II));
354         break;
355       case Instruction::PHI:
356         BBChanged |= processPHI(cast<PHINode>(II));
357         break;
358       case Instruction::ICmp:
359       case Instruction::FCmp:
360         BBChanged |= processCmp(cast<CmpInst>(II));
361         break;
362       case Instruction::Load:
363       case Instruction::Store:
364         BBChanged |= processMemAccess(II);
365         break;
366       case Instruction::Call:
367       case Instruction::Invoke:
368         BBChanged |= processCallSite(CallSite(II));
369         break;
370       }
371     }
372
373     Instruction *Term = FI->getTerminator();
374     switch (Term->getOpcode()) {
375     case Instruction::Switch:
376       BBChanged |= processSwitch(cast<SwitchInst>(Term));
377       break;
378     }
379
380     FnChanged |= BBChanged;
381   }
382
383   return FnChanged;
384 }