LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
CorrelatedValuePropagation.cpp
Go to the documentation of this file.
1 //===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Correlated Value Propagation pass.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #define DEBUG_TYPE "correlated-value-propagation"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/ADT/Statistic.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/CFG.h"
24 #include "llvm/Support/Debug.h"
27 using namespace llvm;
28 
29 STATISTIC(NumPhis, "Number of phis propagated");
30 STATISTIC(NumSelects, "Number of selects propagated");
31 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
32 STATISTIC(NumCmps, "Number of comparisons propagated");
33 STATISTIC(NumDeadCases, "Number of switch cases removed");
34 
35 namespace {
36  class CorrelatedValuePropagation : public FunctionPass {
37  LazyValueInfo *LVI;
38 
39  bool processSelect(SelectInst *SI);
40  bool processPHI(PHINode *P);
41  bool processMemAccess(Instruction *I);
42  bool processCmp(CmpInst *C);
43  bool processSwitch(SwitchInst *SI);
44 
45  public:
46  static char ID;
47  CorrelatedValuePropagation(): FunctionPass(ID) {
49  }
50 
51  bool runOnFunction(Function &F);
52 
53  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55  }
56  };
57 }
58 
60 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
61  "Value Propagation", false, false)
63 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
64  "Value Propagation", false, false)
65 
66 // Public interface to the Value Propagation pass
68  return new CorrelatedValuePropagation();
69 }
70 
71 bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
72  if (S->getType()->isVectorTy()) return false;
73  if (isa<Constant>(S->getOperand(0))) return false;
74 
75  Constant *C = LVI->getConstant(S->getOperand(0), S->getParent());
76  if (!C) return false;
77 
79  if (!CI) return false;
80 
81  Value *ReplaceWith = S->getOperand(1);
82  Value *Other = S->getOperand(2);
83  if (!CI->isOne()) std::swap(ReplaceWith, Other);
84  if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
85 
86  S->replaceAllUsesWith(ReplaceWith);
87  S->eraseFromParent();
88 
89  ++NumSelects;
90 
91  return true;
92 }
93 
94 bool CorrelatedValuePropagation::processPHI(PHINode *P) {
95  bool Changed = false;
96 
97  BasicBlock *BB = P->getParent();
98  for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
99  Value *Incoming = P->getIncomingValue(i);
100  if (isa<Constant>(Incoming)) continue;
101 
102  Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB);
103 
104  // Look if the incoming value is a select with a constant but LVI tells us
105  // that the incoming value can never be that constant. In that case replace
106  // the incoming value with the other value of the select. This often allows
107  // us to remove the select later.
108  if (!V) {
109  SelectInst *SI = dyn_cast<SelectInst>(Incoming);
110  if (!SI) continue;
111 
113  if (!C) continue;
114 
115  if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
116  P->getIncomingBlock(i), BB) !=
118  continue;
119 
120  DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
121  V = SI->getTrueValue();
122  }
123 
124  P->setIncomingValue(i, V);
125  Changed = true;
126  }
127 
128  if (Value *V = SimplifyInstruction(P)) {
129  P->replaceAllUsesWith(V);
130  P->eraseFromParent();
131  Changed = true;
132  }
133 
134  if (Changed)
135  ++NumPhis;
136 
137  return Changed;
138 }
139 
140 bool CorrelatedValuePropagation::processMemAccess(Instruction *I) {
141  Value *Pointer = 0;
142  if (LoadInst *L = dyn_cast<LoadInst>(I))
143  Pointer = L->getPointerOperand();
144  else
145  Pointer = cast<StoreInst>(I)->getPointerOperand();
146 
147  if (isa<Constant>(Pointer)) return false;
148 
149  Constant *C = LVI->getConstant(Pointer, I->getParent());
150  if (!C) return false;
151 
152  ++NumMemAccess;
153  I->replaceUsesOfWith(Pointer, C);
154  return true;
155 }
156 
157 /// processCmp - If the value of this comparison could be determined locally,
158 /// constant propagation would already have figured it out. Instead, walk
159 /// the predecessors and statically evaluate the comparison based on information
160 /// available on that edge. If a given static evaluation is true on ALL
161 /// incoming edges, then it's true universally and we can simplify the compare.
162 bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
163  Value *Op0 = C->getOperand(0);
164  if (isa<Instruction>(Op0) &&
165  cast<Instruction>(Op0)->getParent() == C->getParent())
166  return false;
167 
168  Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
169  if (!Op1) return false;
170 
171  pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent());
172  if (PI == PE) return false;
173 
174  LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(),
175  C->getOperand(0), Op1, *PI, C->getParent());
176  if (Result == LazyValueInfo::Unknown) return false;
177 
178  ++PI;
179  while (PI != PE) {
180  LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(),
181  C->getOperand(0), Op1, *PI, C->getParent());
182  if (Res != Result) return false;
183  ++PI;
184  }
185 
186  ++NumCmps;
187 
188  if (Result == LazyValueInfo::True)
190  else
192 
193  C->eraseFromParent();
194 
195  return true;
196 }
197 
198 /// processSwitch - Simplify a switch instruction by removing cases which can
199 /// never fire. If the uselessness of a case could be determined locally then
200 /// constant propagation would already have figured it out. Instead, walk the
201 /// predecessors and statically evaluate cases based on information available
202 /// on that edge. Cases that cannot fire no matter what the incoming edge can
203 /// safely be removed. If a case fires on every incoming edge then the entire
204 /// switch can be removed and replaced with a branch to the case destination.
205 bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
206  Value *Cond = SI->getCondition();
207  BasicBlock *BB = SI->getParent();
208 
209  // If the condition was defined in same block as the switch then LazyValueInfo
210  // currently won't say anything useful about it, though in theory it could.
211  if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
212  return false;
213 
214  // If the switch is unreachable then trying to improve it is a waste of time.
215  pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
216  if (PB == PE) return false;
217 
218  // Analyse each switch case in turn. This is done in reverse order so that
219  // removing a case doesn't cause trouble for the iteration.
220  bool Changed = false;
221  for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE;
222  ) {
223  ConstantInt *Case = CI.getCaseValue();
224 
225  // Check to see if the switch condition is equal to/not equal to the case
226  // value on every incoming edge, equal/not equal being the same each time.
228  for (pred_iterator PI = PB; PI != PE; ++PI) {
229  // Is the switch condition equal to the case value?
230  LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
231  Cond, Case, *PI, BB);
232  // Give up on this case if nothing is known.
233  if (Value == LazyValueInfo::Unknown) {
234  State = LazyValueInfo::Unknown;
235  break;
236  }
237 
238  // If this was the first edge to be visited, record that all other edges
239  // need to give the same result.
240  if (PI == PB) {
241  State = Value;
242  continue;
243  }
244 
245  // If this case is known to fire for some edges and known not to fire for
246  // others then there is nothing we can do - give up.
247  if (Value != State) {
248  State = LazyValueInfo::Unknown;
249  break;
250  }
251  }
252 
253  if (State == LazyValueInfo::False) {
254  // This case never fires - remove it.
255  CI.getCaseSuccessor()->removePredecessor(BB);
256  SI->removeCase(CI); // Does not invalidate the iterator.
257 
258  // The condition can be modified by removePredecessor's PHI simplification
259  // logic.
260  Cond = SI->getCondition();
261 
262  ++NumDeadCases;
263  Changed = true;
264  } else if (State == LazyValueInfo::True) {
265  // This case always fires. Arrange for the switch to be turned into an
266  // unconditional branch by replacing the switch condition with the case
267  // value.
268  SI->setCondition(Case);
269  NumDeadCases += SI->getNumCases();
270  Changed = true;
271  break;
272  }
273  }
274 
275  if (Changed)
276  // If the switch has been simplified to the point where it can be replaced
277  // by a branch then do so now.
279 
280  return Changed;
281 }
282 
283 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
284  LVI = &getAnalysis<LazyValueInfo>();
285 
286  bool FnChanged = false;
287 
288  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
289  bool BBChanged = false;
290  for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
291  Instruction *II = BI++;
292  switch (II->getOpcode()) {
293  case Instruction::Select:
294  BBChanged |= processSelect(cast<SelectInst>(II));
295  break;
296  case Instruction::PHI:
297  BBChanged |= processPHI(cast<PHINode>(II));
298  break;
299  case Instruction::ICmp:
300  case Instruction::FCmp:
301  BBChanged |= processCmp(cast<CmpInst>(II));
302  break;
303  case Instruction::Load:
304  case Instruction::Store:
305  BBChanged |= processMemAccess(II);
306  break;
307  }
308  }
309 
310  Instruction *Term = FI->getTerminator();
311  switch (Term->getOpcode()) {
312  case Instruction::Switch:
313  BBChanged |= processSwitch(cast<SwitchInst>(Term));
314  break;
315  }
316 
317  FnChanged |= BBChanged;
318  }
319 
320  return FnChanged;
321 }
STATISTIC(NumPhis,"Number of phis propagated")
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:445
Abstract base class of comparison instructions.
Definition: InstrTypes.h:633
static PassRegistry * getPassRegistry()
iterator end()
Definition: Function.h:397
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:266
INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation,"correlated-propagation","Value Propagation", false, false) INITIALIZE_PASS_END(CorrelatedValuePropagation
F(f)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:167
static Value * getPointerOperand(Instruction &Inst)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:172
ID
LLVM Calling Convention Representation.
Definition: CallingConv.h:26
void replaceAllUsesWith(Value *V)
Definition: Value.cpp:303
iterator begin()
Definition: Function.h:395
unsigned getNumIncomingValues() const
void replaceUsesOfWith(Value *From, Value *To)
Definition: User.cpp:26
Pass * createCorrelatedValuePropagationPass()
#define P(N)
LLVM Basic Block Representation.
Definition: BasicBlock.h:72
bool isVectorTy() const
Definition: Type.h:229
LLVM Constant Representation.
Definition: Constant.h:41
Interval::pred_iterator pred_begin(Interval *I)
Definition: Interval.h:117
correlated Value Propagation
BasicBlock * getIncomingBlock(unsigned i) const
Value * getOperand(unsigned i) const
Definition: User.h:88
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:120
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:714
static UndefValue * get(Type *T)
Definition: Constants.cpp:1334
Value * SimplifyInstruction(Instruction *I, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0, const DominatorTree *DT=0)
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:517
const Value * getTrueValue() const
Tristate
Tristate - This is used to return true/false/dunno results.
Definition: LazyValueInfo.h:42
Class for constant integers.
Definition: Constants.h:51
void initializeCorrelatedValuePropagationPass(PassRegistry &)
Value * getIncomingValue(unsigned i) const
Type * getType() const
Definition: Value.h:111
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=0)
Definition: Local.cpp:59
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:438
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
Definition: Debug.cpp:101
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:591
Value * getCondition() const
correlated propagation
void setCondition(Value *V)
#define I(x, y, z)
Definition: MD5.cpp:54
void removeCase(CaseIt i)
unsigned getNumCases() const
correlated Value false
LLVM Value Representation.
Definition: Value.h:66
unsigned getOpcode() const
getOpcode() returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:83
static const Function * getParent(const Value *V)
#define DEBUG(X)
Definition: Debug.h:97
const Value * getFalseValue() const
void setIncomingValue(unsigned i, Value *V)
const BasicBlock * getParent() const
Definition: Instruction.h:52
bool isOne() const
Determine if the value is one.
Definition: Constants.h:168