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