LLVM  4.0.0
IPConstantPropagation.cpp
Go to the documentation of this file.
1 //===-- IPConstantPropagation.cpp - Propagate constants through calls -----===//
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 pass implements an _extremely_ simple interprocedural constant
11 // propagation pass. It could certainly be improved in many different ways,
12 // like using a worklist. This pass makes arguments dead, but does not remove
13 // them. The existing dead argument elimination pass should be run after this
14 // to clean up the mess.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/Transforms/IPO.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Pass.h"
27 using namespace llvm;
28 
29 #define DEBUG_TYPE "ipconstprop"
30 
31 STATISTIC(NumArgumentsProped, "Number of args turned into constants");
32 STATISTIC(NumReturnValProped, "Number of return values turned into constants");
33 
34 namespace {
35  /// IPCP - The interprocedural constant propagation pass
36  ///
37  struct IPCP : public ModulePass {
38  static char ID; // Pass identification, replacement for typeid
39  IPCP() : ModulePass(ID) {
41  }
42 
43  bool runOnModule(Module &M) override;
44  };
45 }
46 
47 /// PropagateConstantsIntoArguments - Look at all uses of the specified
48 /// function. If all uses are direct call sites, and all pass a particular
49 /// constant in for an argument, propagate that constant in as the argument.
50 ///
52  if (F.arg_empty() || F.use_empty()) return false; // No arguments? Early exit.
53 
54  // For each argument, keep track of its constant value and whether it is a
55  // constant or not. The bool is driven to true when found to be non-constant.
56  SmallVector<std::pair<Constant*, bool>, 16> ArgumentConstants;
57  ArgumentConstants.resize(F.arg_size());
58 
59  unsigned NumNonconstant = 0;
60  for (Use &U : F.uses()) {
61  User *UR = U.getUser();
62  // Ignore blockaddress uses.
63  if (isa<BlockAddress>(UR)) continue;
64 
65  // Used by a non-instruction, or not the callee of a function, do not
66  // transform.
67  if (!isa<CallInst>(UR) && !isa<InvokeInst>(UR))
68  return false;
69 
70  CallSite CS(cast<Instruction>(UR));
71  if (!CS.isCallee(&U))
72  return false;
73 
74  // Check out all of the potentially constant arguments. Note that we don't
75  // inspect varargs here.
78  for (unsigned i = 0, e = ArgumentConstants.size(); i != e;
79  ++i, ++AI, ++Arg) {
80 
81  // If this argument is known non-constant, ignore it.
82  if (ArgumentConstants[i].second)
83  continue;
84 
85  Constant *C = dyn_cast<Constant>(*AI);
86  if (C && ArgumentConstants[i].first == nullptr) {
87  ArgumentConstants[i].first = C; // First constant seen.
88  } else if (C && ArgumentConstants[i].first == C) {
89  // Still the constant value we think it is.
90  } else if (*AI == &*Arg) {
91  // Ignore recursive calls passing argument down.
92  } else {
93  // Argument became non-constant. If all arguments are non-constant now,
94  // give up on this function.
95  if (++NumNonconstant == ArgumentConstants.size())
96  return false;
97  ArgumentConstants[i].second = true;
98  }
99  }
100  }
101 
102  // If we got to this point, there is a constant argument!
103  assert(NumNonconstant != ArgumentConstants.size());
104  bool MadeChange = false;
106  for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI) {
107  // Do we have a constant argument?
108  if (ArgumentConstants[i].second || AI->use_empty() ||
109  AI->hasInAllocaAttr() || (AI->hasByValAttr() && !F.onlyReadsMemory()))
110  continue;
111 
112  Value *V = ArgumentConstants[i].first;
113  if (!V) V = UndefValue::get(AI->getType());
114  AI->replaceAllUsesWith(V);
115  ++NumArgumentsProped;
116  MadeChange = true;
117  }
118  return MadeChange;
119 }
120 
121 
122 // Check to see if this function returns one or more constants. If so, replace
123 // all callers that use those return values with the constant value. This will
124 // leave in the actual return values and instructions, but deadargelim will
125 // clean that up.
126 //
127 // Additionally if a function always returns one of its arguments directly,
128 // callers will be updated to use the value they pass in directly instead of
129 // using the return value.
131  if (F.getReturnType()->isVoidTy())
132  return false; // No return value.
133 
134  // We can infer and propagate the return value only when we know that the
135  // definition we'll get at link time is *exactly* the definition we see now.
136  // For more details, see GlobalValue::mayBeDerefined.
137  if (!F.isDefinitionExact())
138  return false;
139 
140  // Check to see if this function returns a constant.
141  SmallVector<Value *,4> RetVals;
143  if (STy)
144  for (unsigned i = 0, e = STy->getNumElements(); i < e; ++i)
145  RetVals.push_back(UndefValue::get(STy->getElementType(i)));
146  else
148 
149  unsigned NumNonConstant = 0;
150  for (BasicBlock &BB : F)
151  if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
152  for (unsigned i = 0, e = RetVals.size(); i != e; ++i) {
153  // Already found conflicting return values?
154  Value *RV = RetVals[i];
155  if (!RV)
156  continue;
157 
158  // Find the returned value
159  Value *V;
160  if (!STy)
161  V = RI->getOperand(0);
162  else
163  V = FindInsertedValue(RI->getOperand(0), i);
164 
165  if (V) {
166  // Ignore undefs, we can change them into anything
167  if (isa<UndefValue>(V))
168  continue;
169 
170  // Try to see if all the rets return the same constant or argument.
171  if (isa<Constant>(V) || isa<Argument>(V)) {
172  if (isa<UndefValue>(RV)) {
173  // No value found yet? Try the current one.
174  RetVals[i] = V;
175  continue;
176  }
177  // Returning the same value? Good.
178  if (RV == V)
179  continue;
180  }
181  }
182  // Different or no known return value? Don't propagate this return
183  // value.
184  RetVals[i] = nullptr;
185  // All values non-constant? Stop looking.
186  if (++NumNonConstant == RetVals.size())
187  return false;
188  }
189  }
190 
191  // If we got here, the function returns at least one constant value. Loop
192  // over all users, replacing any uses of the return value with the returned
193  // constant.
194  bool MadeChange = false;
195  for (Use &U : F.uses()) {
196  CallSite CS(U.getUser());
197  Instruction* Call = CS.getInstruction();
198 
199  // Not a call instruction or a call instruction that's not calling F
200  // directly?
201  if (!Call || !CS.isCallee(&U))
202  continue;
203 
204  // Call result not used?
205  if (Call->use_empty())
206  continue;
207 
208  MadeChange = true;
209 
210  if (!STy) {
211  Value* New = RetVals[0];
212  if (Argument *A = dyn_cast<Argument>(New))
213  // Was an argument returned? Then find the corresponding argument in
214  // the call instruction and use that.
215  New = CS.getArgument(A->getArgNo());
216  Call->replaceAllUsesWith(New);
217  continue;
218  }
219 
220  for (auto I = Call->user_begin(), E = Call->user_end(); I != E;) {
221  Instruction *Ins = cast<Instruction>(*I);
222 
223  // Increment now, so we can remove the use
224  ++I;
225 
226  // Find the index of the retval to replace with
227  int index = -1;
228  if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Ins))
229  if (EV->hasIndices())
230  index = *EV->idx_begin();
231 
232  // If this use uses a specific return value, and we have a replacement,
233  // replace it.
234  if (index != -1) {
235  Value *New = RetVals[index];
236  if (New) {
237  if (Argument *A = dyn_cast<Argument>(New))
238  // Was an argument returned? Then find the corresponding argument in
239  // the call instruction and use that.
240  New = CS.getArgument(A->getArgNo());
241  Ins->replaceAllUsesWith(New);
242  Ins->eraseFromParent();
243  }
244  }
245  }
246  }
247 
248  if (MadeChange) ++NumReturnValProped;
249  return MadeChange;
250 }
251 
252 char IPCP::ID = 0;
253 INITIALIZE_PASS(IPCP, "ipconstprop",
254  "Interprocedural constant propagation", false, false)
255 
256 ModulePass *llvm::createIPConstantPropagationPass() { return new IPCP(); }
257 
258 bool IPCP::runOnModule(Module &M) {
259  if (skipModule(M))
260  return false;
261 
262  bool Changed = false;
263  bool LocalChange = true;
264 
265  // FIXME: instead of using smart algorithms, we just iterate until we stop
266  // making changes.
267  while (LocalChange) {
268  LocalChange = false;
269  for (Function &F : M)
270  if (!F.isDeclaration()) {
271  // Delete any klingons.
272  F.removeDeadConstantUsers();
273  if (F.hasLocalLinkage())
274  LocalChange |= PropagateConstantsIntoArguments(F);
275  Changed |= PropagateConstantReturn(F);
276  }
277  Changed |= LocalChange;
278  }
279  return Changed;
280 }
Return a value (possibly void), from a function.
void initializeIPCPPass(PassRegistry &)
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:76
ModulePass * createIPConstantPropagationPass()
createIPConstantPropagationPass - This pass propagates constants from call sites into the bodies of f...
iterator_range< use_iterator > uses()
Definition: Value.h:326
This instruction extracts a struct member or array element value from an aggregate value...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVM Argument representation.
Definition: Argument.h:34
static bool PropagateConstantsIntoArguments(Function &F)
PropagateConstantsIntoArguments - Look at all uses of the specified function.
STATISTIC(NumFunctions,"Total number of functions")
size_t i
bool onlyReadsMemory() const
Determine if the function does not access or only reads memory.
Definition: Function.h:321
INITIALIZE_PASS(IPCP,"ipconstprop","Interprocedural constant propagation", false, false) ModulePass *llvm
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:52
Type * getReturnType() const
Returns the type of the ret val.
Definition: Function.cpp:238
size_t arg_size() const
Definition: Function.cpp:327
Class to represent struct types.
Definition: DerivedTypes.h:199
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
#define F(x, y, z)
Definition: MD5.cpp:51
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:401
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
Type * getElementType(unsigned N) const
Definition: DerivedTypes.h:290
This is an important base class in LLVM.
Definition: Constant.h:42
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isDefinitionExact() const
Return true if the currently visible definition of this global (if any) is exactly the definition we ...
Definition: GlobalValue.h:381
arg_iterator arg_begin()
Definition: Function.h:550
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1337
User::op_iterator arg_iterator
arg_iterator - The type of iterator to use when looping over actual arguments at this call site...
Definition: CallSite.h:205
Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, Instruction *InsertBefore=nullptr)
Given an aggregrate and an sequence of indices, see if the scalar value indexed is already around as ...
IterTy arg_begin() const
Definition: CallSite.h:528
Iterator for intrusive lists based on ilist_node.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
Module.h This file contains the declarations for the Module class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
bool arg_empty() const
Definition: Function.cpp:330
static bool PropagateConstantReturn(Function &F)
#define I(x, y, z)
Definition: MD5.cpp:54
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:235
LLVM_NODISCARD 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:287
bool use_empty() const
Definition: Value.h:299
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:71
unsigned getNumElements() const
Random access to the elements.
Definition: DerivedTypes.h:289
static GCRegistry::Add< ErlangGC > A("erlang","erlang-compatible garbage collector")
bool isCallee(Value::const_user_iterator UI) const
isCallee - Determine whether the passed iterator points to the callee operand's Use.
Definition: CallSite.h:134
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:139
void resize(size_type N)
Definition: SmallVector.h:352