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