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/Transforms/Scalar.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/GlobalsModRef.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/LazyValueInfo.h"
20 #include "llvm/IR/CFG.h"
21 #include "llvm/IR/ConstantRange.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Transforms/Utils/Local.h"
32 #define DEBUG_TYPE "correlated-value-propagation"
34 STATISTIC(NumPhis, "Number of phis propagated");
35 STATISTIC(NumSelects, "Number of selects propagated");
36 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
37 STATISTIC(NumCmps, "Number of comparisons propagated");
38 STATISTIC(NumReturns, "Number of return values propagated");
39 STATISTIC(NumDeadCases, "Number of switch cases removed");
40 STATISTIC(NumSDivs, "Number of sdiv converted to udiv");
41 STATISTIC(NumAShrs, "Number of ashr converted to lshr");
42 STATISTIC(NumSRems, "Number of srem converted to urem");
45 class CorrelatedValuePropagation : public FunctionPass {
48 CorrelatedValuePropagation(): FunctionPass(ID) {
49 initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
52 bool runOnFunction(Function &F) override;
54 void getAnalysisUsage(AnalysisUsage &AU) const override {
55 AU.addRequired<LazyValueInfoWrapperPass>();
56 AU.addPreserved<GlobalsAAWrapperPass>();
61 char CorrelatedValuePropagation::ID = 0;
62 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
63 "Value Propagation", false, false)
64 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
65 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
66 "Value Propagation", false, false)
68 // Public interface to the Value Propagation pass
69 Pass *llvm::createCorrelatedValuePropagationPass() {
70 return new CorrelatedValuePropagation();
73 static bool processSelect(SelectInst *S, LazyValueInfo *LVI) {
74 if (S->getType()->isVectorTy()) return false;
75 if (isa<Constant>(S->getOperand(0))) return false;
77 Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S);
80 ConstantInt *CI = dyn_cast<ConstantInt>(C);
81 if (!CI) return false;
83 Value *ReplaceWith = S->getOperand(1);
84 Value *Other = S->getOperand(2);
85 if (!CI->isOne()) std::swap(ReplaceWith, Other);
86 if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
88 S->replaceAllUsesWith(ReplaceWith);
96 static bool processPHI(PHINode *P, LazyValueInfo *LVI) {
99 BasicBlock *BB = P->getParent();
100 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
101 Value *Incoming = P->getIncomingValue(i);
102 if (isa<Constant>(Incoming)) continue;
104 Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P);
106 // Look if the incoming value is a select with a scalar condition for which
107 // LVI can tells us the value. In that case replace the incoming value with
108 // the appropriate value of the select. This often allows us to remove the
111 SelectInst *SI = dyn_cast<SelectInst>(Incoming);
114 Value *Condition = SI->getCondition();
115 if (!Condition->getType()->isVectorTy()) {
116 if (Constant *C = LVI->getConstantOnEdge(
117 Condition, P->getIncomingBlock(i), BB, P)) {
118 if (C->isOneValue()) {
119 V = SI->getTrueValue();
120 } else if (C->isZeroValue()) {
121 V = SI->getFalseValue();
123 // Once LVI learns to handle vector types, we could also add support
124 // for vector type constants that are not all zeroes or all ones.
128 // Look if the select has a constant but LVI tells us that the incoming
129 // value can never be that constant. In that case replace the incoming
130 // value with the other value of the select. This often allows us to
131 // remove the select later.
133 Constant *C = dyn_cast<Constant>(SI->getFalseValue());
136 if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
137 P->getIncomingBlock(i), BB, P) !=
138 LazyValueInfo::False)
140 V = SI->getTrueValue();
143 DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
146 P->setIncomingValue(i, V);
150 // FIXME: Provide TLI, DT, AT to SimplifyInstruction.
151 const DataLayout &DL = BB->getModule()->getDataLayout();
152 if (Value *V = SimplifyInstruction(P, DL)) {
153 P->replaceAllUsesWith(V);
154 P->eraseFromParent();
164 static bool processMemAccess(Instruction *I, LazyValueInfo *LVI) {
165 Value *Pointer = nullptr;
166 if (LoadInst *L = dyn_cast<LoadInst>(I))
167 Pointer = L->getPointerOperand();
169 Pointer = cast<StoreInst>(I)->getPointerOperand();
171 if (isa<Constant>(Pointer)) return false;
173 Constant *C = LVI->getConstant(Pointer, I->getParent(), I);
174 if (!C) return false;
177 I->replaceUsesOfWith(Pointer, C);
181 /// See if LazyValueInfo's ability to exploit edge conditions or range
182 /// information is sufficient to prove this comparison. Even for local
183 /// conditions, this can sometimes prove conditions instcombine can't by
184 /// exploiting range information.
185 static bool processCmp(CmpInst *C, LazyValueInfo *LVI) {
186 Value *Op0 = C->getOperand(0);
187 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
188 if (!Op1) return false;
190 // As a policy choice, we choose not to waste compile time on anything where
191 // the comparison is testing local values. While LVI can sometimes reason
192 // about such cases, it's not its primary purpose. We do make sure to do
193 // the block local query for uses from terminator instructions, but that's
194 // handled in the code for each terminator.
195 auto *I = dyn_cast<Instruction>(Op0);
196 if (I && I->getParent() == C->getParent())
199 LazyValueInfo::Tristate Result =
200 LVI->getPredicateAt(C->getPredicate(), Op0, Op1, C);
201 if (Result == LazyValueInfo::Unknown) return false;
204 if (Result == LazyValueInfo::True)
205 C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
207 C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
208 C->eraseFromParent();
213 /// Simplify a switch instruction by removing cases which can never fire. If the
214 /// uselessness of a case could be determined locally then constant propagation
215 /// would already have figured it out. Instead, walk the predecessors and
216 /// statically evaluate cases based on information available on that edge. Cases
217 /// that cannot fire no matter what the incoming edge can safely be removed. If
218 /// a case fires on every incoming edge then the entire switch can be removed
219 /// and replaced with a branch to the case destination.
220 static bool processSwitch(SwitchInst *SI, LazyValueInfo *LVI) {
221 Value *Cond = SI->getCondition();
222 BasicBlock *BB = SI->getParent();
224 // If the condition was defined in same block as the switch then LazyValueInfo
225 // currently won't say anything useful about it, though in theory it could.
226 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
229 // If the switch is unreachable then trying to improve it is a waste of time.
230 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
231 if (PB == PE) return false;
233 // Analyse each switch case in turn. This is done in reverse order so that
234 // removing a case doesn't cause trouble for the iteration.
235 bool Changed = false;
236 for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE;
238 ConstantInt *Case = CI.getCaseValue();
240 // Check to see if the switch condition is equal to/not equal to the case
241 // value on every incoming edge, equal/not equal being the same each time.
242 LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
243 for (pred_iterator PI = PB; PI != PE; ++PI) {
244 // Is the switch condition equal to the case value?
245 LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
248 // Give up on this case if nothing is known.
249 if (Value == LazyValueInfo::Unknown) {
250 State = LazyValueInfo::Unknown;
254 // If this was the first edge to be visited, record that all other edges
255 // need to give the same result.
261 // If this case is known to fire for some edges and known not to fire for
262 // others then there is nothing we can do - give up.
263 if (Value != State) {
264 State = LazyValueInfo::Unknown;
269 if (State == LazyValueInfo::False) {
270 // This case never fires - remove it.
271 CI.getCaseSuccessor()->removePredecessor(BB);
272 SI->removeCase(CI); // Does not invalidate the iterator.
274 // The condition can be modified by removePredecessor's PHI simplification
276 Cond = SI->getCondition();
280 } else if (State == LazyValueInfo::True) {
281 // This case always fires. Arrange for the switch to be turned into an
282 // unconditional branch by replacing the switch condition with the case
284 SI->setCondition(Case);
285 NumDeadCases += SI->getNumCases();
292 // If the switch has been simplified to the point where it can be replaced
293 // by a branch then do so now.
294 ConstantFoldTerminator(BB);
299 /// Infer nonnull attributes for the arguments at the specified callsite.
300 static bool processCallSite(CallSite CS, LazyValueInfo *LVI) {
301 SmallVector<unsigned, 4> Indices;
304 for (Value *V : CS.args()) {
305 PointerType *Type = dyn_cast<PointerType>(V->getType());
306 // Try to mark pointer typed parameters as non-null. We skip the
307 // relatively expensive analysis for constants which are obviously either
308 // null or non-null to start with.
309 if (Type && !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
311 LVI->getPredicateAt(ICmpInst::ICMP_EQ, V,
312 ConstantPointerNull::get(Type),
313 CS.getInstruction()) == LazyValueInfo::False)
314 Indices.push_back(ArgNo + 1);
318 assert(ArgNo == CS.arg_size() && "sanity check");
323 AttributeSet AS = CS.getAttributes();
324 LLVMContext &Ctx = CS.getInstruction()->getContext();
325 AS = AS.addAttribute(Ctx, Indices, Attribute::get(Ctx, Attribute::NonNull));
326 CS.setAttributes(AS);
331 // Helper function to rewrite srem and sdiv. As a policy choice, we choose not
332 // to waste compile time on anything where the operands are local defs. While
333 // LVI can sometimes reason about such cases, it's not its primary purpose.
334 static bool hasLocalDefs(BinaryOperator *SDI) {
335 for (Value *O : SDI->operands()) {
336 auto *I = dyn_cast<Instruction>(O);
337 if (I && I->getParent() == SDI->getParent())
343 static bool hasPositiveOperands(BinaryOperator *SDI, LazyValueInfo *LVI) {
344 Constant *Zero = ConstantInt::get(SDI->getType(), 0);
345 for (Value *O : SDI->operands()) {
346 auto Result = LVI->getPredicateAt(ICmpInst::ICMP_SGE, O, Zero, SDI);
347 if (Result != LazyValueInfo::True)
353 static bool processSRem(BinaryOperator *SDI, LazyValueInfo *LVI) {
354 if (SDI->getType()->isVectorTy() || hasLocalDefs(SDI) ||
355 !hasPositiveOperands(SDI, LVI))
359 auto *BO = BinaryOperator::CreateURem(SDI->getOperand(0), SDI->getOperand(1),
360 SDI->getName(), SDI);
361 SDI->replaceAllUsesWith(BO);
362 SDI->eraseFromParent();
366 /// See if LazyValueInfo's ability to exploit edge conditions or range
367 /// information is sufficient to prove the both operands of this SDiv are
368 /// positive. If this is the case, replace the SDiv with a UDiv. Even for local
369 /// conditions, this can sometimes prove conditions instcombine can't by
370 /// exploiting range information.
371 static bool processSDiv(BinaryOperator *SDI, LazyValueInfo *LVI) {
372 if (SDI->getType()->isVectorTy() || hasLocalDefs(SDI) ||
373 !hasPositiveOperands(SDI, LVI))
377 auto *BO = BinaryOperator::CreateUDiv(SDI->getOperand(0), SDI->getOperand(1),
378 SDI->getName(), SDI);
379 BO->setIsExact(SDI->isExact());
380 SDI->replaceAllUsesWith(BO);
381 SDI->eraseFromParent();
386 static bool processAShr(BinaryOperator *SDI, LazyValueInfo *LVI) {
387 if (SDI->getType()->isVectorTy() || hasLocalDefs(SDI))
390 Constant *Zero = ConstantInt::get(SDI->getType(), 0);
391 if (LVI->getPredicateAt(ICmpInst::ICMP_SGE, SDI->getOperand(0), Zero, SDI) !=
396 auto *BO = BinaryOperator::CreateLShr(SDI->getOperand(0), SDI->getOperand(1),
397 SDI->getName(), SDI);
398 BO->setIsExact(SDI->isExact());
399 SDI->replaceAllUsesWith(BO);
400 SDI->eraseFromParent();
405 static bool processAdd(BinaryOperator *AddOp, LazyValueInfo *LVI) {
406 typedef OverflowingBinaryOperator OBO;
408 if (AddOp->getType()->isVectorTy() || hasLocalDefs(AddOp))
411 bool NSW = AddOp->hasNoSignedWrap();
412 bool NUW = AddOp->hasNoUnsignedWrap();
416 BasicBlock *BB = AddOp->getParent();
418 Value *LHS = AddOp->getOperand(0);
419 Value *RHS = AddOp->getOperand(1);
421 ConstantRange LRange = LVI->getConstantRange(LHS, BB, AddOp);
423 // Initialize RRange only if we need it. If we know that guaranteed no wrap
424 // range for the given LHS range is empty don't spend time calculating the
425 // range for the RHS.
426 Optional<ConstantRange> RRange;
427 auto LazyRRange = [&] () {
429 RRange = LVI->getConstantRange(RHS, BB, AddOp);
430 return RRange.getValue();
433 bool Changed = false;
435 ConstantRange NUWRange =
436 LRange.makeGuaranteedNoWrapRegion(BinaryOperator::Add, LRange,
437 OBO::NoUnsignedWrap);
438 if (!NUWRange.isEmptySet()) {
439 bool NewNUW = NUWRange.contains(LazyRRange());
440 AddOp->setHasNoUnsignedWrap(NewNUW);
445 ConstantRange NSWRange =
446 LRange.makeGuaranteedNoWrapRegion(BinaryOperator::Add, LRange,
448 if (!NSWRange.isEmptySet()) {
449 bool NewNSW = NSWRange.contains(LazyRRange());
450 AddOp->setHasNoSignedWrap(NewNSW);
458 static Constant *getConstantAt(Value *V, Instruction *At, LazyValueInfo *LVI) {
459 if (Constant *C = LVI->getConstant(V, At->getParent(), At))
462 // TODO: The following really should be sunk inside LVI's core algorithm, or
463 // at least the outer shims around such.
464 auto *C = dyn_cast<CmpInst>(V);
465 if (!C) return nullptr;
467 Value *Op0 = C->getOperand(0);
468 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
469 if (!Op1) return nullptr;
471 LazyValueInfo::Tristate Result =
472 LVI->getPredicateAt(C->getPredicate(), Op0, Op1, At);
473 if (Result == LazyValueInfo::Unknown)
476 return (Result == LazyValueInfo::True) ?
477 ConstantInt::getTrue(C->getContext()) :
478 ConstantInt::getFalse(C->getContext());
481 static bool runImpl(Function &F, LazyValueInfo *LVI) {
482 bool FnChanged = false;
484 // Visiting in a pre-order depth-first traversal causes us to simplify early
485 // blocks before querying later blocks (which require us to analyze early
486 // blocks). Eagerly simplifying shallow blocks means there is strictly less
487 // work to do for deep blocks. This also means we don't visit unreachable
489 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
490 bool BBChanged = false;
491 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
492 Instruction *II = &*BI++;
493 switch (II->getOpcode()) {
494 case Instruction::Select:
495 BBChanged |= processSelect(cast<SelectInst>(II), LVI);
497 case Instruction::PHI:
498 BBChanged |= processPHI(cast<PHINode>(II), LVI);
500 case Instruction::ICmp:
501 case Instruction::FCmp:
502 BBChanged |= processCmp(cast<CmpInst>(II), LVI);
504 case Instruction::Load:
505 case Instruction::Store:
506 BBChanged |= processMemAccess(II, LVI);
508 case Instruction::Call:
509 case Instruction::Invoke:
510 BBChanged |= processCallSite(CallSite(II), LVI);
512 case Instruction::SRem:
513 BBChanged |= processSRem(cast<BinaryOperator>(II), LVI);
515 case Instruction::SDiv:
516 BBChanged |= processSDiv(cast<BinaryOperator>(II), LVI);
518 case Instruction::AShr:
519 BBChanged |= processAShr(cast<BinaryOperator>(II), LVI);
521 case Instruction::Add:
522 BBChanged |= processAdd(cast<BinaryOperator>(II), LVI);
527 Instruction *Term = BB->getTerminator();
528 switch (Term->getOpcode()) {
529 case Instruction::Switch:
530 BBChanged |= processSwitch(cast<SwitchInst>(Term), LVI);
532 case Instruction::Ret: {
533 auto *RI = cast<ReturnInst>(Term);
534 // Try to determine the return value if we can. This is mainly here to
535 // simplify the writing of unit tests, but also helps to enable IPO by
536 // constant folding the return values of callees.
537 auto *RetVal = RI->getReturnValue();
538 if (!RetVal) break; // handle "ret void"
539 if (isa<Constant>(RetVal)) break; // nothing to do
540 if (auto *C = getConstantAt(RetVal, RI, LVI)) {
542 RI->replaceUsesOfWith(RetVal, C);
548 FnChanged |= BBChanged;
554 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
558 LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
559 return runImpl(F, LVI);
563 CorrelatedValuePropagationPass::run(Function &F, FunctionAnalysisManager &AM) {
565 LazyValueInfo *LVI = &AM.getResult<LazyValueAnalysis>(F);
566 bool Changed = runImpl(F, LVI);
568 // FIXME: We need to invalidate LVI to avoid PR28400. Is there a better
570 AM.invalidate<LazyValueAnalysis>(F);
573 return PreservedAnalyses::all();
574 PreservedAnalyses PA;
575 PA.preserve<GlobalsAA>();