1 //===- ValuePropagation.cpp - Propagate information derived control flow --===//
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 Value Propagation pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "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 ValuePropagation : public FunctionPass {
31 bool processSelect(SelectInst *SI);
32 bool processPHI(PHINode *P);
36 ValuePropagation(): FunctionPass(ID) { }
38 bool runOnFunction(Function &F);
40 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41 AU.addRequired<LazyValueInfo>();
46 char ValuePropagation::ID = 0;
47 INITIALIZE_PASS(ValuePropagation, "value-propagation",
48 "Value Propagation", false, false);
50 // Public interface to the Value Propagation pass
51 Pass *llvm::createValuePropagationPass() {
52 return new ValuePropagation();
55 bool ValuePropagation::processSelect(SelectInst *S) {
56 Constant *C = LVI->getConstant(S->getOperand(0), S->getParent());
59 ConstantInt *CI = dyn_cast<ConstantInt>(C);
60 if (!CI) return false;
63 S->replaceAllUsesWith(S->getOperand(2));
65 } else if (CI->isOne()) {
66 S->replaceAllUsesWith(S->getOperand(1));
69 assert(0 && "Select on constant is neither 0 nor 1?");
77 bool ValuePropagation::processPHI(PHINode *P) {
80 BasicBlock *BB = P->getParent();
81 for (unsigned i = 0; i < P->getNumIncomingValues(); ++i) {
82 Constant *C = LVI->getConstantOnEdge(P->getIncomingValue(i),
83 P->getIncomingBlock(i),
85 if (!C || C == P->getIncomingValue(i)) continue;
87 P->setIncomingValue(i, C);
91 if (Value *ConstVal = P->hasConstantValue()) {
92 P->replaceAllUsesWith(ConstVal);
102 bool ValuePropagation::runOnFunction(Function &F) {
103 LVI = &getAnalysis<LazyValueInfo>();
105 bool changed = false;
107 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
108 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
109 Instruction *II = BI++;
110 if (SelectInst *SI = dyn_cast<SelectInst>(II))
111 changed |= processSelect(SI);
112 else if (PHINode *P = dyn_cast<PHINode>(II))
113 changed |= processPHI(P);
117 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
118 SimplifyInstructionsInBlock(FI);