1 //===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Correlated Value Propagation pass.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
14 #include "llvm/ADT/DepthFirstIterator.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/DomTreeUpdater.h"
19 #include "llvm/Analysis/GlobalsModRef.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/LazyValueInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/Attributes.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/Constant.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/InstrTypes.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/IR/PassManager.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/InitializePasses.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Transforms/Scalar.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include <cassert>
49 #include <utility>
50 
51 using namespace llvm;
52 
53 #define DEBUG_TYPE "correlated-value-propagation"
54 
55 STATISTIC(NumPhis,      "Number of phis propagated");
56 STATISTIC(NumPhiCommon, "Number of phis deleted via common incoming value");
57 STATISTIC(NumSelects,   "Number of selects propagated");
58 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
59 STATISTIC(NumCmps,      "Number of comparisons propagated");
60 STATISTIC(NumReturns,   "Number of return values propagated");
61 STATISTIC(NumDeadCases, "Number of switch cases removed");
62 STATISTIC(NumSDivSRemsNarrowed,
63           "Number of sdivs/srems whose width was decreased");
64 STATISTIC(NumSDivs,     "Number of sdiv converted to udiv");
65 STATISTIC(NumUDivURemsNarrowed,
66           "Number of udivs/urems whose width was decreased");
67 STATISTIC(NumAShrs,     "Number of ashr converted to lshr");
68 STATISTIC(NumSRems,     "Number of srem converted to urem");
69 STATISTIC(NumSExt,      "Number of sext converted to zext");
70 STATISTIC(NumSICmps,    "Number of signed icmp preds simplified to unsigned");
71 STATISTIC(NumAnd,       "Number of ands removed");
72 STATISTIC(NumNW,        "Number of no-wrap deductions");
73 STATISTIC(NumNSW,       "Number of no-signed-wrap deductions");
74 STATISTIC(NumNUW,       "Number of no-unsigned-wrap deductions");
75 STATISTIC(NumAddNW,     "Number of no-wrap deductions for add");
76 STATISTIC(NumAddNSW,    "Number of no-signed-wrap deductions for add");
77 STATISTIC(NumAddNUW,    "Number of no-unsigned-wrap deductions for add");
78 STATISTIC(NumSubNW,     "Number of no-wrap deductions for sub");
79 STATISTIC(NumSubNSW,    "Number of no-signed-wrap deductions for sub");
80 STATISTIC(NumSubNUW,    "Number of no-unsigned-wrap deductions for sub");
81 STATISTIC(NumMulNW,     "Number of no-wrap deductions for mul");
82 STATISTIC(NumMulNSW,    "Number of no-signed-wrap deductions for mul");
83 STATISTIC(NumMulNUW,    "Number of no-unsigned-wrap deductions for mul");
84 STATISTIC(NumShlNW,     "Number of no-wrap deductions for shl");
85 STATISTIC(NumShlNSW,    "Number of no-signed-wrap deductions for shl");
86 STATISTIC(NumShlNUW,    "Number of no-unsigned-wrap deductions for shl");
87 STATISTIC(NumAbs,       "Number of llvm.abs intrinsics removed");
88 STATISTIC(NumOverflows, "Number of overflow checks removed");
89 STATISTIC(NumSaturating,
90     "Number of saturating arithmetics converted to normal arithmetics");
91 STATISTIC(NumNonNull, "Number of function pointer arguments marked non-null");
92 STATISTIC(NumMinMax, "Number of llvm.[us]{min,max} intrinsics removed");
93 
94 namespace {
95 
96   class CorrelatedValuePropagation : public FunctionPass {
97   public:
98     static char ID;
99 
100     CorrelatedValuePropagation(): FunctionPass(ID) {
101      initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
102     }
103 
104     bool runOnFunction(Function &F) override;
105 
106     void getAnalysisUsage(AnalysisUsage &AU) const override {
107       AU.addRequired<DominatorTreeWrapperPass>();
108       AU.addRequired<LazyValueInfoWrapperPass>();
109       AU.addPreserved<GlobalsAAWrapperPass>();
110       AU.addPreserved<DominatorTreeWrapperPass>();
111       AU.addPreserved<LazyValueInfoWrapperPass>();
112     }
113   };
114 
115 } // end anonymous namespace
116 
117 char CorrelatedValuePropagation::ID = 0;
118 
119 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
120                 "Value Propagation", false, false)
121 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
122 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
123 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
124                 "Value Propagation", false, false)
125 
126 // Public interface to the Value Propagation pass
127 Pass *llvm::createCorrelatedValuePropagationPass() {
128   return new CorrelatedValuePropagation();
129 }
130 
131 static bool processSelect(SelectInst *S, LazyValueInfo *LVI) {
132   if (S->getType()->isVectorTy()) return false;
133   if (isa<Constant>(S->getCondition())) return false;
134 
135   Constant *C = LVI->getConstant(S->getCondition(), S);
136   if (!C) return false;
137 
138   ConstantInt *CI = dyn_cast<ConstantInt>(C);
139   if (!CI) return false;
140 
141   Value *ReplaceWith = CI->isOne() ? S->getTrueValue() : S->getFalseValue();
142   S->replaceAllUsesWith(ReplaceWith);
143   S->eraseFromParent();
144 
145   ++NumSelects;
146 
147   return true;
148 }
149 
150 /// Try to simplify a phi with constant incoming values that match the edge
151 /// values of a non-constant value on all other edges:
152 /// bb0:
153 ///   %isnull = icmp eq i8* %x, null
154 ///   br i1 %isnull, label %bb2, label %bb1
155 /// bb1:
156 ///   br label %bb2
157 /// bb2:
158 ///   %r = phi i8* [ %x, %bb1 ], [ null, %bb0 ]
159 /// -->
160 ///   %r = %x
161 static bool simplifyCommonValuePhi(PHINode *P, LazyValueInfo *LVI,
162                                    DominatorTree *DT) {
163   // Collect incoming constants and initialize possible common value.
164   SmallVector<std::pair<Constant *, unsigned>, 4> IncomingConstants;
165   Value *CommonValue = nullptr;
166   for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
167     Value *Incoming = P->getIncomingValue(i);
168     if (auto *IncomingConstant = dyn_cast<Constant>(Incoming)) {
169       IncomingConstants.push_back(std::make_pair(IncomingConstant, i));
170     } else if (!CommonValue) {
171       // The potential common value is initialized to the first non-constant.
172       CommonValue = Incoming;
173     } else if (Incoming != CommonValue) {
174       // There can be only one non-constant common value.
175       return false;
176     }
177   }
178 
179   if (!CommonValue || IncomingConstants.empty())
180     return false;
181 
182   // The common value must be valid in all incoming blocks.
183   BasicBlock *ToBB = P->getParent();
184   if (auto *CommonInst = dyn_cast<Instruction>(CommonValue))
185     if (!DT->dominates(CommonInst, ToBB))
186       return false;
187 
188   // We have a phi with exactly 1 variable incoming value and 1 or more constant
189   // incoming values. See if all constant incoming values can be mapped back to
190   // the same incoming variable value.
191   for (auto &IncomingConstant : IncomingConstants) {
192     Constant *C = IncomingConstant.first;
193     BasicBlock *IncomingBB = P->getIncomingBlock(IncomingConstant.second);
194     if (C != LVI->getConstantOnEdge(CommonValue, IncomingBB, ToBB, P))
195       return false;
196   }
197 
198   // LVI only guarantees that the value matches a certain constant if the value
199   // is not poison. Make sure we don't replace a well-defined value with poison.
200   // This is usually satisfied due to a prior branch on the value.
201   if (!isGuaranteedNotToBePoison(CommonValue, nullptr, P, DT))
202     return false;
203 
204   // All constant incoming values map to the same variable along the incoming
205   // edges of the phi. The phi is unnecessary.
206   P->replaceAllUsesWith(CommonValue);
207   P->eraseFromParent();
208   ++NumPhiCommon;
209   return true;
210 }
211 
212 static bool processPHI(PHINode *P, LazyValueInfo *LVI, DominatorTree *DT,
213                        const SimplifyQuery &SQ) {
214   bool Changed = false;
215 
216   BasicBlock *BB = P->getParent();
217   for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
218     Value *Incoming = P->getIncomingValue(i);
219     if (isa<Constant>(Incoming)) continue;
220 
221     Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P);
222 
223     // Look if the incoming value is a select with a scalar condition for which
224     // LVI can tells us the value. In that case replace the incoming value with
225     // the appropriate value of the select. This often allows us to remove the
226     // select later.
227     if (!V) {
228       SelectInst *SI = dyn_cast<SelectInst>(Incoming);
229       if (!SI) continue;
230 
231       Value *Condition = SI->getCondition();
232       if (!Condition->getType()->isVectorTy()) {
233         if (Constant *C = LVI->getConstantOnEdge(
234                 Condition, P->getIncomingBlock(i), BB, P)) {
235           if (C->isOneValue()) {
236             V = SI->getTrueValue();
237           } else if (C->isZeroValue()) {
238             V = SI->getFalseValue();
239           }
240           // Once LVI learns to handle vector types, we could also add support
241           // for vector type constants that are not all zeroes or all ones.
242         }
243       }
244 
245       // Look if the select has a constant but LVI tells us that the incoming
246       // value can never be that constant. In that case replace the incoming
247       // value with the other value of the select. This often allows us to
248       // remove the select later.
249       if (!V) {
250         Constant *C = dyn_cast<Constant>(SI->getFalseValue());
251         if (!C) continue;
252 
253         if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
254               P->getIncomingBlock(i), BB, P) !=
255             LazyValueInfo::False)
256           continue;
257         V = SI->getTrueValue();
258       }
259 
260       LLVM_DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
261     }
262 
263     P->setIncomingValue(i, V);
264     Changed = true;
265   }
266 
267   if (Value *V = SimplifyInstruction(P, SQ)) {
268     P->replaceAllUsesWith(V);
269     P->eraseFromParent();
270     Changed = true;
271   }
272 
273   if (!Changed)
274     Changed = simplifyCommonValuePhi(P, LVI, DT);
275 
276   if (Changed)
277     ++NumPhis;
278 
279   return Changed;
280 }
281 
282 static bool processMemAccess(Instruction *I, LazyValueInfo *LVI) {
283   Value *Pointer = nullptr;
284   if (LoadInst *L = dyn_cast<LoadInst>(I))
285     Pointer = L->getPointerOperand();
286   else
287     Pointer = cast<StoreInst>(I)->getPointerOperand();
288 
289   if (isa<Constant>(Pointer)) return false;
290 
291   Constant *C = LVI->getConstant(Pointer, I);
292   if (!C) return false;
293 
294   ++NumMemAccess;
295   I->replaceUsesOfWith(Pointer, C);
296   return true;
297 }
298 
299 static bool processICmp(ICmpInst *Cmp, LazyValueInfo *LVI) {
300   // Only for signed relational comparisons of scalar integers.
301   if (Cmp->getType()->isVectorTy() ||
302       !Cmp->getOperand(0)->getType()->isIntegerTy())
303     return false;
304 
305   if (!Cmp->isSigned())
306     return false;
307 
308   ICmpInst::Predicate UnsignedPred =
309       ConstantRange::getEquivalentPredWithFlippedSignedness(
310           Cmp->getPredicate(), LVI->getConstantRange(Cmp->getOperand(0), Cmp),
311           LVI->getConstantRange(Cmp->getOperand(1), Cmp));
312 
313   if (UnsignedPred == ICmpInst::Predicate::BAD_ICMP_PREDICATE)
314     return false;
315 
316   ++NumSICmps;
317   Cmp->setPredicate(UnsignedPred);
318 
319   return true;
320 }
321 
322 /// See if LazyValueInfo's ability to exploit edge conditions or range
323 /// information is sufficient to prove this comparison. Even for local
324 /// conditions, this can sometimes prove conditions instcombine can't by
325 /// exploiting range information.
326 static bool constantFoldCmp(CmpInst *Cmp, LazyValueInfo *LVI) {
327   Value *Op0 = Cmp->getOperand(0);
328   auto *C = dyn_cast<Constant>(Cmp->getOperand(1));
329   if (!C)
330     return false;
331 
332   LazyValueInfo::Tristate Result =
333       LVI->getPredicateAt(Cmp->getPredicate(), Op0, C, Cmp,
334                           /*UseBlockValue=*/true);
335   if (Result == LazyValueInfo::Unknown)
336     return false;
337 
338   ++NumCmps;
339   Constant *TorF = ConstantInt::get(Type::getInt1Ty(Cmp->getContext()), Result);
340   Cmp->replaceAllUsesWith(TorF);
341   Cmp->eraseFromParent();
342   return true;
343 }
344 
345 static bool processCmp(CmpInst *Cmp, LazyValueInfo *LVI) {
346   if (constantFoldCmp(Cmp, LVI))
347     return true;
348 
349   if (auto *ICmp = dyn_cast<ICmpInst>(Cmp))
350     if (processICmp(ICmp, LVI))
351       return true;
352 
353   return false;
354 }
355 
356 /// Simplify a switch instruction by removing cases which can never fire. If the
357 /// uselessness of a case could be determined locally then constant propagation
358 /// would already have figured it out. Instead, walk the predecessors and
359 /// statically evaluate cases based on information available on that edge. Cases
360 /// that cannot fire no matter what the incoming edge can safely be removed. If
361 /// a case fires on every incoming edge then the entire switch can be removed
362 /// and replaced with a branch to the case destination.
363 static bool processSwitch(SwitchInst *I, LazyValueInfo *LVI,
364                           DominatorTree *DT) {
365   DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy);
366   Value *Cond = I->getCondition();
367   BasicBlock *BB = I->getParent();
368 
369   // Analyse each switch case in turn.
370   bool Changed = false;
371   DenseMap<BasicBlock*, int> SuccessorsCount;
372   for (auto *Succ : successors(BB))
373     SuccessorsCount[Succ]++;
374 
375   { // Scope for SwitchInstProfUpdateWrapper. It must not live during
376     // ConstantFoldTerminator() as the underlying SwitchInst can be changed.
377     SwitchInstProfUpdateWrapper SI(*I);
378 
379     APInt Low =
380         APInt::getSignedMaxValue(Cond->getType()->getScalarSizeInBits());
381     APInt High =
382         APInt::getSignedMinValue(Cond->getType()->getScalarSizeInBits());
383 
384     SwitchInst::CaseIt CI = SI->case_begin();
385     for (auto CE = SI->case_end(); CI != CE;) {
386       ConstantInt *Case = CI->getCaseValue();
387       LazyValueInfo::Tristate State =
388           LVI->getPredicateAt(CmpInst::ICMP_EQ, Cond, Case, I,
389                               /* UseBlockValue */ true);
390 
391       if (State == LazyValueInfo::False) {
392         // This case never fires - remove it.
393         BasicBlock *Succ = CI->getCaseSuccessor();
394         Succ->removePredecessor(BB);
395         CI = SI.removeCase(CI);
396         CE = SI->case_end();
397 
398         // The condition can be modified by removePredecessor's PHI simplification
399         // logic.
400         Cond = SI->getCondition();
401 
402         ++NumDeadCases;
403         Changed = true;
404         if (--SuccessorsCount[Succ] == 0)
405           DTU.applyUpdatesPermissive({{DominatorTree::Delete, BB, Succ}});
406         continue;
407       }
408       if (State == LazyValueInfo::True) {
409         // This case always fires.  Arrange for the switch to be turned into an
410         // unconditional branch by replacing the switch condition with the case
411         // value.
412         SI->setCondition(Case);
413         NumDeadCases += SI->getNumCases();
414         Changed = true;
415         break;
416       }
417 
418       // Get Lower/Upper bound from switch cases.
419       Low = APIntOps::smin(Case->getValue(), Low);
420       High = APIntOps::smax(Case->getValue(), High);
421 
422       // Increment the case iterator since we didn't delete it.
423       ++CI;
424     }
425 
426     // Try to simplify default case as unreachable
427     if (CI == SI->case_end() && SI->getNumCases() != 0 &&
428         !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg())) {
429       const ConstantRange SIRange =
430           LVI->getConstantRange(SI->getCondition(), SI);
431 
432       // If the numbered switch cases cover the entire range of the condition,
433       // then the default case is not reachable.
434       if (SIRange.getSignedMin() == Low && SIRange.getSignedMax() == High &&
435           SI->getNumCases() == High - Low + 1) {
436         createUnreachableSwitchDefault(SI, &DTU);
437         Changed = true;
438       }
439     }
440   }
441 
442   if (Changed)
443     // If the switch has been simplified to the point where it can be replaced
444     // by a branch then do so now.
445     ConstantFoldTerminator(BB, /*DeleteDeadConditions = */ false,
446                            /*TLI = */ nullptr, &DTU);
447   return Changed;
448 }
449 
450 // See if we can prove that the given binary op intrinsic will not overflow.
451 static bool willNotOverflow(BinaryOpIntrinsic *BO, LazyValueInfo *LVI) {
452   ConstantRange LRange = LVI->getConstantRange(BO->getLHS(), BO);
453   ConstantRange RRange = LVI->getConstantRange(BO->getRHS(), BO);
454   ConstantRange NWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
455       BO->getBinaryOp(), RRange, BO->getNoWrapKind());
456   return NWRegion.contains(LRange);
457 }
458 
459 static void setDeducedOverflowingFlags(Value *V, Instruction::BinaryOps Opcode,
460                                        bool NewNSW, bool NewNUW) {
461   Statistic *OpcNW, *OpcNSW, *OpcNUW;
462   switch (Opcode) {
463   case Instruction::Add:
464     OpcNW = &NumAddNW;
465     OpcNSW = &NumAddNSW;
466     OpcNUW = &NumAddNUW;
467     break;
468   case Instruction::Sub:
469     OpcNW = &NumSubNW;
470     OpcNSW = &NumSubNSW;
471     OpcNUW = &NumSubNUW;
472     break;
473   case Instruction::Mul:
474     OpcNW = &NumMulNW;
475     OpcNSW = &NumMulNSW;
476     OpcNUW = &NumMulNUW;
477     break;
478   case Instruction::Shl:
479     OpcNW = &NumShlNW;
480     OpcNSW = &NumShlNSW;
481     OpcNUW = &NumShlNUW;
482     break;
483   default:
484     llvm_unreachable("Will not be called with other binops");
485   }
486 
487   auto *Inst = dyn_cast<Instruction>(V);
488   if (NewNSW) {
489     ++NumNW;
490     ++*OpcNW;
491     ++NumNSW;
492     ++*OpcNSW;
493     if (Inst)
494       Inst->setHasNoSignedWrap();
495   }
496   if (NewNUW) {
497     ++NumNW;
498     ++*OpcNW;
499     ++NumNUW;
500     ++*OpcNUW;
501     if (Inst)
502       Inst->setHasNoUnsignedWrap();
503   }
504 }
505 
506 static bool processBinOp(BinaryOperator *BinOp, LazyValueInfo *LVI);
507 
508 // See if @llvm.abs argument is alays positive/negative, and simplify.
509 // Notably, INT_MIN can belong to either range, regardless of the NSW,
510 // because it is negation-invariant.
511 static bool processAbsIntrinsic(IntrinsicInst *II, LazyValueInfo *LVI) {
512   Value *X = II->getArgOperand(0);
513   bool IsIntMinPoison = cast<ConstantInt>(II->getArgOperand(1))->isOne();
514 
515   Type *Ty = X->getType();
516   Constant *IntMin =
517       ConstantInt::get(Ty, APInt::getSignedMinValue(Ty->getScalarSizeInBits()));
518   LazyValueInfo::Tristate Result;
519 
520   // Is X in [0, IntMin]?  NOTE: INT_MIN is fine!
521   Result = LVI->getPredicateAt(CmpInst::Predicate::ICMP_ULE, X, IntMin, II,
522                                /*UseBlockValue=*/true);
523   if (Result == LazyValueInfo::True) {
524     ++NumAbs;
525     II->replaceAllUsesWith(X);
526     II->eraseFromParent();
527     return true;
528   }
529 
530   // Is X in [IntMin, 0]?  NOTE: INT_MIN is fine!
531   Constant *Zero = ConstantInt::getNullValue(Ty);
532   Result = LVI->getPredicateAt(CmpInst::Predicate::ICMP_SLE, X, Zero, II,
533                                /*UseBlockValue=*/true);
534   assert(Result != LazyValueInfo::False && "Should have been handled already.");
535 
536   if (Result == LazyValueInfo::Unknown) {
537     // Argument's range crosses zero.
538     bool Changed = false;
539     if (!IsIntMinPoison) {
540       // Can we at least tell that the argument is never INT_MIN?
541       Result = LVI->getPredicateAt(CmpInst::Predicate::ICMP_NE, X, IntMin, II,
542                                    /*UseBlockValue=*/true);
543       if (Result == LazyValueInfo::True) {
544         ++NumNSW;
545         ++NumSubNSW;
546         II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
547         Changed = true;
548       }
549     }
550     return Changed;
551   }
552 
553   IRBuilder<> B(II);
554   Value *NegX = B.CreateNeg(X, II->getName(), /*HasNUW=*/false,
555                             /*HasNSW=*/IsIntMinPoison);
556   ++NumAbs;
557   II->replaceAllUsesWith(NegX);
558   II->eraseFromParent();
559 
560   // See if we can infer some no-wrap flags.
561   if (auto *BO = dyn_cast<BinaryOperator>(NegX))
562     processBinOp(BO, LVI);
563 
564   return true;
565 }
566 
567 // See if this min/max intrinsic always picks it's one specific operand.
568 static bool processMinMaxIntrinsic(MinMaxIntrinsic *MM, LazyValueInfo *LVI) {
569   CmpInst::Predicate Pred = CmpInst::getNonStrictPredicate(MM->getPredicate());
570   LazyValueInfo::Tristate Result = LVI->getPredicateAt(
571       Pred, MM->getLHS(), MM->getRHS(), MM, /*UseBlockValue=*/true);
572   if (Result == LazyValueInfo::Unknown)
573     return false;
574 
575   ++NumMinMax;
576   MM->replaceAllUsesWith(MM->getOperand(!Result));
577   MM->eraseFromParent();
578   return true;
579 }
580 
581 // Rewrite this with.overflow intrinsic as non-overflowing.
582 static bool processOverflowIntrinsic(WithOverflowInst *WO, LazyValueInfo *LVI) {
583   IRBuilder<> B(WO);
584   Instruction::BinaryOps Opcode = WO->getBinaryOp();
585   bool NSW = WO->isSigned();
586   bool NUW = !WO->isSigned();
587 
588   Value *NewOp =
589       B.CreateBinOp(Opcode, WO->getLHS(), WO->getRHS(), WO->getName());
590   setDeducedOverflowingFlags(NewOp, Opcode, NSW, NUW);
591 
592   StructType *ST = cast<StructType>(WO->getType());
593   Constant *Struct = ConstantStruct::get(ST,
594       { UndefValue::get(ST->getElementType(0)),
595         ConstantInt::getFalse(ST->getElementType(1)) });
596   Value *NewI = B.CreateInsertValue(Struct, NewOp, 0);
597   WO->replaceAllUsesWith(NewI);
598   WO->eraseFromParent();
599   ++NumOverflows;
600 
601   // See if we can infer the other no-wrap too.
602   if (auto *BO = dyn_cast<BinaryOperator>(NewOp))
603     processBinOp(BO, LVI);
604 
605   return true;
606 }
607 
608 static bool processSaturatingInst(SaturatingInst *SI, LazyValueInfo *LVI) {
609   Instruction::BinaryOps Opcode = SI->getBinaryOp();
610   bool NSW = SI->isSigned();
611   bool NUW = !SI->isSigned();
612   BinaryOperator *BinOp = BinaryOperator::Create(
613       Opcode, SI->getLHS(), SI->getRHS(), SI->getName(), SI);
614   BinOp->setDebugLoc(SI->getDebugLoc());
615   setDeducedOverflowingFlags(BinOp, Opcode, NSW, NUW);
616 
617   SI->replaceAllUsesWith(BinOp);
618   SI->eraseFromParent();
619   ++NumSaturating;
620 
621   // See if we can infer the other no-wrap too.
622   if (auto *BO = dyn_cast<BinaryOperator>(BinOp))
623     processBinOp(BO, LVI);
624 
625   return true;
626 }
627 
628 /// Infer nonnull attributes for the arguments at the specified callsite.
629 static bool processCallSite(CallBase &CB, LazyValueInfo *LVI) {
630 
631   if (CB.getIntrinsicID() == Intrinsic::abs) {
632     return processAbsIntrinsic(&cast<IntrinsicInst>(CB), LVI);
633   }
634 
635   if (auto *MM = dyn_cast<MinMaxIntrinsic>(&CB)) {
636     return processMinMaxIntrinsic(MM, LVI);
637   }
638 
639   if (auto *WO = dyn_cast<WithOverflowInst>(&CB)) {
640     if (WO->getLHS()->getType()->isIntegerTy() && willNotOverflow(WO, LVI)) {
641       return processOverflowIntrinsic(WO, LVI);
642     }
643   }
644 
645   if (auto *SI = dyn_cast<SaturatingInst>(&CB)) {
646     if (SI->getType()->isIntegerTy() && willNotOverflow(SI, LVI)) {
647       return processSaturatingInst(SI, LVI);
648     }
649   }
650 
651   bool Changed = false;
652 
653   // Deopt bundle operands are intended to capture state with minimal
654   // perturbance of the code otherwise.  If we can find a constant value for
655   // any such operand and remove a use of the original value, that's
656   // desireable since it may allow further optimization of that value (e.g. via
657   // single use rules in instcombine).  Since deopt uses tend to,
658   // idiomatically, appear along rare conditional paths, it's reasonable likely
659   // we may have a conditional fact with which LVI can fold.
660   if (auto DeoptBundle = CB.getOperandBundle(LLVMContext::OB_deopt)) {
661     for (const Use &ConstU : DeoptBundle->Inputs) {
662       Use &U = const_cast<Use&>(ConstU);
663       Value *V = U.get();
664       if (V->getType()->isVectorTy()) continue;
665       if (isa<Constant>(V)) continue;
666 
667       Constant *C = LVI->getConstant(V, &CB);
668       if (!C) continue;
669       U.set(C);
670       Changed = true;
671     }
672   }
673 
674   SmallVector<unsigned, 4> ArgNos;
675   unsigned ArgNo = 0;
676 
677   for (Value *V : CB.args()) {
678     PointerType *Type = dyn_cast<PointerType>(V->getType());
679     // Try to mark pointer typed parameters as non-null.  We skip the
680     // relatively expensive analysis for constants which are obviously either
681     // null or non-null to start with.
682     if (Type && !CB.paramHasAttr(ArgNo, Attribute::NonNull) &&
683         !isa<Constant>(V) &&
684         LVI->getPredicateAt(ICmpInst::ICMP_EQ, V,
685                             ConstantPointerNull::get(Type), &CB,
686                             /*UseBlockValue=*/false) == LazyValueInfo::False)
687       ArgNos.push_back(ArgNo);
688     ArgNo++;
689   }
690 
691   assert(ArgNo == CB.arg_size() && "sanity check");
692 
693   if (ArgNos.empty())
694     return Changed;
695 
696   NumNonNull += ArgNos.size();
697   AttributeList AS = CB.getAttributes();
698   LLVMContext &Ctx = CB.getContext();
699   AS = AS.addParamAttribute(Ctx, ArgNos,
700                             Attribute::get(Ctx, Attribute::NonNull));
701   CB.setAttributes(AS);
702 
703   return true;
704 }
705 
706 static bool isNonNegative(Value *V, LazyValueInfo *LVI, Instruction *CxtI) {
707   Constant *Zero = ConstantInt::get(V->getType(), 0);
708   auto Result = LVI->getPredicateAt(ICmpInst::ICMP_SGE, V, Zero, CxtI,
709                                     /*UseBlockValue=*/true);
710   return Result == LazyValueInfo::True;
711 }
712 
713 static bool isNonPositive(Value *V, LazyValueInfo *LVI, Instruction *CxtI) {
714   Constant *Zero = ConstantInt::get(V->getType(), 0);
715   auto Result = LVI->getPredicateAt(ICmpInst::ICMP_SLE, V, Zero, CxtI,
716                                     /*UseBlockValue=*/true);
717   return Result == LazyValueInfo::True;
718 }
719 
720 enum class Domain { NonNegative, NonPositive, Unknown };
721 
722 Domain getDomain(Value *V, LazyValueInfo *LVI, Instruction *CxtI) {
723   if (isNonNegative(V, LVI, CxtI))
724     return Domain::NonNegative;
725   if (isNonPositive(V, LVI, CxtI))
726     return Domain::NonPositive;
727   return Domain::Unknown;
728 }
729 
730 /// Try to shrink a sdiv/srem's width down to the smallest power of two that's
731 /// sufficient to contain its operands.
732 static bool narrowSDivOrSRem(BinaryOperator *Instr, LazyValueInfo *LVI) {
733   assert(Instr->getOpcode() == Instruction::SDiv ||
734          Instr->getOpcode() == Instruction::SRem);
735   if (Instr->getType()->isVectorTy())
736     return false;
737 
738   // Find the smallest power of two bitwidth that's sufficient to hold Instr's
739   // operands.
740   unsigned OrigWidth = Instr->getType()->getIntegerBitWidth();
741 
742   // What is the smallest bit width that can accomodate the entire value ranges
743   // of both of the operands?
744   std::array<Optional<ConstantRange>, 2> CRs;
745   unsigned MinSignedBits = 0;
746   for (auto I : zip(Instr->operands(), CRs)) {
747     std::get<1>(I) = LVI->getConstantRange(std::get<0>(I), Instr);
748     MinSignedBits = std::max(std::get<1>(I)->getMinSignedBits(), MinSignedBits);
749   }
750 
751   // sdiv/srem is UB if divisor is -1 and divident is INT_MIN, so unless we can
752   // prove that such a combination is impossible, we need to bump the bitwidth.
753   if (CRs[1]->contains(APInt::getAllOnes(OrigWidth)) &&
754       CRs[0]->contains(
755           APInt::getSignedMinValue(MinSignedBits).sextOrSelf(OrigWidth)))
756     ++MinSignedBits;
757 
758   // Don't shrink below 8 bits wide.
759   unsigned NewWidth = std::max<unsigned>(PowerOf2Ceil(MinSignedBits), 8);
760 
761   // NewWidth might be greater than OrigWidth if OrigWidth is not a power of
762   // two.
763   if (NewWidth >= OrigWidth)
764     return false;
765 
766   ++NumSDivSRemsNarrowed;
767   IRBuilder<> B{Instr};
768   auto *TruncTy = Type::getIntNTy(Instr->getContext(), NewWidth);
769   auto *LHS = B.CreateTruncOrBitCast(Instr->getOperand(0), TruncTy,
770                                      Instr->getName() + ".lhs.trunc");
771   auto *RHS = B.CreateTruncOrBitCast(Instr->getOperand(1), TruncTy,
772                                      Instr->getName() + ".rhs.trunc");
773   auto *BO = B.CreateBinOp(Instr->getOpcode(), LHS, RHS, Instr->getName());
774   auto *Sext = B.CreateSExt(BO, Instr->getType(), Instr->getName() + ".sext");
775   if (auto *BinOp = dyn_cast<BinaryOperator>(BO))
776     if (BinOp->getOpcode() == Instruction::SDiv)
777       BinOp->setIsExact(Instr->isExact());
778 
779   Instr->replaceAllUsesWith(Sext);
780   Instr->eraseFromParent();
781   return true;
782 }
783 
784 /// Try to shrink a udiv/urem's width down to the smallest power of two that's
785 /// sufficient to contain its operands.
786 static bool processUDivOrURem(BinaryOperator *Instr, LazyValueInfo *LVI) {
787   assert(Instr->getOpcode() == Instruction::UDiv ||
788          Instr->getOpcode() == Instruction::URem);
789   if (Instr->getType()->isVectorTy())
790     return false;
791 
792   // Find the smallest power of two bitwidth that's sufficient to hold Instr's
793   // operands.
794 
795   // What is the smallest bit width that can accomodate the entire value ranges
796   // of both of the operands?
797   unsigned MaxActiveBits = 0;
798   for (Value *Operand : Instr->operands()) {
799     ConstantRange CR = LVI->getConstantRange(Operand, Instr);
800     MaxActiveBits = std::max(CR.getActiveBits(), MaxActiveBits);
801   }
802   // Don't shrink below 8 bits wide.
803   unsigned NewWidth = std::max<unsigned>(PowerOf2Ceil(MaxActiveBits), 8);
804 
805   // NewWidth might be greater than OrigWidth if OrigWidth is not a power of
806   // two.
807   if (NewWidth >= Instr->getType()->getIntegerBitWidth())
808     return false;
809 
810   ++NumUDivURemsNarrowed;
811   IRBuilder<> B{Instr};
812   auto *TruncTy = Type::getIntNTy(Instr->getContext(), NewWidth);
813   auto *LHS = B.CreateTruncOrBitCast(Instr->getOperand(0), TruncTy,
814                                      Instr->getName() + ".lhs.trunc");
815   auto *RHS = B.CreateTruncOrBitCast(Instr->getOperand(1), TruncTy,
816                                      Instr->getName() + ".rhs.trunc");
817   auto *BO = B.CreateBinOp(Instr->getOpcode(), LHS, RHS, Instr->getName());
818   auto *Zext = B.CreateZExt(BO, Instr->getType(), Instr->getName() + ".zext");
819   if (auto *BinOp = dyn_cast<BinaryOperator>(BO))
820     if (BinOp->getOpcode() == Instruction::UDiv)
821       BinOp->setIsExact(Instr->isExact());
822 
823   Instr->replaceAllUsesWith(Zext);
824   Instr->eraseFromParent();
825   return true;
826 }
827 
828 static bool processSRem(BinaryOperator *SDI, LazyValueInfo *LVI) {
829   assert(SDI->getOpcode() == Instruction::SRem);
830   if (SDI->getType()->isVectorTy())
831     return false;
832 
833   struct Operand {
834     Value *V;
835     Domain D;
836   };
837   std::array<Operand, 2> Ops;
838 
839   for (const auto I : zip(Ops, SDI->operands())) {
840     Operand &Op = std::get<0>(I);
841     Op.V = std::get<1>(I);
842     Op.D = getDomain(Op.V, LVI, SDI);
843     if (Op.D == Domain::Unknown)
844       return false;
845   }
846 
847   // We know domains of both of the operands!
848   ++NumSRems;
849 
850   // We need operands to be non-negative, so negate each one that isn't.
851   for (Operand &Op : Ops) {
852     if (Op.D == Domain::NonNegative)
853       continue;
854     auto *BO =
855         BinaryOperator::CreateNeg(Op.V, Op.V->getName() + ".nonneg", SDI);
856     BO->setDebugLoc(SDI->getDebugLoc());
857     Op.V = BO;
858   }
859 
860   auto *URem =
861       BinaryOperator::CreateURem(Ops[0].V, Ops[1].V, SDI->getName(), SDI);
862   URem->setDebugLoc(SDI->getDebugLoc());
863 
864   Value *Res = URem;
865 
866   // If the divident was non-positive, we need to negate the result.
867   if (Ops[0].D == Domain::NonPositive)
868     Res = BinaryOperator::CreateNeg(Res, Res->getName() + ".neg", SDI);
869 
870   SDI->replaceAllUsesWith(Res);
871   SDI->eraseFromParent();
872 
873   // Try to simplify our new urem.
874   processUDivOrURem(URem, LVI);
875 
876   return true;
877 }
878 
879 /// See if LazyValueInfo's ability to exploit edge conditions or range
880 /// information is sufficient to prove the signs of both operands of this SDiv.
881 /// If this is the case, replace the SDiv with a UDiv. Even for local
882 /// conditions, this can sometimes prove conditions instcombine can't by
883 /// exploiting range information.
884 static bool processSDiv(BinaryOperator *SDI, LazyValueInfo *LVI) {
885   assert(SDI->getOpcode() == Instruction::SDiv);
886   if (SDI->getType()->isVectorTy())
887     return false;
888 
889   struct Operand {
890     Value *V;
891     Domain D;
892   };
893   std::array<Operand, 2> Ops;
894 
895   for (const auto I : zip(Ops, SDI->operands())) {
896     Operand &Op = std::get<0>(I);
897     Op.V = std::get<1>(I);
898     Op.D = getDomain(Op.V, LVI, SDI);
899     if (Op.D == Domain::Unknown)
900       return false;
901   }
902 
903   // We know domains of both of the operands!
904   ++NumSDivs;
905 
906   // We need operands to be non-negative, so negate each one that isn't.
907   for (Operand &Op : Ops) {
908     if (Op.D == Domain::NonNegative)
909       continue;
910     auto *BO =
911         BinaryOperator::CreateNeg(Op.V, Op.V->getName() + ".nonneg", SDI);
912     BO->setDebugLoc(SDI->getDebugLoc());
913     Op.V = BO;
914   }
915 
916   auto *UDiv =
917       BinaryOperator::CreateUDiv(Ops[0].V, Ops[1].V, SDI->getName(), SDI);
918   UDiv->setDebugLoc(SDI->getDebugLoc());
919   UDiv->setIsExact(SDI->isExact());
920 
921   Value *Res = UDiv;
922 
923   // If the operands had two different domains, we need to negate the result.
924   if (Ops[0].D != Ops[1].D)
925     Res = BinaryOperator::CreateNeg(Res, Res->getName() + ".neg", SDI);
926 
927   SDI->replaceAllUsesWith(Res);
928   SDI->eraseFromParent();
929 
930   // Try to simplify our new udiv.
931   processUDivOrURem(UDiv, LVI);
932 
933   return true;
934 }
935 
936 static bool processSDivOrSRem(BinaryOperator *Instr, LazyValueInfo *LVI) {
937   assert(Instr->getOpcode() == Instruction::SDiv ||
938          Instr->getOpcode() == Instruction::SRem);
939   if (Instr->getType()->isVectorTy())
940     return false;
941 
942   if (Instr->getOpcode() == Instruction::SDiv)
943     if (processSDiv(Instr, LVI))
944       return true;
945 
946   if (Instr->getOpcode() == Instruction::SRem)
947     if (processSRem(Instr, LVI))
948       return true;
949 
950   return narrowSDivOrSRem(Instr, LVI);
951 }
952 
953 static bool processAShr(BinaryOperator *SDI, LazyValueInfo *LVI) {
954   if (SDI->getType()->isVectorTy())
955     return false;
956 
957   if (!isNonNegative(SDI->getOperand(0), LVI, SDI))
958     return false;
959 
960   ++NumAShrs;
961   auto *BO = BinaryOperator::CreateLShr(SDI->getOperand(0), SDI->getOperand(1),
962                                         SDI->getName(), SDI);
963   BO->setDebugLoc(SDI->getDebugLoc());
964   BO->setIsExact(SDI->isExact());
965   SDI->replaceAllUsesWith(BO);
966   SDI->eraseFromParent();
967 
968   return true;
969 }
970 
971 static bool processSExt(SExtInst *SDI, LazyValueInfo *LVI) {
972   if (SDI->getType()->isVectorTy())
973     return false;
974 
975   Value *Base = SDI->getOperand(0);
976 
977   if (!isNonNegative(Base, LVI, SDI))
978     return false;
979 
980   ++NumSExt;
981   auto *ZExt =
982       CastInst::CreateZExtOrBitCast(Base, SDI->getType(), SDI->getName(), SDI);
983   ZExt->setDebugLoc(SDI->getDebugLoc());
984   SDI->replaceAllUsesWith(ZExt);
985   SDI->eraseFromParent();
986 
987   return true;
988 }
989 
990 static bool processBinOp(BinaryOperator *BinOp, LazyValueInfo *LVI) {
991   using OBO = OverflowingBinaryOperator;
992 
993   if (BinOp->getType()->isVectorTy())
994     return false;
995 
996   bool NSW = BinOp->hasNoSignedWrap();
997   bool NUW = BinOp->hasNoUnsignedWrap();
998   if (NSW && NUW)
999     return false;
1000 
1001   Instruction::BinaryOps Opcode = BinOp->getOpcode();
1002   Value *LHS = BinOp->getOperand(0);
1003   Value *RHS = BinOp->getOperand(1);
1004 
1005   ConstantRange LRange = LVI->getConstantRange(LHS, BinOp);
1006   ConstantRange RRange = LVI->getConstantRange(RHS, BinOp);
1007 
1008   bool Changed = false;
1009   bool NewNUW = false, NewNSW = false;
1010   if (!NUW) {
1011     ConstantRange NUWRange = ConstantRange::makeGuaranteedNoWrapRegion(
1012         Opcode, RRange, OBO::NoUnsignedWrap);
1013     NewNUW = NUWRange.contains(LRange);
1014     Changed |= NewNUW;
1015   }
1016   if (!NSW) {
1017     ConstantRange NSWRange = ConstantRange::makeGuaranteedNoWrapRegion(
1018         Opcode, RRange, OBO::NoSignedWrap);
1019     NewNSW = NSWRange.contains(LRange);
1020     Changed |= NewNSW;
1021   }
1022 
1023   setDeducedOverflowingFlags(BinOp, Opcode, NewNSW, NewNUW);
1024 
1025   return Changed;
1026 }
1027 
1028 static bool processAnd(BinaryOperator *BinOp, LazyValueInfo *LVI) {
1029   if (BinOp->getType()->isVectorTy())
1030     return false;
1031 
1032   // Pattern match (and lhs, C) where C includes a superset of bits which might
1033   // be set in lhs.  This is a common truncation idiom created by instcombine.
1034   Value *LHS = BinOp->getOperand(0);
1035   ConstantInt *RHS = dyn_cast<ConstantInt>(BinOp->getOperand(1));
1036   if (!RHS || !RHS->getValue().isMask())
1037     return false;
1038 
1039   // We can only replace the AND with LHS based on range info if the range does
1040   // not include undef.
1041   ConstantRange LRange =
1042       LVI->getConstantRange(LHS, BinOp, /*UndefAllowed=*/false);
1043   if (!LRange.getUnsignedMax().ule(RHS->getValue()))
1044     return false;
1045 
1046   BinOp->replaceAllUsesWith(LHS);
1047   BinOp->eraseFromParent();
1048   NumAnd++;
1049   return true;
1050 }
1051 
1052 
1053 static Constant *getConstantAt(Value *V, Instruction *At, LazyValueInfo *LVI) {
1054   if (Constant *C = LVI->getConstant(V, At))
1055     return C;
1056 
1057   // TODO: The following really should be sunk inside LVI's core algorithm, or
1058   // at least the outer shims around such.
1059   auto *C = dyn_cast<CmpInst>(V);
1060   if (!C) return nullptr;
1061 
1062   Value *Op0 = C->getOperand(0);
1063   Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
1064   if (!Op1) return nullptr;
1065 
1066   LazyValueInfo::Tristate Result = LVI->getPredicateAt(
1067       C->getPredicate(), Op0, Op1, At, /*UseBlockValue=*/false);
1068   if (Result == LazyValueInfo::Unknown)
1069     return nullptr;
1070 
1071   return (Result == LazyValueInfo::True) ?
1072     ConstantInt::getTrue(C->getContext()) :
1073     ConstantInt::getFalse(C->getContext());
1074 }
1075 
1076 static bool runImpl(Function &F, LazyValueInfo *LVI, DominatorTree *DT,
1077                     const SimplifyQuery &SQ) {
1078   bool FnChanged = false;
1079   // Visiting in a pre-order depth-first traversal causes us to simplify early
1080   // blocks before querying later blocks (which require us to analyze early
1081   // blocks).  Eagerly simplifying shallow blocks means there is strictly less
1082   // work to do for deep blocks.  This also means we don't visit unreachable
1083   // blocks.
1084   for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
1085     bool BBChanged = false;
1086     for (Instruction &II : llvm::make_early_inc_range(*BB)) {
1087       switch (II.getOpcode()) {
1088       case Instruction::Select:
1089         BBChanged |= processSelect(cast<SelectInst>(&II), LVI);
1090         break;
1091       case Instruction::PHI:
1092         BBChanged |= processPHI(cast<PHINode>(&II), LVI, DT, SQ);
1093         break;
1094       case Instruction::ICmp:
1095       case Instruction::FCmp:
1096         BBChanged |= processCmp(cast<CmpInst>(&II), LVI);
1097         break;
1098       case Instruction::Load:
1099       case Instruction::Store:
1100         BBChanged |= processMemAccess(&II, LVI);
1101         break;
1102       case Instruction::Call:
1103       case Instruction::Invoke:
1104         BBChanged |= processCallSite(cast<CallBase>(II), LVI);
1105         break;
1106       case Instruction::SRem:
1107       case Instruction::SDiv:
1108         BBChanged |= processSDivOrSRem(cast<BinaryOperator>(&II), LVI);
1109         break;
1110       case Instruction::UDiv:
1111       case Instruction::URem:
1112         BBChanged |= processUDivOrURem(cast<BinaryOperator>(&II), LVI);
1113         break;
1114       case Instruction::AShr:
1115         BBChanged |= processAShr(cast<BinaryOperator>(&II), LVI);
1116         break;
1117       case Instruction::SExt:
1118         BBChanged |= processSExt(cast<SExtInst>(&II), LVI);
1119         break;
1120       case Instruction::Add:
1121       case Instruction::Sub:
1122       case Instruction::Mul:
1123       case Instruction::Shl:
1124         BBChanged |= processBinOp(cast<BinaryOperator>(&II), LVI);
1125         break;
1126       case Instruction::And:
1127         BBChanged |= processAnd(cast<BinaryOperator>(&II), LVI);
1128         break;
1129       }
1130     }
1131 
1132     Instruction *Term = BB->getTerminator();
1133     switch (Term->getOpcode()) {
1134     case Instruction::Switch:
1135       BBChanged |= processSwitch(cast<SwitchInst>(Term), LVI, DT);
1136       break;
1137     case Instruction::Ret: {
1138       auto *RI = cast<ReturnInst>(Term);
1139       // Try to determine the return value if we can.  This is mainly here to
1140       // simplify the writing of unit tests, but also helps to enable IPO by
1141       // constant folding the return values of callees.
1142       auto *RetVal = RI->getReturnValue();
1143       if (!RetVal) break; // handle "ret void"
1144       if (isa<Constant>(RetVal)) break; // nothing to do
1145       if (auto *C = getConstantAt(RetVal, RI, LVI)) {
1146         ++NumReturns;
1147         RI->replaceUsesOfWith(RetVal, C);
1148         BBChanged = true;
1149       }
1150     }
1151     }
1152 
1153     FnChanged |= BBChanged;
1154   }
1155 
1156   return FnChanged;
1157 }
1158 
1159 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
1160   if (skipFunction(F))
1161     return false;
1162 
1163   LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
1164   DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1165 
1166   return runImpl(F, LVI, DT, getBestSimplifyQuery(*this, F));
1167 }
1168 
1169 PreservedAnalyses
1170 CorrelatedValuePropagationPass::run(Function &F, FunctionAnalysisManager &AM) {
1171   LazyValueInfo *LVI = &AM.getResult<LazyValueAnalysis>(F);
1172   DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1173 
1174   bool Changed = runImpl(F, LVI, DT, getBestSimplifyQuery(AM, F));
1175 
1176   PreservedAnalyses PA;
1177   if (!Changed) {
1178     PA = PreservedAnalyses::all();
1179   } else {
1180     PA.preserve<DominatorTreeAnalysis>();
1181     PA.preserve<LazyValueAnalysis>();
1182   }
1183 
1184   // Keeping LVI alive is expensive, both because it uses a lot of memory, and
1185   // because invalidating values in LVI is expensive. While CVP does preserve
1186   // LVI, we know that passes after JumpThreading+CVP will not need the result
1187   // of this analysis, so we forcefully discard it early.
1188   PA.abandon<LazyValueAnalysis>();
1189   return PA;
1190 }
1191