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);
50 CorrelatedValuePropagation(): FunctionPass(ID) {
51 initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
54 bool runOnFunction(Function &F) override;
56 void getAnalysisUsage(AnalysisUsage &AU) const override {
57 AU.addRequired<LazyValueInfo>();
58 AU.addPreserved<GlobalsAAWrapperPass>();
63 char CorrelatedValuePropagation::ID = 0;
64 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
65 "Value Propagation", false, false)
66 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
67 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
68 "Value Propagation", false, false)
70 // Public interface to the Value Propagation pass
71 Pass *llvm::createCorrelatedValuePropagationPass() {
72 return new CorrelatedValuePropagation();
75 bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
76 if (S->getType()->isVectorTy()) return false;
77 if (isa<Constant>(S->getOperand(0))) return false;
79 Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S);
82 ConstantInt *CI = dyn_cast<ConstantInt>(C);
83 if (!CI) return false;
85 Value *ReplaceWith = S->getOperand(1);
86 Value *Other = S->getOperand(2);
87 if (!CI->isOne()) std::swap(ReplaceWith, Other);
88 if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
90 S->replaceAllUsesWith(ReplaceWith);
98 bool CorrelatedValuePropagation::processPHI(PHINode *P) {
101 BasicBlock *BB = P->getParent();
102 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
103 Value *Incoming = P->getIncomingValue(i);
104 if (isa<Constant>(Incoming)) continue;
106 Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P);
108 // Look if the incoming value is a select with a scalar condition for which
109 // LVI can tells us the value. In that case replace the incoming value with
110 // the appropriate value of the select. This often allows us to remove the
113 SelectInst *SI = dyn_cast<SelectInst>(Incoming);
116 Value *Condition = SI->getCondition();
117 if (!Condition->getType()->isVectorTy()) {
118 if (Constant *C = LVI->getConstantOnEdge(
119 Condition, P->getIncomingBlock(i), BB, P)) {
120 if (C->isOneValue()) {
121 V = SI->getTrueValue();
122 } else if (C->isZeroValue()) {
123 V = SI->getFalseValue();
125 // Once LVI learns to handle vector types, we could also add support
126 // for vector type constants that are not all zeroes or all ones.
130 // Look if the select has a constant but LVI tells us that the incoming
131 // value can never be that constant. In that case replace the incoming
132 // value with the other value of the select. This often allows us to
133 // remove the select later.
135 Constant *C = dyn_cast<Constant>(SI->getFalseValue());
138 if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
139 P->getIncomingBlock(i), BB, P) !=
140 LazyValueInfo::False)
142 V = SI->getTrueValue();
145 DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
148 P->setIncomingValue(i, V);
152 // FIXME: Provide TLI, DT, AT to SimplifyInstruction.
153 const DataLayout &DL = BB->getModule()->getDataLayout();
154 if (Value *V = SimplifyInstruction(P, DL)) {
155 P->replaceAllUsesWith(V);
156 P->eraseFromParent();
166 bool CorrelatedValuePropagation::processMemAccess(Instruction *I) {
167 Value *Pointer = nullptr;
168 if (LoadInst *L = dyn_cast<LoadInst>(I))
169 Pointer = L->getPointerOperand();
171 Pointer = cast<StoreInst>(I)->getPointerOperand();
173 if (isa<Constant>(Pointer)) return false;
175 Constant *C = LVI->getConstant(Pointer, I->getParent(), I);
176 if (!C) return false;
179 I->replaceUsesOfWith(Pointer, C);
183 /// processCmp - If the value of this comparison could be determined locally,
184 /// constant propagation would already have figured it out. Instead, walk
185 /// the predecessors and statically evaluate the comparison based on information
186 /// available on that edge. If a given static evaluation is true on ALL
187 /// incoming edges, then it's true universally and we can simplify the compare.
188 bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
189 Value *Op0 = C->getOperand(0);
190 if (isa<Instruction>(Op0) &&
191 cast<Instruction>(Op0)->getParent() == C->getParent())
194 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
195 if (!Op1) return false;
197 pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent());
198 if (PI == PE) return false;
200 LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(),
201 C->getOperand(0), Op1, *PI,
203 if (Result == LazyValueInfo::Unknown) return false;
207 LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(),
208 C->getOperand(0), Op1, *PI,
210 if (Res != Result) return false;
216 if (Result == LazyValueInfo::True)
217 C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
219 C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
221 C->eraseFromParent();
226 /// processSwitch - Simplify a switch instruction by removing cases which can
227 /// never fire. If the uselessness of a case could be determined locally then
228 /// constant propagation would already have figured it out. Instead, walk the
229 /// predecessors and statically evaluate cases based on information available
230 /// on that edge. Cases that cannot fire no matter what the incoming edge can
231 /// safely be removed. If a case fires on every incoming edge then the entire
232 /// switch can be removed and replaced with a branch to the case destination.
233 bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
234 Value *Cond = SI->getCondition();
235 BasicBlock *BB = SI->getParent();
237 // If the condition was defined in same block as the switch then LazyValueInfo
238 // currently won't say anything useful about it, though in theory it could.
239 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
242 // If the switch is unreachable then trying to improve it is a waste of time.
243 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
244 if (PB == PE) return false;
246 // Analyse each switch case in turn. This is done in reverse order so that
247 // removing a case doesn't cause trouble for the iteration.
248 bool Changed = false;
249 for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE;
251 ConstantInt *Case = CI.getCaseValue();
253 // Check to see if the switch condition is equal to/not equal to the case
254 // value on every incoming edge, equal/not equal being the same each time.
255 LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
256 for (pred_iterator PI = PB; PI != PE; ++PI) {
257 // Is the switch condition equal to the case value?
258 LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
261 // Give up on this case if nothing is known.
262 if (Value == LazyValueInfo::Unknown) {
263 State = LazyValueInfo::Unknown;
267 // If this was the first edge to be visited, record that all other edges
268 // need to give the same result.
274 // If this case is known to fire for some edges and known not to fire for
275 // others then there is nothing we can do - give up.
276 if (Value != State) {
277 State = LazyValueInfo::Unknown;
282 if (State == LazyValueInfo::False) {
283 // This case never fires - remove it.
284 CI.getCaseSuccessor()->removePredecessor(BB);
285 SI->removeCase(CI); // Does not invalidate the iterator.
287 // The condition can be modified by removePredecessor's PHI simplification
289 Cond = SI->getCondition();
293 } else if (State == LazyValueInfo::True) {
294 // This case always fires. Arrange for the switch to be turned into an
295 // unconditional branch by replacing the switch condition with the case
297 SI->setCondition(Case);
298 NumDeadCases += SI->getNumCases();
305 // If the switch has been simplified to the point where it can be replaced
306 // by a branch then do so now.
307 ConstantFoldTerminator(BB);
312 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
313 if (skipOptnoneFunction(F))
316 LVI = &getAnalysis<LazyValueInfo>();
318 bool FnChanged = false;
320 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
321 bool BBChanged = false;
322 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
323 Instruction *II = BI++;
324 switch (II->getOpcode()) {
325 case Instruction::Select:
326 BBChanged |= processSelect(cast<SelectInst>(II));
328 case Instruction::PHI:
329 BBChanged |= processPHI(cast<PHINode>(II));
331 case Instruction::ICmp:
332 case Instruction::FCmp:
333 BBChanged |= processCmp(cast<CmpInst>(II));
335 case Instruction::Load:
336 case Instruction::Store:
337 BBChanged |= processMemAccess(II);
342 Instruction *Term = FI->getTerminator();
343 switch (Term->getOpcode()) {
344 case Instruction::Switch:
345 BBChanged |= processSwitch(cast<SwitchInst>(Term));
349 FnChanged |= BBChanged;