12944142f5c93e3eb75075bb198b314a333c33b2
[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 - See if LazyValueInfo's ability to exploit edge conditions,
185 /// or range information is sufficient to prove this comparison.  Even for
186 /// local conditions, this can sometimes prove conditions instcombine can't by
187 /// exploiting range information.
188 bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
189   Value *Op0 = C->getOperand(0);
190   Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
191   if (!Op1) return false;
192
193   LazyValueInfo::Tristate Result =
194     LVI->getPredicateAt(C->getPredicate(), Op0, Op1, C);
195   if (Result == LazyValueInfo::Unknown) return false;
196
197   ++NumCmps;
198   if (Result == LazyValueInfo::True)
199     C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
200   else
201     C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
202   C->eraseFromParent();
203
204   return true;
205 }
206
207 /// processSwitch - Simplify a switch instruction by removing cases which can
208 /// never fire.  If the uselessness of a case could be determined locally then
209 /// constant propagation would already have figured it out.  Instead, walk the
210 /// predecessors and statically evaluate cases based on information available
211 /// on that edge.  Cases that cannot fire no matter what the incoming edge can
212 /// safely be removed.  If a case fires on every incoming edge then the entire
213 /// switch can be removed and replaced with a branch to the case destination.
214 bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
215   Value *Cond = SI->getCondition();
216   BasicBlock *BB = SI->getParent();
217
218   // If the condition was defined in same block as the switch then LazyValueInfo
219   // currently won't say anything useful about it, though in theory it could.
220   if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
221     return false;
222
223   // If the switch is unreachable then trying to improve it is a waste of time.
224   pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
225   if (PB == PE) return false;
226
227   // Analyse each switch case in turn.  This is done in reverse order so that
228   // removing a case doesn't cause trouble for the iteration.
229   bool Changed = false;
230   for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE;
231        ) {
232     ConstantInt *Case = CI.getCaseValue();
233
234     // Check to see if the switch condition is equal to/not equal to the case
235     // value on every incoming edge, equal/not equal being the same each time.
236     LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
237     for (pred_iterator PI = PB; PI != PE; ++PI) {
238       // Is the switch condition equal to the case value?
239       LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
240                                                               Cond, Case, *PI,
241                                                               BB, SI);
242       // Give up on this case if nothing is known.
243       if (Value == LazyValueInfo::Unknown) {
244         State = LazyValueInfo::Unknown;
245         break;
246       }
247
248       // If this was the first edge to be visited, record that all other edges
249       // need to give the same result.
250       if (PI == PB) {
251         State = Value;
252         continue;
253       }
254
255       // If this case is known to fire for some edges and known not to fire for
256       // others then there is nothing we can do - give up.
257       if (Value != State) {
258         State = LazyValueInfo::Unknown;
259         break;
260       }
261     }
262
263     if (State == LazyValueInfo::False) {
264       // This case never fires - remove it.
265       CI.getCaseSuccessor()->removePredecessor(BB);
266       SI->removeCase(CI); // Does not invalidate the iterator.
267
268       // The condition can be modified by removePredecessor's PHI simplification
269       // logic.
270       Cond = SI->getCondition();
271
272       ++NumDeadCases;
273       Changed = true;
274     } else if (State == LazyValueInfo::True) {
275       // This case always fires.  Arrange for the switch to be turned into an
276       // unconditional branch by replacing the switch condition with the case
277       // value.
278       SI->setCondition(Case);
279       NumDeadCases += SI->getNumCases();
280       Changed = true;
281       break;
282     }
283   }
284
285   if (Changed)
286     // If the switch has been simplified to the point where it can be replaced
287     // by a branch then do so now.
288     ConstantFoldTerminator(BB);
289
290   return Changed;
291 }
292
293 /// processCallSite - Infer nonnull attributes for the arguments at the
294 /// specified callsite.
295 bool CorrelatedValuePropagation::processCallSite(CallSite CS) {
296   bool Changed = false;
297
298   unsigned ArgNo = 0;
299   for (Value *V : CS.args()) {
300     PointerType *Type = dyn_cast<PointerType>(V->getType());
301
302     if (Type && !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
303         LVI->getPredicateAt(ICmpInst::ICMP_EQ, V,
304                             ConstantPointerNull::get(Type),
305                             CS.getInstruction()) == LazyValueInfo::False) {
306       AttributeSet AS = CS.getAttributes();
307       AS = AS.addAttribute(CS.getInstruction()->getContext(), ArgNo + 1,
308                            Attribute::NonNull);
309       CS.setAttributes(AS);
310       Changed = true;
311     }
312     ArgNo++;
313   }
314   assert(ArgNo == CS.arg_size() && "sanity check");
315
316   return Changed;
317 }
318
319 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
320   if (skipOptnoneFunction(F))
321     return false;
322
323   LVI = &getAnalysis<LazyValueInfo>();
324
325   bool FnChanged = false;
326
327   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
328     bool BBChanged = false;
329     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
330       Instruction *II = &*BI++;
331       switch (II->getOpcode()) {
332       case Instruction::Select:
333         BBChanged |= processSelect(cast<SelectInst>(II));
334         break;
335       case Instruction::PHI:
336         BBChanged |= processPHI(cast<PHINode>(II));
337         break;
338       case Instruction::ICmp:
339       case Instruction::FCmp:
340         BBChanged |= processCmp(cast<CmpInst>(II));
341         break;
342       case Instruction::Load:
343       case Instruction::Store:
344         BBChanged |= processMemAccess(II);
345         break;
346       case Instruction::Call:
347       case Instruction::Invoke:
348         BBChanged |= processCallSite(CallSite(II));
349         break;
350       }
351     }
352
353     Instruction *Term = FI->getTerminator();
354     switch (Term->getOpcode()) {
355     case Instruction::Switch:
356       BBChanged |= processSwitch(cast<SwitchInst>(Term));
357       break;
358     }
359
360     FnChanged |= BBChanged;
361   }
362
363   return FnChanged;
364 }