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.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/GlobalsModRef.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/LazyValueInfo.h"
19 #include "llvm/IR/CFG.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Transforms/Utils/Local.h"
30 #define DEBUG_TYPE "correlated-value-propagation"
32 STATISTIC(NumPhis, "Number of phis propagated");
33 STATISTIC(NumSelects, "Number of selects propagated");
34 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
35 STATISTIC(NumCmps, "Number of comparisons propagated");
36 STATISTIC(NumDeadCases, "Number of switch cases removed");
39 class CorrelatedValuePropagation : public FunctionPass {
42 bool processSelect(SelectInst *SI);
43 bool processPHI(PHINode *P);
44 bool processMemAccess(Instruction *I);
45 bool processCmp(CmpInst *C);
46 bool processSwitch(SwitchInst *SI);
47 bool processCallSite(CallSite CS);
51 CorrelatedValuePropagation(): FunctionPass(ID) {
52 initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
55 bool runOnFunction(Function &F) override;
57 void getAnalysisUsage(AnalysisUsage &AU) const override {
58 AU.addRequired<LazyValueInfo>();
59 AU.addPreserved<GlobalsAAWrapperPass>();
64 char CorrelatedValuePropagation::ID = 0;
65 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
66 "Value Propagation", false, false)
67 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
68 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
69 "Value Propagation", false, false)
71 // Public interface to the Value Propagation pass
72 Pass *llvm::createCorrelatedValuePropagationPass() {
73 return new CorrelatedValuePropagation();
76 bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
77 if (S->getType()->isVectorTy()) return false;
78 if (isa<Constant>(S->getOperand(0))) return false;
80 Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S);
83 ConstantInt *CI = dyn_cast<ConstantInt>(C);
84 if (!CI) return false;
86 Value *ReplaceWith = S->getOperand(1);
87 Value *Other = S->getOperand(2);
88 if (!CI->isOne()) std::swap(ReplaceWith, Other);
89 if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
91 S->replaceAllUsesWith(ReplaceWith);
99 bool CorrelatedValuePropagation::processPHI(PHINode *P) {
100 bool Changed = false;
102 BasicBlock *BB = P->getParent();
103 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
104 Value *Incoming = P->getIncomingValue(i);
105 if (isa<Constant>(Incoming)) continue;
107 Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P);
109 // Look if the incoming value is a select with a scalar condition for which
110 // LVI can tells us the value. In that case replace the incoming value with
111 // the appropriate value of the select. This often allows us to remove the
114 SelectInst *SI = dyn_cast<SelectInst>(Incoming);
117 Value *Condition = SI->getCondition();
118 if (!Condition->getType()->isVectorTy()) {
119 if (Constant *C = LVI->getConstantOnEdge(
120 Condition, P->getIncomingBlock(i), BB, P)) {
121 if (C->isOneValue()) {
122 V = SI->getTrueValue();
123 } else if (C->isZeroValue()) {
124 V = SI->getFalseValue();
126 // Once LVI learns to handle vector types, we could also add support
127 // for vector type constants that are not all zeroes or all ones.
131 // Look if the select has a constant but LVI tells us that the incoming
132 // value can never be that constant. In that case replace the incoming
133 // value with the other value of the select. This often allows us to
134 // remove the select later.
136 Constant *C = dyn_cast<Constant>(SI->getFalseValue());
139 if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
140 P->getIncomingBlock(i), BB, P) !=
141 LazyValueInfo::False)
143 V = SI->getTrueValue();
146 DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
149 P->setIncomingValue(i, V);
153 // FIXME: Provide TLI, DT, AT to SimplifyInstruction.
154 const DataLayout &DL = BB->getModule()->getDataLayout();
155 if (Value *V = SimplifyInstruction(P, DL)) {
156 P->replaceAllUsesWith(V);
157 P->eraseFromParent();
167 bool CorrelatedValuePropagation::processMemAccess(Instruction *I) {
168 Value *Pointer = nullptr;
169 if (LoadInst *L = dyn_cast<LoadInst>(I))
170 Pointer = L->getPointerOperand();
172 Pointer = cast<StoreInst>(I)->getPointerOperand();
174 if (isa<Constant>(Pointer)) return false;
176 Constant *C = LVI->getConstant(Pointer, I->getParent(), I);
177 if (!C) return false;
180 I->replaceUsesOfWith(Pointer, C);
184 /// processCmp - If the value of this comparison could be determined locally,
185 /// constant propagation would already have figured it out. Instead, walk
186 /// the predecessors and statically evaluate the comparison based on information
187 /// available on that edge. If a given static evaluation is true on ALL
188 /// incoming edges, then it's true universally and we can simplify the compare.
189 bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
190 Value *Op0 = C->getOperand(0);
191 if (isa<Instruction>(Op0) &&
192 cast<Instruction>(Op0)->getParent() == C->getParent())
195 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
196 if (!Op1) return false;
198 pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent());
199 if (PI == PE) return false;
201 LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(),
202 C->getOperand(0), Op1, *PI,
204 if (Result == LazyValueInfo::Unknown) return false;
208 LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(),
209 C->getOperand(0), Op1, *PI,
211 if (Res != Result) return false;
217 if (Result == LazyValueInfo::True)
218 C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
220 C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
222 C->eraseFromParent();
227 /// processSwitch - Simplify a switch instruction by removing cases which can
228 /// never fire. If the uselessness of a case could be determined locally then
229 /// constant propagation would already have figured it out. Instead, walk the
230 /// predecessors and statically evaluate cases based on information available
231 /// on that edge. Cases that cannot fire no matter what the incoming edge can
232 /// safely be removed. If a case fires on every incoming edge then the entire
233 /// switch can be removed and replaced with a branch to the case destination.
234 bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
235 Value *Cond = SI->getCondition();
236 BasicBlock *BB = SI->getParent();
238 // If the condition was defined in same block as the switch then LazyValueInfo
239 // currently won't say anything useful about it, though in theory it could.
240 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
243 // If the switch is unreachable then trying to improve it is a waste of time.
244 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
245 if (PB == PE) return false;
247 // Analyse each switch case in turn. This is done in reverse order so that
248 // removing a case doesn't cause trouble for the iteration.
249 bool Changed = false;
250 for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE;
252 ConstantInt *Case = CI.getCaseValue();
254 // Check to see if the switch condition is equal to/not equal to the case
255 // value on every incoming edge, equal/not equal being the same each time.
256 LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
257 for (pred_iterator PI = PB; PI != PE; ++PI) {
258 // Is the switch condition equal to the case value?
259 LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
262 // Give up on this case if nothing is known.
263 if (Value == LazyValueInfo::Unknown) {
264 State = LazyValueInfo::Unknown;
268 // If this was the first edge to be visited, record that all other edges
269 // need to give the same result.
275 // If this case is known to fire for some edges and known not to fire for
276 // others then there is nothing we can do - give up.
277 if (Value != State) {
278 State = LazyValueInfo::Unknown;
283 if (State == LazyValueInfo::False) {
284 // This case never fires - remove it.
285 CI.getCaseSuccessor()->removePredecessor(BB);
286 SI->removeCase(CI); // Does not invalidate the iterator.
288 // The condition can be modified by removePredecessor's PHI simplification
290 Cond = SI->getCondition();
294 } else if (State == LazyValueInfo::True) {
295 // This case always fires. Arrange for the switch to be turned into an
296 // unconditional branch by replacing the switch condition with the case
298 SI->setCondition(Case);
299 NumDeadCases += SI->getNumCases();
306 // If the switch has been simplified to the point where it can be replaced
307 // by a branch then do so now.
308 ConstantFoldTerminator(BB);
313 /// processCallSite - Infer nonnull attributes for the arguments at the
314 /// specified callsite.
315 bool CorrelatedValuePropagation::processCallSite(CallSite CS) {
316 bool Changed = false;
319 for (Value *V : CS.args()) {
320 PointerType *Type = dyn_cast<PointerType>(V->getType());
322 if (Type && !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
323 LVI->getPredicateAt(ICmpInst::ICMP_EQ, V,
324 ConstantPointerNull::get(Type),
325 CS.getInstruction()) == LazyValueInfo::False) {
326 AttributeSet AS = CS.getAttributes();
327 AS = AS.addAttribute(CS.getInstruction()->getContext(), ArgNo + 1,
329 CS.setAttributes(AS);
334 assert(ArgNo == CS.arg_size() && "sanity check");
339 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
340 if (skipOptnoneFunction(F))
343 LVI = &getAnalysis<LazyValueInfo>();
345 bool FnChanged = false;
347 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
348 bool BBChanged = false;
349 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
350 Instruction *II = BI++;
351 switch (II->getOpcode()) {
352 case Instruction::Select:
353 BBChanged |= processSelect(cast<SelectInst>(II));
355 case Instruction::PHI:
356 BBChanged |= processPHI(cast<PHINode>(II));
358 case Instruction::ICmp:
359 case Instruction::FCmp:
360 BBChanged |= processCmp(cast<CmpInst>(II));
362 case Instruction::Load:
363 case Instruction::Store:
364 BBChanged |= processMemAccess(II);
366 case Instruction::Call:
367 case Instruction::Invoke:
368 BBChanged |= processCallSite(CallSite(II));
373 Instruction *Term = FI->getTerminator();
374 switch (Term->getOpcode()) {
375 case Instruction::Switch:
376 BBChanged |= processSwitch(cast<SwitchInst>(Term));
380 FnChanged |= BBChanged;