1 //===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Correlated Value Propagation pass.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
15 #include "llvm/ADT/DepthFirstIterator.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/GlobalsModRef.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/LazyValueInfo.h"
22 #include "llvm/IR/Attributes.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/CFG.h"
25 #include "llvm/IR/CallSite.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/InstrTypes.h"
32 #include "llvm/IR/Instruction.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/IRBuilder.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/Pass.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Scalar.h"
46 #include "llvm/Transforms/Utils/Local.h"
52 #define DEBUG_TYPE "correlated-value-propagation"
54 STATISTIC(NumPhis, "Number of phis propagated");
55 STATISTIC(NumSelects, "Number of selects propagated");
56 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
57 STATISTIC(NumCmps, "Number of comparisons propagated");
58 STATISTIC(NumReturns, "Number of return values propagated");
59 STATISTIC(NumDeadCases, "Number of switch cases removed");
60 STATISTIC(NumSDivs, "Number of sdiv converted to udiv");
61 STATISTIC(NumAShrs, "Number of ashr converted to lshr");
62 STATISTIC(NumSRems, "Number of srem converted to urem");
63 STATISTIC(NumOverflows, "Number of overflow checks removed");
65 static cl::opt<bool> DontProcessAdds("cvp-dont-process-adds", cl::init(true));
69 class CorrelatedValuePropagation : public FunctionPass {
73 CorrelatedValuePropagation(): FunctionPass(ID) {
74 initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
77 bool runOnFunction(Function &F) override;
79 void getAnalysisUsage(AnalysisUsage &AU) const override {
80 AU.addRequired<LazyValueInfoWrapperPass>();
81 AU.addPreserved<GlobalsAAWrapperPass>();
85 } // end anonymous namespace
87 char CorrelatedValuePropagation::ID = 0;
89 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
90 "Value Propagation", false, false)
91 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
92 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
93 "Value Propagation", false, false)
95 // Public interface to the Value Propagation pass
96 Pass *llvm::createCorrelatedValuePropagationPass() {
97 return new CorrelatedValuePropagation();
100 static bool processSelect(SelectInst *S, LazyValueInfo *LVI) {
101 if (S->getType()->isVectorTy()) return false;
102 if (isa<Constant>(S->getOperand(0))) return false;
104 Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S);
105 if (!C) return false;
107 ConstantInt *CI = dyn_cast<ConstantInt>(C);
108 if (!CI) return false;
110 Value *ReplaceWith = S->getOperand(1);
111 Value *Other = S->getOperand(2);
112 if (!CI->isOne()) std::swap(ReplaceWith, Other);
113 if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
115 S->replaceAllUsesWith(ReplaceWith);
116 S->eraseFromParent();
123 static bool processPHI(PHINode *P, LazyValueInfo *LVI,
124 const SimplifyQuery &SQ) {
125 bool Changed = false;
127 BasicBlock *BB = P->getParent();
128 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
129 Value *Incoming = P->getIncomingValue(i);
130 if (isa<Constant>(Incoming)) continue;
132 Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P);
134 // Look if the incoming value is a select with a scalar condition for which
135 // LVI can tells us the value. In that case replace the incoming value with
136 // the appropriate value of the select. This often allows us to remove the
139 SelectInst *SI = dyn_cast<SelectInst>(Incoming);
142 Value *Condition = SI->getCondition();
143 if (!Condition->getType()->isVectorTy()) {
144 if (Constant *C = LVI->getConstantOnEdge(
145 Condition, P->getIncomingBlock(i), BB, P)) {
146 if (C->isOneValue()) {
147 V = SI->getTrueValue();
148 } else if (C->isZeroValue()) {
149 V = SI->getFalseValue();
151 // Once LVI learns to handle vector types, we could also add support
152 // for vector type constants that are not all zeroes or all ones.
156 // Look if the select has a constant but LVI tells us that the incoming
157 // value can never be that constant. In that case replace the incoming
158 // value with the other value of the select. This often allows us to
159 // remove the select later.
161 Constant *C = dyn_cast<Constant>(SI->getFalseValue());
164 if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
165 P->getIncomingBlock(i), BB, P) !=
166 LazyValueInfo::False)
168 V = SI->getTrueValue();
171 DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
174 P->setIncomingValue(i, V);
178 if (Value *V = SimplifyInstruction(P, SQ)) {
179 P->replaceAllUsesWith(V);
180 P->eraseFromParent();
190 static bool processMemAccess(Instruction *I, LazyValueInfo *LVI) {
191 Value *Pointer = nullptr;
192 if (LoadInst *L = dyn_cast<LoadInst>(I))
193 Pointer = L->getPointerOperand();
195 Pointer = cast<StoreInst>(I)->getPointerOperand();
197 if (isa<Constant>(Pointer)) return false;
199 Constant *C = LVI->getConstant(Pointer, I->getParent(), I);
200 if (!C) return false;
203 I->replaceUsesOfWith(Pointer, C);
207 /// See if LazyValueInfo's ability to exploit edge conditions or range
208 /// information is sufficient to prove this comparison. Even for local
209 /// conditions, this can sometimes prove conditions instcombine can't by
210 /// exploiting range information.
211 static bool processCmp(CmpInst *C, LazyValueInfo *LVI) {
212 Value *Op0 = C->getOperand(0);
213 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
214 if (!Op1) return false;
216 // As a policy choice, we choose not to waste compile time on anything where
217 // the comparison is testing local values. While LVI can sometimes reason
218 // about such cases, it's not its primary purpose. We do make sure to do
219 // the block local query for uses from terminator instructions, but that's
220 // handled in the code for each terminator.
221 auto *I = dyn_cast<Instruction>(Op0);
222 if (I && I->getParent() == C->getParent())
225 LazyValueInfo::Tristate Result =
226 LVI->getPredicateAt(C->getPredicate(), Op0, Op1, C);
227 if (Result == LazyValueInfo::Unknown) return false;
230 if (Result == LazyValueInfo::True)
231 C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
233 C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
234 C->eraseFromParent();
239 /// Simplify a switch instruction by removing cases which can never fire. If the
240 /// uselessness of a case could be determined locally then constant propagation
241 /// would already have figured it out. Instead, walk the predecessors and
242 /// statically evaluate cases based on information available on that edge. Cases
243 /// that cannot fire no matter what the incoming edge can safely be removed. If
244 /// a case fires on every incoming edge then the entire switch can be removed
245 /// and replaced with a branch to the case destination.
246 static bool processSwitch(SwitchInst *SI, LazyValueInfo *LVI) {
247 Value *Cond = SI->getCondition();
248 BasicBlock *BB = SI->getParent();
250 // If the condition was defined in same block as the switch then LazyValueInfo
251 // currently won't say anything useful about it, though in theory it could.
252 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
255 // If the switch is unreachable then trying to improve it is a waste of time.
256 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
257 if (PB == PE) return false;
259 // Analyse each switch case in turn.
260 bool Changed = false;
261 for (auto CI = SI->case_begin(), CE = SI->case_end(); CI != CE;) {
262 ConstantInt *Case = CI->getCaseValue();
264 // Check to see if the switch condition is equal to/not equal to the case
265 // value on every incoming edge, equal/not equal being the same each time.
266 LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
267 for (pred_iterator PI = PB; PI != PE; ++PI) {
268 // Is the switch condition equal to the case value?
269 LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
272 // Give up on this case if nothing is known.
273 if (Value == LazyValueInfo::Unknown) {
274 State = LazyValueInfo::Unknown;
278 // If this was the first edge to be visited, record that all other edges
279 // need to give the same result.
285 // If this case is known to fire for some edges and known not to fire for
286 // others then there is nothing we can do - give up.
287 if (Value != State) {
288 State = LazyValueInfo::Unknown;
293 if (State == LazyValueInfo::False) {
294 // This case never fires - remove it.
295 CI->getCaseSuccessor()->removePredecessor(BB);
296 CI = SI->removeCase(CI);
299 // The condition can be modified by removePredecessor's PHI simplification
301 Cond = SI->getCondition();
307 if (State == LazyValueInfo::True) {
308 // This case always fires. Arrange for the switch to be turned into an
309 // unconditional branch by replacing the switch condition with the case
311 SI->setCondition(Case);
312 NumDeadCases += SI->getNumCases();
317 // Increment the case iterator since we didn't delete it.
322 // If the switch has been simplified to the point where it can be replaced
323 // by a branch then do so now.
324 ConstantFoldTerminator(BB);
329 // See if we can prove that the given overflow intrinsic will not overflow.
330 static bool willNotOverflow(IntrinsicInst *II, LazyValueInfo *LVI) {
331 using OBO = OverflowingBinaryOperator;
332 auto NoWrap = [&] (Instruction::BinaryOps BinOp, unsigned NoWrapKind) {
333 Value *RHS = II->getOperand(1);
334 ConstantRange RRange = LVI->getConstantRange(RHS, II->getParent(), II);
335 ConstantRange NWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
336 BinOp, RRange, NoWrapKind);
337 // As an optimization, do not compute LRange if we do not need it.
338 if (NWRegion.isEmptySet())
340 Value *LHS = II->getOperand(0);
341 ConstantRange LRange = LVI->getConstantRange(LHS, II->getParent(), II);
342 return NWRegion.contains(LRange);
344 switch (II->getIntrinsicID()) {
347 case Intrinsic::uadd_with_overflow:
348 return NoWrap(Instruction::Add, OBO::NoUnsignedWrap);
349 case Intrinsic::sadd_with_overflow:
350 return NoWrap(Instruction::Add, OBO::NoSignedWrap);
351 case Intrinsic::usub_with_overflow:
352 return NoWrap(Instruction::Sub, OBO::NoUnsignedWrap);
353 case Intrinsic::ssub_with_overflow:
354 return NoWrap(Instruction::Sub, OBO::NoSignedWrap);
359 static void processOverflowIntrinsic(IntrinsicInst *II) {
360 Value *NewOp = nullptr;
361 switch (II->getIntrinsicID()) {
363 llvm_unreachable("Unexpected instruction.");
364 case Intrinsic::uadd_with_overflow:
365 case Intrinsic::sadd_with_overflow:
366 NewOp = BinaryOperator::CreateAdd(II->getOperand(0), II->getOperand(1),
369 case Intrinsic::usub_with_overflow:
370 case Intrinsic::ssub_with_overflow:
371 NewOp = BinaryOperator::CreateSub(II->getOperand(0), II->getOperand(1),
377 Value *NewI = B.CreateInsertValue(UndefValue::get(II->getType()), NewOp, 0);
378 NewI = B.CreateInsertValue(NewI, ConstantInt::getFalse(II->getContext()), 1);
379 II->replaceAllUsesWith(NewI);
380 II->eraseFromParent();
383 /// Infer nonnull attributes for the arguments at the specified callsite.
384 static bool processCallSite(CallSite CS, LazyValueInfo *LVI) {
385 SmallVector<unsigned, 4> ArgNos;
388 if (auto *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
389 if (willNotOverflow(II, LVI)) {
390 processOverflowIntrinsic(II);
395 for (Value *V : CS.args()) {
396 PointerType *Type = dyn_cast<PointerType>(V->getType());
397 // Try to mark pointer typed parameters as non-null. We skip the
398 // relatively expensive analysis for constants which are obviously either
399 // null or non-null to start with.
400 if (Type && !CS.paramHasAttr(ArgNo, Attribute::NonNull) &&
402 LVI->getPredicateAt(ICmpInst::ICMP_EQ, V,
403 ConstantPointerNull::get(Type),
404 CS.getInstruction()) == LazyValueInfo::False)
405 ArgNos.push_back(ArgNo);
409 assert(ArgNo == CS.arg_size() && "sanity check");
414 AttributeList AS = CS.getAttributes();
415 LLVMContext &Ctx = CS.getInstruction()->getContext();
416 AS = AS.addParamAttribute(Ctx, ArgNos,
417 Attribute::get(Ctx, Attribute::NonNull));
418 CS.setAttributes(AS);
423 static bool hasPositiveOperands(BinaryOperator *SDI, LazyValueInfo *LVI) {
424 Constant *Zero = ConstantInt::get(SDI->getType(), 0);
425 for (Value *O : SDI->operands()) {
426 auto Result = LVI->getPredicateAt(ICmpInst::ICMP_SGE, O, Zero, SDI);
427 if (Result != LazyValueInfo::True)
433 static bool processSRem(BinaryOperator *SDI, LazyValueInfo *LVI) {
434 if (SDI->getType()->isVectorTy() ||
435 !hasPositiveOperands(SDI, LVI))
439 auto *BO = BinaryOperator::CreateURem(SDI->getOperand(0), SDI->getOperand(1),
440 SDI->getName(), SDI);
441 SDI->replaceAllUsesWith(BO);
442 SDI->eraseFromParent();
446 /// See if LazyValueInfo's ability to exploit edge conditions or range
447 /// information is sufficient to prove the both operands of this SDiv are
448 /// positive. If this is the case, replace the SDiv with a UDiv. Even for local
449 /// conditions, this can sometimes prove conditions instcombine can't by
450 /// exploiting range information.
451 static bool processSDiv(BinaryOperator *SDI, LazyValueInfo *LVI) {
452 if (SDI->getType()->isVectorTy() ||
453 !hasPositiveOperands(SDI, LVI))
457 auto *BO = BinaryOperator::CreateUDiv(SDI->getOperand(0), SDI->getOperand(1),
458 SDI->getName(), SDI);
459 BO->setIsExact(SDI->isExact());
460 SDI->replaceAllUsesWith(BO);
461 SDI->eraseFromParent();
466 static bool processAShr(BinaryOperator *SDI, LazyValueInfo *LVI) {
467 if (SDI->getType()->isVectorTy())
470 Constant *Zero = ConstantInt::get(SDI->getType(), 0);
471 if (LVI->getPredicateAt(ICmpInst::ICMP_SGE, SDI->getOperand(0), Zero, SDI) !=
476 auto *BO = BinaryOperator::CreateLShr(SDI->getOperand(0), SDI->getOperand(1),
477 SDI->getName(), SDI);
478 BO->setIsExact(SDI->isExact());
479 SDI->replaceAllUsesWith(BO);
480 SDI->eraseFromParent();
485 static bool processAdd(BinaryOperator *AddOp, LazyValueInfo *LVI) {
486 using OBO = OverflowingBinaryOperator;
491 if (AddOp->getType()->isVectorTy())
494 bool NSW = AddOp->hasNoSignedWrap();
495 bool NUW = AddOp->hasNoUnsignedWrap();
499 BasicBlock *BB = AddOp->getParent();
501 Value *LHS = AddOp->getOperand(0);
502 Value *RHS = AddOp->getOperand(1);
504 ConstantRange LRange = LVI->getConstantRange(LHS, BB, AddOp);
506 // Initialize RRange only if we need it. If we know that guaranteed no wrap
507 // range for the given LHS range is empty don't spend time calculating the
508 // range for the RHS.
509 Optional<ConstantRange> RRange;
510 auto LazyRRange = [&] () {
512 RRange = LVI->getConstantRange(RHS, BB, AddOp);
513 return RRange.getValue();
516 bool Changed = false;
518 ConstantRange NUWRange = ConstantRange::makeGuaranteedNoWrapRegion(
519 BinaryOperator::Add, LRange, OBO::NoUnsignedWrap);
520 if (!NUWRange.isEmptySet()) {
521 bool NewNUW = NUWRange.contains(LazyRRange());
522 AddOp->setHasNoUnsignedWrap(NewNUW);
527 ConstantRange NSWRange = ConstantRange::makeGuaranteedNoWrapRegion(
528 BinaryOperator::Add, LRange, OBO::NoSignedWrap);
529 if (!NSWRange.isEmptySet()) {
530 bool NewNSW = NSWRange.contains(LazyRRange());
531 AddOp->setHasNoSignedWrap(NewNSW);
539 static Constant *getConstantAt(Value *V, Instruction *At, LazyValueInfo *LVI) {
540 if (Constant *C = LVI->getConstant(V, At->getParent(), At))
543 // TODO: The following really should be sunk inside LVI's core algorithm, or
544 // at least the outer shims around such.
545 auto *C = dyn_cast<CmpInst>(V);
546 if (!C) return nullptr;
548 Value *Op0 = C->getOperand(0);
549 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
550 if (!Op1) return nullptr;
552 LazyValueInfo::Tristate Result =
553 LVI->getPredicateAt(C->getPredicate(), Op0, Op1, At);
554 if (Result == LazyValueInfo::Unknown)
557 return (Result == LazyValueInfo::True) ?
558 ConstantInt::getTrue(C->getContext()) :
559 ConstantInt::getFalse(C->getContext());
562 static bool runImpl(Function &F, LazyValueInfo *LVI, const SimplifyQuery &SQ) {
563 bool FnChanged = false;
564 // Visiting in a pre-order depth-first traversal causes us to simplify early
565 // blocks before querying later blocks (which require us to analyze early
566 // blocks). Eagerly simplifying shallow blocks means there is strictly less
567 // work to do for deep blocks. This also means we don't visit unreachable
569 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
570 bool BBChanged = false;
571 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
572 Instruction *II = &*BI++;
573 switch (II->getOpcode()) {
574 case Instruction::Select:
575 BBChanged |= processSelect(cast<SelectInst>(II), LVI);
577 case Instruction::PHI:
578 BBChanged |= processPHI(cast<PHINode>(II), LVI, SQ);
580 case Instruction::ICmp:
581 case Instruction::FCmp:
582 BBChanged |= processCmp(cast<CmpInst>(II), LVI);
584 case Instruction::Load:
585 case Instruction::Store:
586 BBChanged |= processMemAccess(II, LVI);
588 case Instruction::Call:
589 case Instruction::Invoke:
590 BBChanged |= processCallSite(CallSite(II), LVI);
592 case Instruction::SRem:
593 BBChanged |= processSRem(cast<BinaryOperator>(II), LVI);
595 case Instruction::SDiv:
596 BBChanged |= processSDiv(cast<BinaryOperator>(II), LVI);
598 case Instruction::AShr:
599 BBChanged |= processAShr(cast<BinaryOperator>(II), LVI);
601 case Instruction::Add:
602 BBChanged |= processAdd(cast<BinaryOperator>(II), LVI);
607 Instruction *Term = BB->getTerminator();
608 switch (Term->getOpcode()) {
609 case Instruction::Switch:
610 BBChanged |= processSwitch(cast<SwitchInst>(Term), LVI);
612 case Instruction::Ret: {
613 auto *RI = cast<ReturnInst>(Term);
614 // Try to determine the return value if we can. This is mainly here to
615 // simplify the writing of unit tests, but also helps to enable IPO by
616 // constant folding the return values of callees.
617 auto *RetVal = RI->getReturnValue();
618 if (!RetVal) break; // handle "ret void"
619 if (isa<Constant>(RetVal)) break; // nothing to do
620 if (auto *C = getConstantAt(RetVal, RI, LVI)) {
622 RI->replaceUsesOfWith(RetVal, C);
628 FnChanged |= BBChanged;
634 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
638 LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
639 return runImpl(F, LVI, getBestSimplifyQuery(*this, F));
643 CorrelatedValuePropagationPass::run(Function &F, FunctionAnalysisManager &AM) {
645 LazyValueInfo *LVI = &AM.getResult<LazyValueAnalysis>(F);
646 bool Changed = runImpl(F, LVI, getBestSimplifyQuery(AM, F));
649 return PreservedAnalyses::all();
650 PreservedAnalyses PA;
651 PA.preserve<GlobalsAA>();