LLVM  3.7.0
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 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/ADT/Statistic.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/IR/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/Debug.h"
27 using namespace llvm;
28 
29 #define DEBUG_TYPE "correlated-value-propagation"
30 
31 STATISTIC(NumPhis, "Number of phis propagated");
32 STATISTIC(NumSelects, "Number of selects propagated");
33 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
34 STATISTIC(NumCmps, "Number of comparisons propagated");
35 STATISTIC(NumDeadCases, "Number of switch cases removed");
36 
37 namespace {
38  class CorrelatedValuePropagation : public FunctionPass {
39  LazyValueInfo *LVI;
40 
41  bool processSelect(SelectInst *SI);
42  bool processPHI(PHINode *P);
43  bool processMemAccess(Instruction *I);
44  bool processCmp(CmpInst *C);
45  bool processSwitch(SwitchInst *SI);
46 
47  public:
48  static char ID;
49  CorrelatedValuePropagation(): FunctionPass(ID) {
51  }
52 
53  bool runOnFunction(Function &F) override;
54 
55  void getAnalysisUsage(AnalysisUsage &AU) const override {
57  }
58  };
59 }
60 
62 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
63  "Value Propagation", false, false)
65 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
66  "Value Propagation", false, false)
67 
68 // Public interface to the Value Propagation pass
70  return new CorrelatedValuePropagation();
71 }
72 
73 bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
74  if (S->getType()->isVectorTy()) return false;
75  if (isa<Constant>(S->getOperand(0))) return false;
76 
77  Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S);
78  if (!C) return false;
79 
81  if (!CI) return false;
82 
83  Value *ReplaceWith = S->getOperand(1);
84  Value *Other = S->getOperand(2);
85  if (!CI->isOne()) std::swap(ReplaceWith, Other);
86  if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
87 
88  S->replaceAllUsesWith(ReplaceWith);
89  S->eraseFromParent();
90 
91  ++NumSelects;
92 
93  return true;
94 }
95 
96 bool CorrelatedValuePropagation::processPHI(PHINode *P) {
97  bool Changed = false;
98 
99  BasicBlock *BB = P->getParent();
100  for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
101  Value *Incoming = P->getIncomingValue(i);
102  if (isa<Constant>(Incoming)) continue;
103 
104  Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P);
105 
106  // Look if the incoming value is a select with a scalar condition for which
107  // LVI can tells us the value. In that case replace the incoming value with
108  // the appropriate value of the select. This often allows us to remove the
109  // select later.
110  if (!V) {
111  SelectInst *SI = dyn_cast<SelectInst>(Incoming);
112  if (!SI) continue;
113 
114  Value *Condition = SI->getCondition();
115  if (!Condition->getType()->isVectorTy()) {
116  if (Constant *C = LVI->getConstantOnEdge(
117  Condition, P->getIncomingBlock(i), BB, P)) {
118  if (C->isOneValue()) {
119  V = SI->getTrueValue();
120  } else if (C->isZeroValue()) {
121  V = SI->getFalseValue();
122  }
123  // Once LVI learns to handle vector types, we could also add support
124  // for vector type constants that are not all zeroes or all ones.
125  }
126  }
127 
128  // Look if the select has a constant but LVI tells us that the incoming
129  // value can never be that constant. In that case replace the incoming
130  // value with the other value of the select. This often allows us to
131  // remove the select later.
132  if (!V) {
134  if (!C) continue;
135 
136  if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
137  P->getIncomingBlock(i), BB, P) !=
139  continue;
140  V = SI->getTrueValue();
141  }
142 
143  DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
144  }
145 
146  P->setIncomingValue(i, V);
147  Changed = true;
148  }
149 
150  // FIXME: Provide TLI, DT, AT to SimplifyInstruction.
151  const DataLayout &DL = BB->getModule()->getDataLayout();
152  if (Value *V = SimplifyInstruction(P, DL)) {
153  P->replaceAllUsesWith(V);
154  P->eraseFromParent();
155  Changed = true;
156  }
157 
158  if (Changed)
159  ++NumPhis;
160 
161  return Changed;
162 }
163 
164 bool CorrelatedValuePropagation::processMemAccess(Instruction *I) {
165  Value *Pointer = nullptr;
166  if (LoadInst *L = dyn_cast<LoadInst>(I))
167  Pointer = L->getPointerOperand();
168  else
169  Pointer = cast<StoreInst>(I)->getPointerOperand();
170 
171  if (isa<Constant>(Pointer)) return false;
172 
173  Constant *C = LVI->getConstant(Pointer, I->getParent(), I);
174  if (!C) return false;
175 
176  ++NumMemAccess;
177  I->replaceUsesOfWith(Pointer, C);
178  return true;
179 }
180 
181 /// processCmp - If the value of this comparison could be determined locally,
182 /// constant propagation would already have figured it out. Instead, walk
183 /// the predecessors and statically evaluate the comparison based on information
184 /// available on that edge. If a given static evaluation is true on ALL
185 /// incoming edges, then it's true universally and we can simplify the compare.
186 bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
187  Value *Op0 = C->getOperand(0);
188  if (isa<Instruction>(Op0) &&
189  cast<Instruction>(Op0)->getParent() == C->getParent())
190  return false;
191 
192  Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
193  if (!Op1) return false;
194 
195  pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent());
196  if (PI == PE) return false;
197 
198  LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(),
199  C->getOperand(0), Op1, *PI,
200  C->getParent(), C);
201  if (Result == LazyValueInfo::Unknown) return false;
202 
203  ++PI;
204  while (PI != PE) {
205  LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(),
206  C->getOperand(0), Op1, *PI,
207  C->getParent(), C);
208  if (Res != Result) return false;
209  ++PI;
210  }
211 
212  ++NumCmps;
213 
214  if (Result == LazyValueInfo::True)
216  else
218 
219  C->eraseFromParent();
220 
221  return true;
222 }
223 
224 /// processSwitch - Simplify a switch instruction by removing cases which can
225 /// never fire. If the uselessness of a case could be determined locally then
226 /// constant propagation would already have figured it out. Instead, walk the
227 /// predecessors and statically evaluate cases based on information available
228 /// on that edge. Cases that cannot fire no matter what the incoming edge can
229 /// safely be removed. If a case fires on every incoming edge then the entire
230 /// switch can be removed and replaced with a branch to the case destination.
231 bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
232  Value *Cond = SI->getCondition();
233  BasicBlock *BB = SI->getParent();
234 
235  // If the condition was defined in same block as the switch then LazyValueInfo
236  // currently won't say anything useful about it, though in theory it could.
237  if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
238  return false;
239 
240  // If the switch is unreachable then trying to improve it is a waste of time.
241  pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
242  if (PB == PE) return false;
243 
244  // Analyse each switch case in turn. This is done in reverse order so that
245  // removing a case doesn't cause trouble for the iteration.
246  bool Changed = false;
247  for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE;
248  ) {
249  ConstantInt *Case = CI.getCaseValue();
250 
251  // Check to see if the switch condition is equal to/not equal to the case
252  // value on every incoming edge, equal/not equal being the same each time.
254  for (pred_iterator PI = PB; PI != PE; ++PI) {
255  // Is the switch condition equal to the case value?
256  LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
257  Cond, Case, *PI,
258  BB, SI);
259  // Give up on this case if nothing is known.
260  if (Value == LazyValueInfo::Unknown) {
261  State = LazyValueInfo::Unknown;
262  break;
263  }
264 
265  // If this was the first edge to be visited, record that all other edges
266  // need to give the same result.
267  if (PI == PB) {
268  State = Value;
269  continue;
270  }
271 
272  // If this case is known to fire for some edges and known not to fire for
273  // others then there is nothing we can do - give up.
274  if (Value != State) {
275  State = LazyValueInfo::Unknown;
276  break;
277  }
278  }
279 
280  if (State == LazyValueInfo::False) {
281  // This case never fires - remove it.
282  CI.getCaseSuccessor()->removePredecessor(BB);
283  SI->removeCase(CI); // Does not invalidate the iterator.
284 
285  // The condition can be modified by removePredecessor's PHI simplification
286  // logic.
287  Cond = SI->getCondition();
288 
289  ++NumDeadCases;
290  Changed = true;
291  } else if (State == LazyValueInfo::True) {
292  // This case always fires. Arrange for the switch to be turned into an
293  // unconditional branch by replacing the switch condition with the case
294  // value.
295  SI->setCondition(Case);
296  NumDeadCases += SI->getNumCases();
297  Changed = true;
298  break;
299  }
300  }
301 
302  if (Changed)
303  // If the switch has been simplified to the point where it can be replaced
304  // by a branch then do so now.
306 
307  return Changed;
308 }
309 
310 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
311  if (skipOptnoneFunction(F))
312  return false;
313 
314  LVI = &getAnalysis<LazyValueInfo>();
315 
316  bool FnChanged = false;
317 
318  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
319  bool BBChanged = false;
320  for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
321  Instruction *II = BI++;
322  switch (II->getOpcode()) {
323  case Instruction::Select:
324  BBChanged |= processSelect(cast<SelectInst>(II));
325  break;
326  case Instruction::PHI:
327  BBChanged |= processPHI(cast<PHINode>(II));
328  break;
329  case Instruction::ICmp:
330  case Instruction::FCmp:
331  BBChanged |= processCmp(cast<CmpInst>(II));
332  break;
333  case Instruction::Load:
334  case Instruction::Store:
335  BBChanged |= processMemAccess(II);
336  break;
337  }
338  }
339 
340  Instruction *Term = FI->getTerminator();
341  switch (Term->getOpcode()) {
342  case Instruction::Switch:
343  BBChanged |= processSwitch(cast<SwitchInst>(Term));
344  break;
345  }
346 
347  FnChanged |= BBChanged;
348  }
349 
350  return FnChanged;
351 }
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:82
iplist< Instruction >::iterator eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing basic block and deletes it...
Definition: Instruction.cpp:70
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:104
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:537
CaseIt case_end()
Returns a read/write iterator that points one past the last in the SwitchInst.
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:679
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
STATISTIC(NumFunctions,"Total number of functions")
iterator end()
Definition: Function.h:459
bool isOneValue() const
Returns true if the value is one.
Definition: Constants.cpp:110
CaseIt case_begin()
Returns a read/write iterator that points to the first case in SwitchInst.
INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation,"correlated-propagation","Value Propagation", false, false) INITIALIZE_PASS_END(CorrelatedValuePropagation
F(f)
LoadInst - an instruction for reading from memory.
Definition: Instructions.h:177
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:70
static Value * getPointerOperand(Instruction &Inst)
SelectInst - This class represents the LLVM 'select' instruction.
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr it the function does no...
Definition: BasicBlock.cpp:116
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldTerminator - If a terminator instruction is predicated on a constant value, convert it into an unconditional branch to the constant destination.
Definition: Local.cpp:64
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:75
Windows NT (Windows on ARM)
ELFYAML::ELF_STO Other
Definition: ELFYAML.cpp:591
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:351
iterator begin()
Definition: Function.h:457
unsigned getNumIncomingValues() const
getNumIncomingValues - Return the number of incoming edges
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition: User.cpp:24
Pass * createCorrelatedValuePropagationPass()
#define P(N)
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
bool isVectorTy() const
isVectorTy - True if this is an instance of VectorType.
Definition: Type.h:226
This is an important base class in LLVM.
Definition: Constant.h:41
const Value * getCondition() const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isZeroValue() const
Return true if the value is negative zero or null value.
Definition: Constants.cpp:66
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:114
correlated Value Propagation
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
getIncomingBlock - Return incoming basic block number i.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:294
Value * getOperand(unsigned i) const
Definition: User.h:118
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:117
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:760
static UndefValue * get(Type *T)
get() - Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1473
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:519
const Value * getTrueValue() const
Tristate
This is used to return true/false/dunno results.
Definition: LazyValueInfo.h:45
This is the shared class of boolean and integer constants.
Definition: Constants.h:47
void initializeCorrelatedValuePropagationPass(PassRegistry &)
Value * getIncomingValue(unsigned i) const
getIncomingValue - Return incoming value number x
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:222
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:530
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:123
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:576
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:285
Value * getCondition() const
correlated propagation
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:372
void setCondition(Value *V)
#define I(x, y, z)
Definition: MD5.cpp:54
void removeCase(CaseIt i)
removeCase - This method removes the specified case and its successor from the switch instruction...
unsigned getNumCases() const
getNumCases - return the number of 'cases' in this switch instruction, except the default case ...
correlated Value false
SwitchInst - Multiway switch.
This pass computes, caches, and vends lazy value constraint information.
Definition: LazyValueInfo.h:30
LLVM Value Representation.
Definition: Value.h:69
unsigned getOpcode() const
getOpcode() returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:112
static const Function * getParent(const Value *V)
#define DEBUG(X)
Definition: Debug.h:92
const Value * getFalseValue() const
Value * SimplifyInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr)
SimplifyInstruction - See if we can compute a simplified version of this instruction.
void setIncomingValue(unsigned i, Value *V)
const BasicBlock * getParent() const
Definition: Instruction.h:72
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition: Constants.h:169