1 //===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass promotes "by reference" arguments to be "by value" arguments. In
11 // practice, this means looking for internal functions that have pointer
12 // arguments. If we can prove, through the use of alias analysis, that an
13 // argument is *only* loaded, then we can pass the value into the function
14 // instead of the address of the value. This can cause recursive simplification
15 // of code and lead to the elimination of allocas (especially in C++ template
16 // code like the STL).
18 // This pass also handles aggregate arguments that are passed into a function,
19 // scalarizing them if the elements of the aggregate are only loaded. Note that
20 // we refuse to scalarize aggregates which would require passing in more than
21 // three operands to the function, because we don't want to pass thousands of
22 // operands for a large array or structure!
24 // Note that this transformation could also be done for arguments that are only
25 // stored to (returning the value instead), but we do not currently handle that
26 // case. This case would be best handled when and if we start supporting
27 // multiple return values from functions.
29 //===----------------------------------------------------------------------===//
31 #define DEBUG_TYPE "argpromotion"
32 #include "llvm/Transforms/IPO.h"
33 #include "llvm/Constants.h"
34 #include "llvm/DerivedTypes.h"
35 #include "llvm/Module.h"
36 #include "llvm/CallGraphSCCPass.h"
37 #include "llvm/Instructions.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/Analysis/CallGraph.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Support/CallSite.h"
42 #include "llvm/Support/CFG.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/ADT/DepthFirstIterator.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
50 STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
51 STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
52 STATISTIC(NumArgumentsDead , "Number of dead pointer args eliminated");
55 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
57 struct ArgPromotion : public CallGraphSCCPass {
58 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59 AU.addRequired<AliasAnalysis>();
60 AU.addRequired<TargetData>();
61 CallGraphSCCPass::getAnalysisUsage(AU);
64 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
66 bool PromoteArguments(CallGraphNode *CGN);
67 bool isSafeToPromoteArgument(Argument *Arg) const;
68 Function *DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote);
71 RegisterPass<ArgPromotion> X("argpromotion",
72 "Promote 'by reference' arguments to scalars");
75 ModulePass *llvm::createArgumentPromotionPass() {
76 return new ArgPromotion();
79 bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
80 bool Changed = false, LocalChange;
82 do { // Iterate until we stop promoting from this SCC.
84 // Attempt to promote arguments from all functions in this SCC.
85 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
86 LocalChange |= PromoteArguments(SCC[i]);
87 Changed |= LocalChange; // Remember that we changed something.
88 } while (LocalChange);
93 /// PromoteArguments - This method checks the specified function to see if there
94 /// are any promotable arguments and if it is safe to promote the function (for
95 /// example, all callers are direct). If safe to promote some arguments, it
96 /// calls the DoPromotion method.
98 bool ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
99 Function *F = CGN->getFunction();
101 // Make sure that it is local to this module.
102 if (!F || !F->hasInternalLinkage()) return false;
104 // First check: see if there are any pointer arguments! If not, quick exit.
105 std::vector<Argument*> PointerArgs;
106 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
107 if (isa<PointerType>(I->getType()))
108 PointerArgs.push_back(I);
109 if (PointerArgs.empty()) return false;
111 // Second check: make sure that all callers are direct callers. We can't
112 // transform functions that have indirect callers.
113 for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
115 CallSite CS = CallSite::get(*UI);
116 if (!CS.getInstruction()) // "Taking the address" of the function
119 // Ensure that this call site is CALLING the function, not passing it as
121 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
123 if (*AI == F) return false; // Passing the function address in!
126 // Check to see which arguments are promotable. If an argument is not
127 // promotable, remove it from the PointerArgs vector.
128 for (unsigned i = 0; i != PointerArgs.size(); ++i)
129 if (!isSafeToPromoteArgument(PointerArgs[i])) {
130 std::swap(PointerArgs[i--], PointerArgs.back());
131 PointerArgs.pop_back();
134 // No promotable pointer arguments.
135 if (PointerArgs.empty()) return false;
137 // Okay, promote all of the arguments are rewrite the callees!
138 Function *NewF = DoPromotion(F, PointerArgs);
140 // Update the call graph to know that the old function is gone.
141 getAnalysis<CallGraph>().changeFunction(F, NewF);
145 /// IsAlwaysValidPointer - Return true if the specified pointer is always legal
147 static bool IsAlwaysValidPointer(Value *V) {
148 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
149 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V))
150 return IsAlwaysValidPointer(GEP->getOperand(0));
151 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
152 if (CE->getOpcode() == Instruction::GetElementPtr)
153 return IsAlwaysValidPointer(CE->getOperand(0));
158 /// AllCalleesPassInValidPointerForArgument - Return true if we can prove that
159 /// all callees pass in a valid pointer for the specified function argument.
160 static bool AllCalleesPassInValidPointerForArgument(Argument *Arg) {
161 Function *Callee = Arg->getParent();
163 unsigned ArgNo = std::distance(Callee->arg_begin(), Function::arg_iterator(Arg));
165 // Look at all call sites of the function. At this pointer we know we only
166 // have direct callees.
167 for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
169 CallSite CS = CallSite::get(*UI);
170 assert(CS.getInstruction() && "Should only have direct calls!");
172 if (!IsAlwaysValidPointer(CS.getArgument(ArgNo)))
179 /// isSafeToPromoteArgument - As you might guess from the name of this method,
180 /// it checks to see if it is both safe and useful to promote the argument.
181 /// This method limits promotion of aggregates to only promote up to three
182 /// elements of the aggregate in order to avoid exploding the number of
183 /// arguments passed in.
184 bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {
185 // We can only promote this argument if all of the uses are loads, or are GEP
186 // instructions (with constant indices) that are subsequently loaded.
187 bool HasLoadInEntryBlock = false;
188 BasicBlock *EntryBlock = Arg->getParent()->begin();
189 std::vector<LoadInst*> Loads;
190 std::vector<std::vector<ConstantInt*> > GEPIndices;
191 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
193 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
194 if (LI->isVolatile()) return false; // Don't hack volatile loads
196 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
197 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
198 if (GEP->use_empty()) {
199 // Dead GEP's cause trouble later. Just remove them if we run into
201 getAnalysis<AliasAnalysis>().deleteValue(GEP);
202 GEP->getParent()->getInstList().erase(GEP);
203 return isSafeToPromoteArgument(Arg);
205 // Ensure that all of the indices are constants.
206 std::vector<ConstantInt*> Operands;
207 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
208 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
209 Operands.push_back(C);
211 return false; // Not a constant operand GEP!
213 // Ensure that the only users of the GEP are load instructions.
214 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
216 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
217 if (LI->isVolatile()) return false; // Don't hack volatile loads
219 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
224 // See if there is already a GEP with these indices. If not, check to
225 // make sure that we aren't promoting too many elements. If so, nothing
227 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
229 if (GEPIndices.size() == 3) {
230 DOUT << "argpromotion disable promoting argument '"
231 << Arg->getName() << "' because it would require adding more "
232 << "than 3 arguments to the function.\n";
233 // We limit aggregate promotion to only promoting up to three elements
237 GEPIndices.push_back(Operands);
240 return false; // Not a load or a GEP.
243 if (Loads.empty()) return true; // No users, this is a dead argument.
245 // If we decide that we want to promote this argument, the value is going to
246 // be unconditionally loaded in all callees. This is only safe to do if the
247 // pointer was going to be unconditionally loaded anyway (i.e. there is a load
248 // of the pointer in the entry block of the function) or if we can prove that
249 // all pointers passed in are always to legal locations (for example, no null
250 // pointers are passed in, no pointers to free'd memory, etc).
251 if (!HasLoadInEntryBlock && !AllCalleesPassInValidPointerForArgument(Arg))
252 return false; // Cannot prove that this is safe!!
254 // Okay, now we know that the argument is only used by load instructions and
255 // it is safe to unconditionally load the pointer. Use alias analysis to
256 // check to see if the pointer is guaranteed to not be modified from entry of
257 // the function to each of the load instructions.
259 // Because there could be several/many load instructions, remember which
260 // blocks we know to be transparent to the load.
261 std::set<BasicBlock*> TranspBlocks;
263 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
264 TargetData &TD = getAnalysis<TargetData>();
266 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
267 // Check to see if the load is invalidated from the start of the block to
269 LoadInst *Load = Loads[i];
270 BasicBlock *BB = Load->getParent();
272 const PointerType *LoadTy =
273 cast<PointerType>(Load->getOperand(0)->getType());
274 unsigned LoadSize = (unsigned)TD.getTypeSize(LoadTy->getElementType());
276 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
277 return false; // Pointer is invalidated!
279 // Now check every path from the entry block to the load for transparency.
280 // To do this, we perform a depth first search on the inverse CFG from the
282 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
283 for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),
284 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
285 if (AA.canBasicBlockModify(**I, Arg, LoadSize))
289 // If the path from the entry of the function to each load is free of
290 // instructions that potentially invalidate the load, we can make the
296 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value*
297 /// elements are instances of ConstantInt.
299 struct GEPIdxComparator {
300 bool operator()(const std::vector<Value*> &LHS,
301 const std::vector<Value*> &RHS) const {
303 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
304 if (LHS[idx] != RHS[idx]) {
305 return cast<ConstantInt>(LHS[idx])->getZExtValue() <
306 cast<ConstantInt>(RHS[idx])->getZExtValue();
310 // Return less than if we ran out of stuff in LHS and we didn't run out of
312 return idx == LHS.size() && idx != RHS.size();
318 /// DoPromotion - This method actually performs the promotion of the specified
319 /// arguments, and returns the new function. At this point, we know that it's
321 Function *ArgPromotion::DoPromotion(Function *F,
322 std::vector<Argument*> &Args2Prom) {
323 std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
325 // Start by computing a new prototype for the function, which is the same as
326 // the old function, but has modified arguments.
327 const FunctionType *FTy = F->getFunctionType();
328 std::vector<const Type*> Params;
330 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
332 // ScalarizedElements - If we are promoting a pointer that has elements
333 // accessed out of it, keep track of which elements are accessed so that we
334 // can add one argument for each.
336 // Arguments that are directly loaded will have a zero element value here, to
337 // handle cases where there are both a direct load and GEP accesses.
339 std::map<Argument*, ScalarizeTable> ScalarizedElements;
341 // OriginalLoads - Keep track of a representative load instruction from the
342 // original function so that we can tell the alias analysis implementation
343 // what the new GEP/Load instructions we are inserting look like.
344 std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
346 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
347 if (!ArgsToPromote.count(I)) {
348 Params.push_back(I->getType());
349 } else if (I->use_empty()) {
352 // Okay, this is being promoted. Check to see if there are any GEP uses
354 ScalarizeTable &ArgIndices = ScalarizedElements[I];
355 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
357 Instruction *User = cast<Instruction>(*UI);
358 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
359 std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
360 ArgIndices.insert(Indices);
362 if (LoadInst *L = dyn_cast<LoadInst>(User))
365 OrigLoad = cast<LoadInst>(User->use_back());
366 OriginalLoads[Indices] = OrigLoad;
369 // Add a parameter to the function for each element passed in.
370 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
371 E = ArgIndices.end(); SI != E; ++SI)
372 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
374 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
375 ++NumArgumentsPromoted;
377 ++NumAggregatesPromoted;
380 const Type *RetTy = FTy->getReturnType();
382 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
383 // have zero fixed arguments.
384 bool ExtraArgHack = false;
385 if (Params.empty() && FTy->isVarArg()) {
387 Params.push_back(Type::IntTy);
389 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
391 // Create the new function body and insert it into the module...
392 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
393 NF->setCallingConv(F->getCallingConv());
394 F->getParent()->getFunctionList().insert(F, NF);
396 // Get the alias analysis information that we need to update to reflect our
398 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
400 // Loop over all of the callers of the function, transforming the call sites
401 // to pass in the loaded pointers.
403 std::vector<Value*> Args;
404 while (!F->use_empty()) {
405 CallSite CS = CallSite::get(F->use_back());
406 Instruction *Call = CS.getInstruction();
408 // Loop over the operands, inserting GEP and loads in the caller as
410 CallSite::arg_iterator AI = CS.arg_begin();
411 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
413 if (!ArgsToPromote.count(I))
414 Args.push_back(*AI); // Unmodified argument
415 else if (!I->use_empty()) {
416 // Non-dead argument: insert GEPs and loads as appropriate.
417 ScalarizeTable &ArgIndices = ScalarizedElements[I];
418 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
419 E = ArgIndices.end(); SI != E; ++SI) {
421 LoadInst *OrigLoad = OriginalLoads[*SI];
423 V = new GetElementPtrInst(V, *SI, V->getName()+".idx", Call);
424 AA.copyValue(OrigLoad->getOperand(0), V);
426 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
427 AA.copyValue(OrigLoad, Args.back());
432 Args.push_back(Constant::getNullValue(Type::IntTy));
434 // Push any varargs arguments on the list
435 for (; AI != CS.arg_end(); ++AI)
439 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
440 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
442 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
444 New = new CallInst(NF, Args, "", Call);
445 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
446 if (cast<CallInst>(Call)->isTailCall())
447 cast<CallInst>(New)->setTailCall();
451 // Update the alias analysis implementation to know that we are replacing
452 // the old call with a new one.
453 AA.replaceWithNewValue(Call, New);
455 if (!Call->use_empty()) {
456 Call->replaceAllUsesWith(New);
457 std::string Name = Call->getName();
462 // Finally, remove the old call from the program, reducing the use-count of
464 Call->getParent()->getInstList().erase(Call);
467 // Since we have now created the new function, splice the body of the old
468 // function right into the new function, leaving the old rotting hulk of the
470 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
472 // Loop over the argument list, transfering uses of the old arguments over to
473 // the new arguments, also transfering over the names as well.
475 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(), I2 = NF->arg_begin();
477 if (!ArgsToPromote.count(I)) {
478 // If this is an unmodified argument, move the name and users over to the
480 I->replaceAllUsesWith(I2);
481 I2->setName(I->getName());
482 AA.replaceWithNewValue(I, I2);
484 } else if (I->use_empty()) {
487 // Otherwise, if we promoted this argument, then all users are load
488 // instructions, and all loads should be using the new argument that we
490 ScalarizeTable &ArgIndices = ScalarizedElements[I];
492 while (!I->use_empty()) {
493 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
494 assert(ArgIndices.begin()->empty() &&
495 "Load element should sort to front!");
496 I2->setName(I->getName()+".val");
497 LI->replaceAllUsesWith(I2);
498 AA.replaceWithNewValue(LI, I2);
499 LI->getParent()->getInstList().erase(LI);
500 DOUT << "*** Promoted load of argument '" << I->getName()
501 << "' in function '" << F->getName() << "'\n";
503 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
504 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
506 Function::arg_iterator TheArg = I2;
507 for (ScalarizeTable::iterator It = ArgIndices.begin();
508 *It != Operands; ++It, ++TheArg) {
509 assert(It != ArgIndices.end() && "GEP not handled??");
512 std::string NewName = I->getName();
513 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
514 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
515 NewName += "."+itostr((int64_t)CI->getZExtValue());
518 TheArg->setName(NewName+".val");
520 DOUT << "*** Promoted agg argument '" << TheArg->getName()
521 << "' of function '" << F->getName() << "'\n";
523 // All of the uses must be load instructions. Replace them all with
524 // the argument specified by ArgNo.
525 while (!GEP->use_empty()) {
526 LoadInst *L = cast<LoadInst>(GEP->use_back());
527 L->replaceAllUsesWith(TheArg);
528 AA.replaceWithNewValue(L, TheArg);
529 L->getParent()->getInstList().erase(L);
532 GEP->getParent()->getInstList().erase(GEP);
536 // Increment I2 past all of the arguments added for this promoted pointer.
537 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
541 // Notify the alias analysis implementation that we inserted a new argument.
543 AA.copyValue(Constant::getNullValue(Type::IntTy), NF->arg_begin());
546 // Tell the alias analysis that the old function is about to disappear.
547 AA.replaceWithNewValue(F, NF);
549 // Now that the old function is dead, delete it.
550 F->getParent()->getFunctionList().erase(F);