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 #define DEBUG_TYPE "correlated-value-propagation"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Function.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Analysis/LazyValueInfo.h"
20 #include "llvm/Transforms/Utils/Local.h"
21 #include "llvm/ADT/Statistic.h"
24 STATISTIC(NumPhis, "Number of phis propagated");
25 STATISTIC(NumSelects, "Number of selects propagated");
28 class CorrelatedValuePropagation : public FunctionPass {
31 bool processSelect(SelectInst *SI);
32 bool processPHI(PHINode *P);
36 CorrelatedValuePropagation(): FunctionPass(ID) { }
38 bool runOnFunction(Function &F);
40 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41 AU.addRequired<LazyValueInfo>();
46 char CorrelatedValuePropagation::ID = 0;
47 INITIALIZE_PASS(CorrelatedValuePropagation, "correlated-propagation",
48 "Value Propagation", false, false);
50 // Public interface to the Value Propagation pass
51 Pass *llvm::createCorrelatedValuePropagationPass() {
52 return new CorrelatedValuePropagation();
55 bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
56 if (S->getType()->isVectorTy()) return false;
58 Constant *C = LVI->getConstant(S->getOperand(0), S->getParent());
61 ConstantInt *CI = dyn_cast<ConstantInt>(C);
62 if (!CI) return false;
64 S->replaceAllUsesWith(S->getOperand(CI->isOne() ? 1 : 2));
72 bool CorrelatedValuePropagation::processPHI(PHINode *P) {
75 BasicBlock *BB = P->getParent();
76 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
77 Value *Incoming = P->getIncomingValue(i);
78 if (isa<Constant>(Incoming)) continue;
80 Constant *C = LVI->getConstantOnEdge(P->getIncomingValue(i),
81 P->getIncomingBlock(i),
85 P->setIncomingValue(i, C);
89 if (Value *ConstVal = P->hasConstantValue()) {
90 P->replaceAllUsesWith(ConstVal);
100 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
101 LVI = &getAnalysis<LazyValueInfo>();
103 bool FnChanged = false;
105 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
106 bool BBChanged = false;
107 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
108 Instruction *II = BI++;
109 if (SelectInst *SI = dyn_cast<SelectInst>(II))
110 BBChanged |= processSelect(SI);
111 else if (PHINode *P = dyn_cast<PHINode>(II))
112 BBChanged |= processPHI(P);
115 // Propagating correlated values might leave cruft around.
116 // Try to clean it up before we continue.
118 SimplifyInstructionsInBlock(FI);
120 FnChanged |= BBChanged;