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