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/CorrelatedValuePropagation.h"
15#include "llvm/Transforms/Scalar.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/Analysis/GlobalsModRef.h"
18#include "llvm/Analysis/InstructionSimplify.h"
19#include "llvm/Analysis/LazyValueInfo.h"
20#include "llvm/IR/CFG.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/Function.h"
23#include "llvm/IR/Instructions.h"
24#include "llvm/IR/Module.h"
25#include "llvm/Pass.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Transforms/Utils/Local.h"
29using namespace llvm;
30
31#define DEBUG_TYPE "correlated-value-propagation"
32
33STATISTIC(NumPhis,      "Number of phis propagated");
34STATISTIC(NumSelects,   "Number of selects propagated");
35STATISTIC(NumMemAccess, "Number of memory access targets propagated");
36STATISTIC(NumCmps,      "Number of comparisons propagated");
37STATISTIC(NumReturns,   "Number of return values propagated");
38STATISTIC(NumDeadCases, "Number of switch cases removed");
39STATISTIC(NumSDivs,     "Number of sdiv converted to udiv");
40STATISTIC(NumSRems,     "Number of srem converted to urem");
41
42namespace {
43  class CorrelatedValuePropagation : public FunctionPass {
44  public:
45    static char ID;
46    CorrelatedValuePropagation(): FunctionPass(ID) {
47     initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
48    }
49
50    bool runOnFunction(Function &F) override;
51
52    void getAnalysisUsage(AnalysisUsage &AU) const override {
53      AU.addRequired<LazyValueInfoWrapperPass>();
54      AU.addPreserved<GlobalsAAWrapperPass>();
55    }
56  };
57}
58
59char CorrelatedValuePropagation::ID = 0;
60INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
61                "Value Propagation", false, false)
62INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
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
71static bool processSelect(SelectInst *S, LazyValueInfo *LVI) {
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(), S);
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
94static bool processPHI(PHINode *P, LazyValueInfo *LVI) {
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, P);
103
104    // Look if the incoming value is a select with a scalar condition for which
105    // LVI can tells us the value. In that case replace the incoming value with
106    // the appropriate value of the select. This often allows us to remove the
107    // select later.
108    if (!V) {
109      SelectInst *SI = dyn_cast<SelectInst>(Incoming);
110      if (!SI) continue;
111
112      Value *Condition = SI->getCondition();
113      if (!Condition->getType()->isVectorTy()) {
114        if (Constant *C = LVI->getConstantOnEdge(
115                Condition, P->getIncomingBlock(i), BB, P)) {
116          if (C->isOneValue()) {
117            V = SI->getTrueValue();
118          } else if (C->isZeroValue()) {
119            V = SI->getFalseValue();
120          }
121          // Once LVI learns to handle vector types, we could also add support
122          // for vector type constants that are not all zeroes or all ones.
123        }
124      }
125
126      // Look if the select has a constant but LVI tells us that the incoming
127      // value can never be that constant. In that case replace the incoming
128      // value with the other value of the select. This often allows us to
129      // remove the select later.
130      if (!V) {
131        Constant *C = dyn_cast<Constant>(SI->getFalseValue());
132        if (!C) continue;
133
134        if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
135              P->getIncomingBlock(i), BB, P) !=
136            LazyValueInfo::False)
137          continue;
138        V = SI->getTrueValue();
139      }
140
141      DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
142    }
143
144    P->setIncomingValue(i, V);
145    Changed = true;
146  }
147
148  // FIXME: Provide TLI, DT, AT to SimplifyInstruction.
149  const DataLayout &DL = BB->getModule()->getDataLayout();
150  if (Value *V = SimplifyInstruction(P, DL)) {
151    P->replaceAllUsesWith(V);
152    P->eraseFromParent();
153    Changed = true;
154  }
155
156  if (Changed)
157    ++NumPhis;
158
159  return Changed;
160}
161
162static bool processMemAccess(Instruction *I, LazyValueInfo *LVI) {
163  Value *Pointer = nullptr;
164  if (LoadInst *L = dyn_cast<LoadInst>(I))
165    Pointer = L->getPointerOperand();
166  else
167    Pointer = cast<StoreInst>(I)->getPointerOperand();
168
169  if (isa<Constant>(Pointer)) return false;
170
171  Constant *C = LVI->getConstant(Pointer, I->getParent(), I);
172  if (!C) return false;
173
174  ++NumMemAccess;
175  I->replaceUsesOfWith(Pointer, C);
176  return true;
177}
178
179/// See if LazyValueInfo's ability to exploit edge conditions or range
180/// information is sufficient to prove this comparison. Even for local
181/// conditions, this can sometimes prove conditions instcombine can't by
182/// exploiting range information.
183static bool processCmp(CmpInst *C, LazyValueInfo *LVI) {
184  Value *Op0 = C->getOperand(0);
185  Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
186  if (!Op1) return false;
187
188  // As a policy choice, we choose not to waste compile time on anything where
189  // the comparison is testing local values.  While LVI can sometimes reason
190  // about such cases, it's not its primary purpose.  We do make sure to do
191  // the block local query for uses from terminator instructions, but that's
192  // handled in the code for each terminator.
193  auto *I = dyn_cast<Instruction>(Op0);
194  if (I && I->getParent() == C->getParent())
195    return false;
196
197  LazyValueInfo::Tristate Result =
198    LVI->getPredicateAt(C->getPredicate(), Op0, Op1, C);
199  if (Result == LazyValueInfo::Unknown) return false;
200
201  ++NumCmps;
202  if (Result == LazyValueInfo::True)
203    C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
204  else
205    C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
206  C->eraseFromParent();
207
208  return true;
209}
210
211/// Simplify a switch instruction by removing cases which can never fire. If the
212/// uselessness of a case could be determined locally then constant propagation
213/// would already have figured it out. Instead, walk the predecessors and
214/// statically evaluate cases based on information available on that edge. Cases
215/// that cannot fire no matter what the incoming edge can safely be removed. If
216/// a case fires on every incoming edge then the entire switch can be removed
217/// and replaced with a branch to the case destination.
218static bool processSwitch(SwitchInst *SI, LazyValueInfo *LVI) {
219  Value *Cond = SI->getCondition();
220  BasicBlock *BB = SI->getParent();
221
222  // If the condition was defined in same block as the switch then LazyValueInfo
223  // currently won't say anything useful about it, though in theory it could.
224  if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
225    return false;
226
227  // If the switch is unreachable then trying to improve it is a waste of time.
228  pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
229  if (PB == PE) return false;
230
231  // Analyse each switch case in turn.  This is done in reverse order so that
232  // removing a case doesn't cause trouble for the iteration.
233  bool Changed = false;
234  for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE;
235       ) {
236    ConstantInt *Case = CI.getCaseValue();
237
238    // Check to see if the switch condition is equal to/not equal to the case
239    // value on every incoming edge, equal/not equal being the same each time.
240    LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
241    for (pred_iterator PI = PB; PI != PE; ++PI) {
242      // Is the switch condition equal to the case value?
243      LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
244                                                              Cond, Case, *PI,
245                                                              BB, SI);
246      // Give up on this case if nothing is known.
247      if (Value == LazyValueInfo::Unknown) {
248        State = LazyValueInfo::Unknown;
249        break;
250      }
251
252      // If this was the first edge to be visited, record that all other edges
253      // need to give the same result.
254      if (PI == PB) {
255        State = Value;
256        continue;
257      }
258
259      // If this case is known to fire for some edges and known not to fire for
260      // others then there is nothing we can do - give up.
261      if (Value != State) {
262        State = LazyValueInfo::Unknown;
263        break;
264      }
265    }
266
267    if (State == LazyValueInfo::False) {
268      // This case never fires - remove it.
269      CI.getCaseSuccessor()->removePredecessor(BB);
270      SI->removeCase(CI); // Does not invalidate the iterator.
271
272      // The condition can be modified by removePredecessor's PHI simplification
273      // logic.
274      Cond = SI->getCondition();
275
276      ++NumDeadCases;
277      Changed = true;
278    } else if (State == LazyValueInfo::True) {
279      // This case always fires.  Arrange for the switch to be turned into an
280      // unconditional branch by replacing the switch condition with the case
281      // value.
282      SI->setCondition(Case);
283      NumDeadCases += SI->getNumCases();
284      Changed = true;
285      break;
286    }
287  }
288
289  if (Changed)
290    // If the switch has been simplified to the point where it can be replaced
291    // by a branch then do so now.
292    ConstantFoldTerminator(BB);
293
294  return Changed;
295}
296
297/// Infer nonnull attributes for the arguments at the specified callsite.
298static bool processCallSite(CallSite CS, LazyValueInfo *LVI) {
299  SmallVector<unsigned, 4> Indices;
300  unsigned ArgNo = 0;
301
302  for (Value *V : CS.args()) {
303    PointerType *Type = dyn_cast<PointerType>(V->getType());
304    // Try to mark pointer typed parameters as non-null.  We skip the
305    // relatively expensive analysis for constants which are obviously either
306    // null or non-null to start with.
307    if (Type && !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
308        !isa<Constant>(V) &&
309        LVI->getPredicateAt(ICmpInst::ICMP_EQ, V,
310                            ConstantPointerNull::get(Type),
311                            CS.getInstruction()) == LazyValueInfo::False)
312      Indices.push_back(ArgNo + 1);
313    ArgNo++;
314  }
315
316  assert(ArgNo == CS.arg_size() && "sanity check");
317
318  if (Indices.empty())
319    return false;
320
321  AttributeSet AS = CS.getAttributes();
322  LLVMContext &Ctx = CS.getInstruction()->getContext();
323  AS = AS.addAttribute(Ctx, Indices, Attribute::get(Ctx, Attribute::NonNull));
324  CS.setAttributes(AS);
325
326  return true;
327}
328
329// Helper function to rewrite srem and sdiv. As a policy choice, we choose not
330// to waste compile time on anything where the operands are local defs.  While
331// LVI can sometimes reason about such cases, it's not its primary purpose.
332static bool hasLocalDefs(BinaryOperator *SDI) {
333  for (Value *O : SDI->operands()) {
334    auto *I = dyn_cast<Instruction>(O);
335    if (I && I->getParent() == SDI->getParent())
336      return true;
337  }
338  return false;
339}
340
341static bool hasPositiveOperands(BinaryOperator *SDI, LazyValueInfo *LVI) {
342  Constant *Zero = ConstantInt::get(SDI->getType(), 0);
343  for (Value *O : SDI->operands()) {
344    auto Result = LVI->getPredicateAt(ICmpInst::ICMP_SGE, O, Zero, SDI);
345    if (Result != LazyValueInfo::True)
346      return false;
347  }
348  return true;
349}
350
351static bool processSRem(BinaryOperator *SDI, LazyValueInfo *LVI) {
352  if (SDI->getType()->isVectorTy() || hasLocalDefs(SDI) ||
353      !hasPositiveOperands(SDI, LVI))
354    return false;
355
356  ++NumSRems;
357  auto *BO = BinaryOperator::CreateURem(SDI->getOperand(0), SDI->getOperand(1),
358                                        SDI->getName(), SDI);
359  SDI->replaceAllUsesWith(BO);
360  SDI->eraseFromParent();
361  return true;
362}
363
364/// See if LazyValueInfo's ability to exploit edge conditions or range
365/// information is sufficient to prove the both operands of this SDiv are
366/// positive.  If this is the case, replace the SDiv with a UDiv. Even for local
367/// conditions, this can sometimes prove conditions instcombine can't by
368/// exploiting range information.
369static bool processSDiv(BinaryOperator *SDI, LazyValueInfo *LVI) {
370  if (SDI->getType()->isVectorTy() || hasLocalDefs(SDI) ||
371      !hasPositiveOperands(SDI, LVI))
372    return false;
373
374  ++NumSDivs;
375  auto *BO = BinaryOperator::CreateUDiv(SDI->getOperand(0), SDI->getOperand(1),
376                                        SDI->getName(), SDI);
377  BO->setIsExact(SDI->isExact());
378  SDI->replaceAllUsesWith(BO);
379  SDI->eraseFromParent();
380
381  return true;
382}
383
384static Constant *getConstantAt(Value *V, Instruction *At, LazyValueInfo *LVI) {
385  if (Constant *C = LVI->getConstant(V, At->getParent(), At))
386    return C;
387
388  // TODO: The following really should be sunk inside LVI's core algorithm, or
389  // at least the outer shims around such.
390  auto *C = dyn_cast<CmpInst>(V);
391  if (!C) return nullptr;
392
393  Value *Op0 = C->getOperand(0);
394  Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
395  if (!Op1) return nullptr;
396
397  LazyValueInfo::Tristate Result =
398    LVI->getPredicateAt(C->getPredicate(), Op0, Op1, At);
399  if (Result == LazyValueInfo::Unknown)
400    return nullptr;
401
402  return (Result == LazyValueInfo::True) ?
403    ConstantInt::getTrue(C->getContext()) :
404    ConstantInt::getFalse(C->getContext());
405}
406
407static bool runImpl(Function &F, LazyValueInfo *LVI) {
408  bool FnChanged = false;
409
410  for (BasicBlock &BB : F) {
411    bool BBChanged = false;
412    for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
413      Instruction *II = &*BI++;
414      switch (II->getOpcode()) {
415      case Instruction::Select:
416        BBChanged |= processSelect(cast<SelectInst>(II), LVI);
417        break;
418      case Instruction::PHI:
419        BBChanged |= processPHI(cast<PHINode>(II), LVI);
420        break;
421      case Instruction::ICmp:
422      case Instruction::FCmp:
423        BBChanged |= processCmp(cast<CmpInst>(II), LVI);
424        break;
425      case Instruction::Load:
426      case Instruction::Store:
427        BBChanged |= processMemAccess(II, LVI);
428        break;
429      case Instruction::Call:
430      case Instruction::Invoke:
431        BBChanged |= processCallSite(CallSite(II), LVI);
432        break;
433      case Instruction::SRem:
434        BBChanged |= processSRem(cast<BinaryOperator>(II), LVI);
435        break;
436      case Instruction::SDiv:
437        BBChanged |= processSDiv(cast<BinaryOperator>(II), LVI);
438        break;
439      }
440    }
441
442    Instruction *Term = BB.getTerminator();
443    switch (Term->getOpcode()) {
444    case Instruction::Switch:
445      BBChanged |= processSwitch(cast<SwitchInst>(Term), LVI);
446      break;
447    case Instruction::Ret: {
448      auto *RI = cast<ReturnInst>(Term);
449      // Try to determine the return value if we can.  This is mainly here to
450      // simplify the writing of unit tests, but also helps to enable IPO by
451      // constant folding the return values of callees.
452      auto *RetVal = RI->getReturnValue();
453      if (!RetVal) break; // handle "ret void"
454      if (isa<Constant>(RetVal)) break; // nothing to do
455      if (auto *C = getConstantAt(RetVal, RI, LVI)) {
456        ++NumReturns;
457        RI->replaceUsesOfWith(RetVal, C);
458        BBChanged = true;
459      }
460    }
461    };
462
463    FnChanged |= BBChanged;
464  }
465
466  return FnChanged;
467}
468
469bool CorrelatedValuePropagation::runOnFunction(Function &F) {
470  if (skipFunction(F))
471    return false;
472
473  LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
474  return runImpl(F, LVI);
475}
476
477PreservedAnalyses
478CorrelatedValuePropagationPass::run(Function &F, FunctionAnalysisManager &AM) {
479
480  LazyValueInfo *LVI = &AM.getResult<LazyValueAnalysis>(F);
481  bool Changed = runImpl(F, LVI);
482
483  // FIXME: We need to invalidate LVI to avoid PR28400. Is there a better
484  // solution?
485  AM.invalidate<LazyValueAnalysis>(F);
486
487  if (!Changed)
488    return PreservedAnalyses::all();
489  PreservedAnalyses PA;
490  PA.preserve<GlobalsAA>();
491  return PA;
492}
493