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/InstructionSimplify.h"
17 #include "llvm/Analysis/LazyValueInfo.h"
18 #include "llvm/IR/CFG.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Transforms/Utils/Local.h"
28 #define DEBUG_TYPE "correlated-value-propagation"
30 STATISTIC(NumPhis, "Number of phis propagated");
31 STATISTIC(NumSelects, "Number of selects propagated");
32 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
33 STATISTIC(NumCmps, "Number of comparisons propagated");
34 STATISTIC(NumDeadCases, "Number of switch cases removed");
37 class CorrelatedValuePropagation : public FunctionPass {
40 bool processSelect(SelectInst *SI);
41 bool processPHI(PHINode *P);
42 bool processMemAccess(Instruction *I);
43 bool processCmp(CmpInst *C);
44 bool processSwitch(SwitchInst *SI);
48 CorrelatedValuePropagation(): FunctionPass(ID) {
49 initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
52 bool runOnFunction(Function &F) override;
54 void getAnalysisUsage(AnalysisUsage &AU) const override {
55 AU.addRequired<LazyValueInfo>();
60 char CorrelatedValuePropagation::ID = 0;
61 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
62 "Value Propagation", false, false)
63 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
64 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
65 "Value Propagation", false, false)
67 // Public interface to the Value Propagation pass
68 Pass *llvm::createCorrelatedValuePropagationPass() {
69 return new CorrelatedValuePropagation();
72 bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
73 if (S->getType()->isVectorTy()) return false;
74 if (isa<Constant>(S->getOperand(0))) return false;
76 Constant *C = LVI->getConstant(S->getOperand(0), S->getParent());
79 ConstantInt *CI = dyn_cast<ConstantInt>(C);
80 if (!CI) return false;
82 Value *ReplaceWith = S->getOperand(1);
83 Value *Other = S->getOperand(2);
84 if (!CI->isOne()) std::swap(ReplaceWith, Other);
85 if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
87 S->replaceAllUsesWith(ReplaceWith);
95 bool CorrelatedValuePropagation::processPHI(PHINode *P) {
98 BasicBlock *BB = P->getParent();
99 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
100 Value *Incoming = P->getIncomingValue(i);
101 if (isa<Constant>(Incoming)) continue;
103 Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB);
105 // Look if the incoming value is a select with a constant but LVI tells us
106 // that the incoming value can never be that constant. In that case replace
107 // the incoming value with the other value of the select. This often allows
108 // us to remove the select later.
110 SelectInst *SI = dyn_cast<SelectInst>(Incoming);
113 Constant *C = dyn_cast<Constant>(SI->getFalseValue());
116 if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
117 P->getIncomingBlock(i), BB) !=
118 LazyValueInfo::False)
121 DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
122 V = SI->getTrueValue();
125 P->setIncomingValue(i, V);
129 // FIXME: Provide DL, TLI, DT, AT to SimplifyInstruction.
130 if (Value *V = SimplifyInstruction(P)) {
131 P->replaceAllUsesWith(V);
132 P->eraseFromParent();
142 bool CorrelatedValuePropagation::processMemAccess(Instruction *I) {
143 Value *Pointer = nullptr;
144 if (LoadInst *L = dyn_cast<LoadInst>(I))
145 Pointer = L->getPointerOperand();
147 Pointer = cast<StoreInst>(I)->getPointerOperand();
149 if (isa<Constant>(Pointer)) return false;
151 Constant *C = LVI->getConstant(Pointer, I->getParent());
152 if (!C) return false;
155 I->replaceUsesOfWith(Pointer, C);
159 /// processCmp - If the value of this comparison could be determined locally,
160 /// constant propagation would already have figured it out. Instead, walk
161 /// the predecessors and statically evaluate the comparison based on information
162 /// available on that edge. If a given static evaluation is true on ALL
163 /// incoming edges, then it's true universally and we can simplify the compare.
164 bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
165 Value *Op0 = C->getOperand(0);
166 if (isa<Instruction>(Op0) &&
167 cast<Instruction>(Op0)->getParent() == C->getParent())
170 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
171 if (!Op1) return false;
173 pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent());
174 if (PI == PE) return false;
176 LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(),
177 C->getOperand(0), Op1, *PI, C->getParent());
178 if (Result == LazyValueInfo::Unknown) return false;
182 LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(),
183 C->getOperand(0), Op1, *PI, C->getParent());
184 if (Res != Result) return false;
190 if (Result == LazyValueInfo::True)
191 C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
193 C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
195 C->eraseFromParent();
200 /// processSwitch - Simplify a switch instruction by removing cases which can
201 /// never fire. If the uselessness of a case could be determined locally then
202 /// constant propagation would already have figured it out. Instead, walk the
203 /// predecessors and statically evaluate cases based on information available
204 /// on that edge. Cases that cannot fire no matter what the incoming edge can
205 /// safely be removed. If a case fires on every incoming edge then the entire
206 /// switch can be removed and replaced with a branch to the case destination.
207 bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
208 Value *Cond = SI->getCondition();
209 BasicBlock *BB = SI->getParent();
211 // If the condition was defined in same block as the switch then LazyValueInfo
212 // currently won't say anything useful about it, though in theory it could.
213 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
216 // If the switch is unreachable then trying to improve it is a waste of time.
217 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
218 if (PB == PE) return false;
220 // Analyse each switch case in turn. This is done in reverse order so that
221 // removing a case doesn't cause trouble for the iteration.
222 bool Changed = false;
223 for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE;
225 ConstantInt *Case = CI.getCaseValue();
227 // Check to see if the switch condition is equal to/not equal to the case
228 // value on every incoming edge, equal/not equal being the same each time.
229 LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
230 for (pred_iterator PI = PB; PI != PE; ++PI) {
231 // Is the switch condition equal to the case value?
232 LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
233 Cond, Case, *PI, BB);
234 // Give up on this case if nothing is known.
235 if (Value == LazyValueInfo::Unknown) {
236 State = LazyValueInfo::Unknown;
240 // If this was the first edge to be visited, record that all other edges
241 // need to give the same result.
247 // If this case is known to fire for some edges and known not to fire for
248 // others then there is nothing we can do - give up.
249 if (Value != State) {
250 State = LazyValueInfo::Unknown;
255 if (State == LazyValueInfo::False) {
256 // This case never fires - remove it.
257 CI.getCaseSuccessor()->removePredecessor(BB);
258 SI->removeCase(CI); // Does not invalidate the iterator.
260 // The condition can be modified by removePredecessor's PHI simplification
262 Cond = SI->getCondition();
266 } else if (State == LazyValueInfo::True) {
267 // This case always fires. Arrange for the switch to be turned into an
268 // unconditional branch by replacing the switch condition with the case
270 SI->setCondition(Case);
271 NumDeadCases += SI->getNumCases();
278 // If the switch has been simplified to the point where it can be replaced
279 // by a branch then do so now.
280 ConstantFoldTerminator(BB);
285 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
286 if (skipOptnoneFunction(F))
289 LVI = &getAnalysis<LazyValueInfo>();
291 bool FnChanged = false;
293 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
294 bool BBChanged = false;
295 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
296 Instruction *II = BI++;
297 switch (II->getOpcode()) {
298 case Instruction::Select:
299 BBChanged |= processSelect(cast<SelectInst>(II));
301 case Instruction::PHI:
302 BBChanged |= processPHI(cast<PHINode>(II));
304 case Instruction::ICmp:
305 case Instruction::FCmp:
306 BBChanged |= processCmp(cast<CmpInst>(II));
308 case Instruction::Load:
309 case Instruction::Store:
310 BBChanged |= processMemAccess(II);
315 Instruction *Term = FI->getTerminator();
316 switch (Term->getOpcode()) {
317 case Instruction::Switch:
318 BBChanged |= processSwitch(cast<SwitchInst>(Term));
322 FnChanged |= BBChanged;