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 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/Pass.h"
37 #include "llvm/Instructions.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Support/CallSite.h"
41 #include "llvm/Support/CFG.h"
42 #include "Support/Debug.h"
43 #include "Support/DepthFirstIterator.h"
44 #include "Support/Statistic.h"
45 #include "Support/StringExtras.h"
50 Statistic<> NumArgumentsPromoted("argpromotion",
51 "Number of pointer arguments promoted");
52 Statistic<> NumAggregatesPromoted("argpromotion",
53 "Number of aggregate arguments promoted");
54 Statistic<> NumArgumentsDead("argpromotion",
55 "Number of dead pointer args eliminated");
57 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
59 class ArgPromotion : public Pass {
60 // WorkList - The set of internal functions that we have yet to process. As
61 // we eliminate arguments from a function, we push all callers into this set
62 // so that the by-reference argument can be bubbled out as far as possible.
63 // This set contains only internal functions.
64 std::set<Function*> WorkList;
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67 AU.addRequired<AliasAnalysis>();
68 AU.addRequired<TargetData>();
71 virtual bool run(Module &M);
73 bool PromoteArguments(Function *F);
74 bool isSafeToPromoteArgument(Argument *Arg) const;
75 void DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote);
78 RegisterOpt<ArgPromotion> X("argpromotion",
79 "Promote 'by reference' arguments to scalars");
82 Pass *llvm::createArgumentPromotionPass() {
83 return new ArgPromotion();
86 bool ArgPromotion::run(Module &M) {
88 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
89 if (I->hasInternalLinkage()) {
92 // If there are any constant pointer refs pointing to this function,
93 // eliminate them now if possible.
94 ConstantPointerRef *CPR = 0;
95 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
97 if ((CPR = dyn_cast<ConstantPointerRef>(*UI)))
100 // See if we can transform all users to use the function directly.
101 while (!CPR->use_empty()) {
102 User *TheUser = CPR->use_back();
103 if (!isa<Constant>(TheUser) && !isa<GlobalVariable>(TheUser)) {
105 TheUser->replaceUsesOfWith(CPR, I);
107 // We won't be able to eliminate all users. :(
108 WorkList.erase(I); // Minor efficiency win.
113 // If we nuked all users of the CPR, kill the CPR now!
114 if (CPR->use_empty()) {
115 CPR->destroyConstant();
121 while (!WorkList.empty()) {
122 Function *F = *WorkList.begin();
123 WorkList.erase(WorkList.begin());
125 if (PromoteArguments(F)) // Attempt to promote an argument.
126 Changed = true; // Remember that we changed something.
132 /// PromoteArguments - This method checks the specified function to see if there
133 /// are any promotable arguments and if it is safe to promote the function (for
134 /// example, all callers are direct). If safe to promote some arguments, it
135 /// calls the DoPromotion method.
137 bool ArgPromotion::PromoteArguments(Function *F) {
138 assert(F->hasInternalLinkage() && "We can only process internal functions!");
140 // First check: see if there are any pointer arguments! If not, quick exit.
141 std::vector<Argument*> PointerArgs;
142 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
143 if (isa<PointerType>(I->getType()))
144 PointerArgs.push_back(I);
145 if (PointerArgs.empty()) return false;
147 // Second check: make sure that all callers are direct callers. We can't
148 // transform functions that have indirect callers.
149 for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
151 CallSite CS = CallSite::get(*UI);
152 if (!CS.getInstruction()) // "Taking the address" of the function
155 // Ensure that this call site is CALLING the function, not passing it as
157 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
159 if (*AI == F) return false; // Passing the function address in!
162 // Check to see which arguments are promotable. If an argument is not
163 // promotable, remove it from the PointerArgs vector.
164 for (unsigned i = 0; i != PointerArgs.size(); ++i)
165 if (!isSafeToPromoteArgument(PointerArgs[i])) {
166 std::swap(PointerArgs[i--], PointerArgs.back());
167 PointerArgs.pop_back();
170 // No promotable pointer arguments.
171 if (PointerArgs.empty()) return false;
173 // Okay, promote all of the arguments are rewrite the callees!
174 DoPromotion(F, PointerArgs);
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 std::vector<LoadInst*> Loads;
188 std::vector<std::vector<ConstantInt*> > GEPIndices;
189 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
191 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
192 if (LI->isVolatile()) return false; // Don't hack volatile loads
194 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
195 if (GEP->use_empty()) {
196 // Dead GEP's cause trouble later. Just remove them if we run into
198 getAnalysis<AliasAnalysis>().deleteValue(GEP);
199 GEP->getParent()->getInstList().erase(GEP);
200 return isSafeToPromoteArgument(Arg);
202 // Ensure that all of the indices are constants.
203 std::vector<ConstantInt*> Operands;
204 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
205 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
206 Operands.push_back(C);
208 return false; // Not a constant operand GEP!
210 // Ensure that the only users of the GEP are load instructions.
211 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
213 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
214 if (LI->isVolatile()) return false; // Don't hack volatile loads
220 // See if there is already a GEP with these indices. If not, check to
221 // make sure that we aren't promoting too many elements. If so, nothing
223 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
225 if (GEPIndices.size() == 3) {
226 DEBUG(std::cerr << "argpromotion disable promoting argument '"
227 << Arg->getName() << "' because it would require adding more "
228 << "than 3 arguments to the function.\n");
229 // We limit aggregate promotion to only promoting up to three elements
233 GEPIndices.push_back(Operands);
236 return false; // Not a load or a GEP.
239 if (Loads.empty()) return true; // No users, this is a dead argument.
241 // Okay, now we know that the argument is only used by load instructions. Use
242 // alias analysis to check to see if the pointer is guaranteed to not be
243 // modified from entry of the function to each of the load instructions.
244 Function &F = *Arg->getParent();
246 // Because there could be several/many load instructions, remember which
247 // blocks we know to be transparent to the load.
248 std::set<BasicBlock*> TranspBlocks;
250 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
251 TargetData &TD = getAnalysis<TargetData>();
253 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
254 // Check to see if the load is invalidated from the start of the block to
256 LoadInst *Load = Loads[i];
257 BasicBlock *BB = Load->getParent();
259 const PointerType *LoadTy =
260 cast<PointerType>(Load->getOperand(0)->getType());
261 unsigned LoadSize = TD.getTypeSize(LoadTy->getElementType());
263 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
264 return false; // Pointer is invalidated!
266 // Now check every path from the entry block to the load for transparency.
267 // To do this, we perform a depth first search on the inverse CFG from the
269 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
270 for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),
271 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
272 if (AA.canBasicBlockModify(**I, Arg, LoadSize))
276 // If the path from the entry of the function to each load is free of
277 // instructions that potentially invalidate the load, we can make the
283 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value*
284 /// elements are instances of ConstantInt.
286 struct GEPIdxComparator {
287 bool operator()(const std::vector<Value*> &LHS,
288 const std::vector<Value*> &RHS) const {
290 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
291 if (LHS[idx] != RHS[idx]) {
292 return cast<ConstantInt>(LHS[idx])->getRawValue() <
293 cast<ConstantInt>(RHS[idx])->getRawValue();
297 // Return less than if we ran out of stuff in LHS and we didn't run out of
299 return idx == LHS.size() && idx != RHS.size();
305 /// DoPromotion - This method actually performs the promotion of the specified
306 /// arguments. At this point, we know that it's safe to do so.
307 void ArgPromotion::DoPromotion(Function *F, std::vector<Argument*> &Args2Prom) {
308 std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
310 // Start by computing a new prototype for the function, which is the same as
311 // the old function, but has modified arguments.
312 const FunctionType *FTy = F->getFunctionType();
313 std::vector<const Type*> Params;
315 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
317 // ScalarizedElements - If we are promoting a pointer that has elements
318 // accessed out of it, keep track of which elements are accessed so that we
319 // can add one argument for each.
321 // Arguments that are directly loaded will have a zero element value here, to
322 // handle cases where there are both a direct load and GEP accesses.
324 std::map<Argument*, ScalarizeTable> ScalarizedElements;
326 // OriginalLoads - Keep track of a representative load instruction from the
327 // original function so that we can tell the alias analysis implementation
328 // what the new GEP/Load instructions we are inserting look like.
329 std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
331 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
332 if (!ArgsToPromote.count(I)) {
333 Params.push_back(I->getType());
334 } else if (I->use_empty()) {
337 // Okay, this is being promoted. Check to see if there are any GEP uses
339 ScalarizeTable &ArgIndices = ScalarizedElements[I];
340 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
342 Instruction *User = cast<Instruction>(*UI);
343 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
344 std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
345 ArgIndices.insert(Indices);
347 if (LoadInst *L = dyn_cast<LoadInst>(User))
350 OrigLoad = cast<LoadInst>(User->use_back());
351 OriginalLoads[Indices] = OrigLoad;
354 // Add a parameter to the function for each element passed in.
355 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
356 E = ArgIndices.end(); SI != E; ++SI)
357 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
359 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
360 ++NumArgumentsPromoted;
362 ++NumAggregatesPromoted;
365 const Type *RetTy = FTy->getReturnType();
367 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
368 // have zero fixed arguments.
369 bool ExtraArgHack = false;
370 if (Params.empty() && FTy->isVarArg()) {
372 Params.push_back(Type::IntTy);
374 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
376 // Create the new function body and insert it into the module...
377 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
378 F->getParent()->getFunctionList().insert(F, NF);
380 // Get the alias analysis information that we need to update to reflect our
382 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
384 // Loop over all of the callers of the function, transforming the call sites
385 // to pass in the loaded pointers.
387 std::vector<Value*> Args;
388 while (!F->use_empty()) {
389 CallSite CS = CallSite::get(F->use_back());
390 Instruction *Call = CS.getInstruction();
392 // Make sure the caller of this function is revisited now that we promoted
393 // arguments in a callee of it.
394 if (Call->getParent()->getParent()->hasInternalLinkage())
395 WorkList.insert(Call->getParent()->getParent());
397 // Loop over the operands, inserting GEP and loads in the caller as
399 CallSite::arg_iterator AI = CS.arg_begin();
400 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++AI)
401 if (!ArgsToPromote.count(I))
402 Args.push_back(*AI); // Unmodified argument
403 else if (!I->use_empty()) {
404 // Non-dead argument: insert GEPs and loads as appropriate.
405 ScalarizeTable &ArgIndices = ScalarizedElements[I];
406 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
407 E = ArgIndices.end(); SI != E; ++SI) {
409 LoadInst *OrigLoad = OriginalLoads[*SI];
411 V = new GetElementPtrInst(V, *SI, V->getName()+".idx", Call);
412 AA.copyValue(OrigLoad->getOperand(0), V);
414 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
415 AA.copyValue(OrigLoad, Args.back());
420 Args.push_back(Constant::getNullValue(Type::IntTy));
422 // Push any varargs arguments on the list
423 for (; AI != CS.arg_end(); ++AI)
427 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
428 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
431 New = new CallInst(NF, Args, "", Call);
435 // Update the alias analysis implementation to know that we are replacing
436 // the old call with a new one.
437 AA.replaceWithNewValue(Call, New);
439 if (!Call->use_empty()) {
440 Call->replaceAllUsesWith(New);
441 std::string Name = Call->getName();
446 // Finally, remove the old call from the program, reducing the use-count of
448 Call->getParent()->getInstList().erase(Call);
451 // Since we have now created the new function, splice the body of the old
452 // function right into the new function, leaving the old rotting hulk of the
454 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
456 // Loop over the argument list, transfering uses of the old arguments over to
457 // the new arguments, also transfering over the names as well.
459 for (Function::aiterator I = F->abegin(), E = F->aend(), I2 = NF->abegin();
461 if (!ArgsToPromote.count(I)) {
462 // If this is an unmodified argument, move the name and users over to the
464 I->replaceAllUsesWith(I2);
465 I2->setName(I->getName());
466 AA.replaceWithNewValue(I, I2);
468 } else if (I->use_empty()) {
471 // Otherwise, if we promoted this argument, then all users are load
472 // instructions, and all loads should be using the new argument that we
474 ScalarizeTable &ArgIndices = ScalarizedElements[I];
476 while (!I->use_empty()) {
477 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
478 assert(ArgIndices.begin()->empty() &&
479 "Load element should sort to front!");
480 I2->setName(I->getName()+".val");
481 LI->replaceAllUsesWith(I2);
482 AA.replaceWithNewValue(LI, I2);
483 LI->getParent()->getInstList().erase(LI);
484 DEBUG(std::cerr << "*** Promoted load of argument '" << I->getName()
485 << "' in function '" << F->getName() << "'\n");
487 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
488 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
491 Function::aiterator TheArg = I2;
492 for (ScalarizeTable::iterator It = ArgIndices.begin();
493 *It != Operands; ++It, ++TheArg) {
494 assert(It != ArgIndices.end() && "GEP not handled??");
497 std::string NewName = I->getName();
498 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
499 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
500 NewName += "."+itostr((int64_t)CI->getRawValue());
503 TheArg->setName(NewName+".val");
505 DEBUG(std::cerr << "*** Promoted agg argument '" << TheArg->getName()
506 << "' of function '" << F->getName() << "'\n");
508 // All of the uses must be load instructions. Replace them all with
509 // the argument specified by ArgNo.
510 while (!GEP->use_empty()) {
511 LoadInst *L = cast<LoadInst>(GEP->use_back());
512 L->replaceAllUsesWith(TheArg);
513 AA.replaceWithNewValue(L, TheArg);
514 L->getParent()->getInstList().erase(L);
517 GEP->getParent()->getInstList().erase(GEP);
521 // If we inserted a new pointer type, it's possible that IT could be
522 // promoted too. Also, increment I2 past all of the arguments added for
523 // this promoted pointer.
524 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i, ++I2)
525 if (isa<PointerType>(I2->getType()))
529 // Notify the alias analysis implementation that we inserted a new argument.
531 AA.copyValue(Constant::getNullValue(Type::IntTy), NF->abegin());
534 // Tell the alias analysis that the old function is about to disappear.
535 AA.replaceWithNewValue(F, NF);
537 // Now that the old function is dead, delete it.
538 F->getParent()->getFunctionList().erase(F);