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