ArgumentPromotion.cpp revision a0e0129e3f03fae1a275537a00e426a31d5eb649
1//===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
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).
17//
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!
23//
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.
28//
29//===----------------------------------------------------------------------===//
30
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"
47#include "llvm/Support/Compiler.h"
48#include <set>
49using namespace llvm;
50
51STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
52STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
53STATISTIC(NumArgumentsDead     , "Number of dead pointer args eliminated");
54
55namespace {
56  /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
57  ///
58  struct VISIBILITY_HIDDEN ArgPromotion : public CallGraphSCCPass {
59    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60      AU.addRequired<AliasAnalysis>();
61      AU.addRequired<TargetData>();
62      CallGraphSCCPass::getAnalysisUsage(AU);
63    }
64
65    virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
66  private:
67    bool PromoteArguments(CallGraphNode *CGN);
68    bool isSafeToPromoteArgument(Argument *Arg) const;
69    Function *DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote);
70  };
71
72  RegisterPass<ArgPromotion> X("argpromotion",
73                               "Promote 'by reference' arguments to scalars");
74}
75
76Pass *llvm::createArgumentPromotionPass() {
77  return new ArgPromotion();
78}
79
80bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
81  bool Changed = false, LocalChange;
82
83  do {  // Iterate until we stop promoting from this SCC.
84    LocalChange = false;
85    // Attempt to promote arguments from all functions in this SCC.
86    for (unsigned i = 0, e = SCC.size(); i != e; ++i)
87      LocalChange |= PromoteArguments(SCC[i]);
88    Changed |= LocalChange;               // Remember that we changed something.
89  } while (LocalChange);
90
91  return Changed;
92}
93
94/// PromoteArguments - This method checks the specified function to see if there
95/// are any promotable arguments and if it is safe to promote the function (for
96/// example, all callers are direct).  If safe to promote some arguments, it
97/// calls the DoPromotion method.
98///
99bool ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
100  Function *F = CGN->getFunction();
101
102  // Make sure that it is local to this module.
103  if (!F || !F->hasInternalLinkage()) return false;
104
105  // First check: see if there are any pointer arguments!  If not, quick exit.
106  std::vector<Argument*> PointerArgs;
107  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
108    if (isa<PointerType>(I->getType()))
109      PointerArgs.push_back(I);
110  if (PointerArgs.empty()) return false;
111
112  // Second check: make sure that all callers are direct callers.  We can't
113  // transform functions that have indirect callers.
114  for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
115       UI != E; ++UI) {
116    CallSite CS = CallSite::get(*UI);
117    if (!CS.getInstruction())       // "Taking the address" of the function
118      return false;
119
120    // Ensure that this call site is CALLING the function, not passing it as
121    // an argument.
122    for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
123         AI != E; ++AI)
124      if (*AI == F) return false;   // Passing the function address in!
125  }
126
127  // Check to see which arguments are promotable.  If an argument is not
128  // promotable, remove it from the PointerArgs vector.
129  for (unsigned i = 0; i != PointerArgs.size(); ++i)
130    if (!isSafeToPromoteArgument(PointerArgs[i])) {
131      std::swap(PointerArgs[i--], PointerArgs.back());
132      PointerArgs.pop_back();
133    }
134
135  // No promotable pointer arguments.
136  if (PointerArgs.empty()) return false;
137
138  // Okay, promote all of the arguments are rewrite the callees!
139  Function *NewF = DoPromotion(F, PointerArgs);
140
141  // Update the call graph to know that the old function is gone.
142  getAnalysis<CallGraph>().changeFunction(F, NewF);
143  return true;
144}
145
146/// IsAlwaysValidPointer - Return true if the specified pointer is always legal
147/// to load.
148static bool IsAlwaysValidPointer(Value *V) {
149  if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
150  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V))
151    return IsAlwaysValidPointer(GEP->getOperand(0));
152  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
153    if (CE->getOpcode() == Instruction::GetElementPtr)
154      return IsAlwaysValidPointer(CE->getOperand(0));
155
156  return false;
157}
158
159/// AllCalleesPassInValidPointerForArgument - Return true if we can prove that
160/// all callees pass in a valid pointer for the specified function argument.
161static bool AllCalleesPassInValidPointerForArgument(Argument *Arg) {
162  Function *Callee = Arg->getParent();
163
164  unsigned ArgNo = std::distance(Callee->arg_begin(),
165                                 Function::arg_iterator(Arg));
166
167  // Look at all call sites of the function.  At this pointer we know we only
168  // have direct callees.
169  for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
170       UI != E; ++UI) {
171    CallSite CS = CallSite::get(*UI);
172    assert(CS.getInstruction() && "Should only have direct calls!");
173
174    if (!IsAlwaysValidPointer(CS.getArgument(ArgNo)))
175      return false;
176  }
177  return true;
178}
179
180
181/// isSafeToPromoteArgument - As you might guess from the name of this method,
182/// it checks to see if it is both safe and useful to promote the argument.
183/// This method limits promotion of aggregates to only promote up to three
184/// elements of the aggregate in order to avoid exploding the number of
185/// arguments passed in.
186bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {
187  // We can only promote this argument if all of the uses are loads, or are GEP
188  // instructions (with constant indices) that are subsequently loaded.
189  bool HasLoadInEntryBlock = false;
190  BasicBlock *EntryBlock = Arg->getParent()->begin();
191  std::vector<LoadInst*> Loads;
192  std::vector<std::vector<ConstantInt*> > GEPIndices;
193  for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
194       UI != E; ++UI)
195    if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
196      if (LI->isVolatile()) return false;  // Don't hack volatile loads
197      Loads.push_back(LI);
198      HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
199    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
200      if (GEP->use_empty()) {
201        // Dead GEP's cause trouble later.  Just remove them if we run into
202        // them.
203        getAnalysis<AliasAnalysis>().deleteValue(GEP);
204        GEP->getParent()->getInstList().erase(GEP);
205        return isSafeToPromoteArgument(Arg);
206      }
207      // Ensure that all of the indices are constants.
208      std::vector<ConstantInt*> Operands;
209      for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
210        if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
211          Operands.push_back(C);
212        else
213          return false;  // Not a constant operand GEP!
214
215      // Ensure that the only users of the GEP are load instructions.
216      for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
217           UI != E; ++UI)
218        if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
219          if (LI->isVolatile()) return false;  // Don't hack volatile loads
220          Loads.push_back(LI);
221          HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
222        } else {
223          return false;
224        }
225
226      // See if there is already a GEP with these indices.  If not, check to
227      // make sure that we aren't promoting too many elements.  If so, nothing
228      // to do.
229      if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
230          GEPIndices.end()) {
231        if (GEPIndices.size() == 3) {
232          DOUT << "argpromotion disable promoting argument '"
233               << Arg->getName() << "' because it would require adding more "
234               << "than 3 arguments to the function.\n";
235          // We limit aggregate promotion to only promoting up to three elements
236          // of the aggregate.
237          return false;
238        }
239        GEPIndices.push_back(Operands);
240      }
241    } else {
242      return false;  // Not a load or a GEP.
243    }
244
245  if (Loads.empty()) return true;  // No users, this is a dead argument.
246
247  // If we decide that we want to promote this argument, the value is going to
248  // be unconditionally loaded in all callees.  This is only safe to do if the
249  // pointer was going to be unconditionally loaded anyway (i.e. there is a load
250  // of the pointer in the entry block of the function) or if we can prove that
251  // all pointers passed in are always to legal locations (for example, no null
252  // pointers are passed in, no pointers to free'd memory, etc).
253  if (!HasLoadInEntryBlock && !AllCalleesPassInValidPointerForArgument(Arg))
254    return false;   // Cannot prove that this is safe!!
255
256  // Okay, now we know that the argument is only used by load instructions and
257  // it is safe to unconditionally load the pointer.  Use alias analysis to
258  // check to see if the pointer is guaranteed to not be modified from entry of
259  // the function to each of the load instructions.
260
261  // Because there could be several/many load instructions, remember which
262  // blocks we know to be transparent to the load.
263  std::set<BasicBlock*> TranspBlocks;
264
265  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
266  TargetData &TD = getAnalysis<TargetData>();
267
268  for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
269    // Check to see if the load is invalidated from the start of the block to
270    // the load itself.
271    LoadInst *Load = Loads[i];
272    BasicBlock *BB = Load->getParent();
273
274    const PointerType *LoadTy =
275      cast<PointerType>(Load->getOperand(0)->getType());
276    unsigned LoadSize = (unsigned)TD.getTypeSize(LoadTy->getElementType());
277
278    if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
279      return false;  // Pointer is invalidated!
280
281    // Now check every path from the entry block to the load for transparency.
282    // To do this, we perform a depth first search on the inverse CFG from the
283    // loading block.
284    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
285      for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),
286             E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
287        if (AA.canBasicBlockModify(**I, Arg, LoadSize))
288          return false;
289  }
290
291  // If the path from the entry of the function to each load is free of
292  // instructions that potentially invalidate the load, we can make the
293  // transformation!
294  return true;
295}
296
297namespace {
298  /// GEPIdxComparator - Provide a strong ordering for GEP indices.  All Value*
299  /// elements are instances of ConstantInt.
300  ///
301  struct GEPIdxComparator {
302    bool operator()(const std::vector<Value*> &LHS,
303                    const std::vector<Value*> &RHS) const {
304      unsigned idx = 0;
305      for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
306        if (LHS[idx] != RHS[idx]) {
307          return cast<ConstantInt>(LHS[idx])->getZExtValue() <
308                 cast<ConstantInt>(RHS[idx])->getZExtValue();
309        }
310      }
311
312      // Return less than if we ran out of stuff in LHS and we didn't run out of
313      // stuff in RHS.
314      return idx == LHS.size() && idx != RHS.size();
315    }
316  };
317}
318
319
320/// DoPromotion - This method actually performs the promotion of the specified
321/// arguments, and returns the new function.  At this point, we know that it's
322/// safe to do so.
323Function *ArgPromotion::DoPromotion(Function *F,
324                                    std::vector<Argument*> &Args2Prom) {
325  std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
326
327  // Start by computing a new prototype for the function, which is the same as
328  // the old function, but has modified arguments.
329  const FunctionType *FTy = F->getFunctionType();
330  std::vector<const Type*> Params;
331
332  typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
333
334  // ScalarizedElements - If we are promoting a pointer that has elements
335  // accessed out of it, keep track of which elements are accessed so that we
336  // can add one argument for each.
337  //
338  // Arguments that are directly loaded will have a zero element value here, to
339  // handle cases where there are both a direct load and GEP accesses.
340  //
341  std::map<Argument*, ScalarizeTable> ScalarizedElements;
342
343  // OriginalLoads - Keep track of a representative load instruction from the
344  // original function so that we can tell the alias analysis implementation
345  // what the new GEP/Load instructions we are inserting look like.
346  std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
347
348  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
349    if (!ArgsToPromote.count(I)) {
350      Params.push_back(I->getType());
351    } else if (I->use_empty()) {
352      ++NumArgumentsDead;
353    } else {
354      // Okay, this is being promoted.  Check to see if there are any GEP uses
355      // of the argument.
356      ScalarizeTable &ArgIndices = ScalarizedElements[I];
357      for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
358           ++UI) {
359        Instruction *User = cast<Instruction>(*UI);
360        assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
361        std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
362        ArgIndices.insert(Indices);
363        LoadInst *OrigLoad;
364        if (LoadInst *L = dyn_cast<LoadInst>(User))
365          OrigLoad = L;
366        else
367          OrigLoad = cast<LoadInst>(User->use_back());
368        OriginalLoads[Indices] = OrigLoad;
369      }
370
371      // Add a parameter to the function for each element passed in.
372      for (ScalarizeTable::iterator SI = ArgIndices.begin(),
373             E = ArgIndices.end(); SI != E; ++SI)
374        Params.push_back(GetElementPtrInst::getIndexedType(I->getType(),
375                                                           &(*SI)[0],
376                                                           SI->size()));
377
378      if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
379        ++NumArgumentsPromoted;
380      else
381        ++NumAggregatesPromoted;
382    }
383
384  const Type *RetTy = FTy->getReturnType();
385
386  // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
387  // have zero fixed arguments.
388  bool ExtraArgHack = false;
389  if (Params.empty() && FTy->isVarArg()) {
390    ExtraArgHack = true;
391    Params.push_back(Type::Int32Ty);
392  }
393  FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
394
395   // Create the new function body and insert it into the module...
396  Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
397  NF->setCallingConv(F->getCallingConv());
398  F->getParent()->getFunctionList().insert(F, NF);
399
400  // Get the alias analysis information that we need to update to reflect our
401  // changes.
402  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
403
404  // Loop over all of the callers of the function, transforming the call sites
405  // to pass in the loaded pointers.
406  //
407  std::vector<Value*> Args;
408  while (!F->use_empty()) {
409    CallSite CS = CallSite::get(F->use_back());
410    Instruction *Call = CS.getInstruction();
411
412    // Loop over the operands, inserting GEP and loads in the caller as
413    // appropriate.
414    CallSite::arg_iterator AI = CS.arg_begin();
415    for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
416         I != E; ++I, ++AI)
417      if (!ArgsToPromote.count(I))
418        Args.push_back(*AI);          // Unmodified argument
419      else if (!I->use_empty()) {
420        // Non-dead argument: insert GEPs and loads as appropriate.
421        ScalarizeTable &ArgIndices = ScalarizedElements[I];
422        for (ScalarizeTable::iterator SI = ArgIndices.begin(),
423               E = ArgIndices.end(); SI != E; ++SI) {
424          Value *V = *AI;
425          LoadInst *OrigLoad = OriginalLoads[*SI];
426          if (!SI->empty()) {
427            V = new GetElementPtrInst(V, &(*SI)[0], SI->size(),
428                                      V->getName()+".idx", Call);
429            AA.copyValue(OrigLoad->getOperand(0), V);
430          }
431          Args.push_back(new LoadInst(V, V->getName()+".val", Call));
432          AA.copyValue(OrigLoad, Args.back());
433        }
434      }
435
436    if (ExtraArgHack)
437      Args.push_back(Constant::getNullValue(Type::Int32Ty));
438
439    // Push any varargs arguments on the list
440    for (; AI != CS.arg_end(); ++AI)
441      Args.push_back(*AI);
442
443    Instruction *New;
444    if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
445      New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
446                           &Args[0], Args.size(), "", Call);
447      cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
448    } else {
449      New = new CallInst(NF, &Args[0], Args.size(), "", Call);
450      cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
451      if (cast<CallInst>(Call)->isTailCall())
452        cast<CallInst>(New)->setTailCall();
453    }
454    Args.clear();
455
456    // Update the alias analysis implementation to know that we are replacing
457    // the old call with a new one.
458    AA.replaceWithNewValue(Call, New);
459
460    if (!Call->use_empty()) {
461      Call->replaceAllUsesWith(New);
462      New->takeName(Call);
463    }
464
465    // Finally, remove the old call from the program, reducing the use-count of
466    // F.
467    Call->getParent()->getInstList().erase(Call);
468  }
469
470  // Since we have now created the new function, splice the body of the old
471  // function right into the new function, leaving the old rotting hulk of the
472  // function empty.
473  NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
474
475  // Loop over the argument list, transfering uses of the old arguments over to
476  // the new arguments, also transfering over the names as well.
477  //
478  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
479       I2 = NF->arg_begin(); I != E; ++I)
480    if (!ArgsToPromote.count(I)) {
481      // If this is an unmodified argument, move the name and users over to the
482      // new version.
483      I->replaceAllUsesWith(I2);
484      I2->takeName(I);
485      AA.replaceWithNewValue(I, I2);
486      ++I2;
487    } else if (I->use_empty()) {
488      AA.deleteValue(I);
489    } else {
490      // Otherwise, if we promoted this argument, then all users are load
491      // instructions, and all loads should be using the new argument that we
492      // added.
493      ScalarizeTable &ArgIndices = ScalarizedElements[I];
494
495      while (!I->use_empty()) {
496        if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
497          assert(ArgIndices.begin()->empty() &&
498                 "Load element should sort to front!");
499          I2->setName(I->getName()+".val");
500          LI->replaceAllUsesWith(I2);
501          AA.replaceWithNewValue(LI, I2);
502          LI->getParent()->getInstList().erase(LI);
503          DOUT << "*** Promoted load of argument '" << I->getName()
504               << "' in function '" << F->getName() << "'\n";
505        } else {
506          GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
507          std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
508
509          Function::arg_iterator TheArg = I2;
510          for (ScalarizeTable::iterator It = ArgIndices.begin();
511               *It != Operands; ++It, ++TheArg) {
512            assert(It != ArgIndices.end() && "GEP not handled??");
513          }
514
515          std::string NewName = I->getName();
516          for (unsigned i = 0, e = Operands.size(); i != e; ++i)
517            if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
518              NewName += "." + CI->getValue().toString(10);
519            else
520              NewName += ".x";
521          TheArg->setName(NewName+".val");
522
523          DOUT << "*** Promoted agg argument '" << TheArg->getName()
524               << "' of function '" << F->getName() << "'\n";
525
526          // All of the uses must be load instructions.  Replace them all with
527          // the argument specified by ArgNo.
528          while (!GEP->use_empty()) {
529            LoadInst *L = cast<LoadInst>(GEP->use_back());
530            L->replaceAllUsesWith(TheArg);
531            AA.replaceWithNewValue(L, TheArg);
532            L->getParent()->getInstList().erase(L);
533          }
534          AA.deleteValue(GEP);
535          GEP->getParent()->getInstList().erase(GEP);
536        }
537      }
538
539      // Increment I2 past all of the arguments added for this promoted pointer.
540      for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
541        ++I2;
542    }
543
544  // Notify the alias analysis implementation that we inserted a new argument.
545  if (ExtraArgHack)
546    AA.copyValue(Constant::getNullValue(Type::Int32Ty), NF->arg_begin());
547
548
549  // Tell the alias analysis that the old function is about to disappear.
550  AA.replaceWithNewValue(F, NF);
551
552  // Now that the old function is dead, delete it.
553  F->getParent()->getFunctionList().erase(F);
554  return NF;
555}
556