1 //===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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 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).
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!
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.
29 //===----------------------------------------------------------------------===//
31 #define DEBUG_TYPE "argpromotion"
32 #include "llvm/Transforms/IPO.h"
33 #include "llvm/Constants.h"
34 #include "llvm/DerivedTypes.h"
35 #include "llvm/Module.h"
36 #include "llvm/CallGraphSCCPass.h"
37 #include "llvm/Instructions.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/Analysis/CallGraph.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Support/CallSite.h"
42 #include "llvm/Support/CFG.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/ADT/DepthFirstIterator.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/Support/Compiler.h"
51 STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
52 STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
53 STATISTIC(NumByValArgsPromoted , "Number of byval arguments promoted");
54 STATISTIC(NumArgumentsDead , "Number of dead pointer args eliminated");
57 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
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);
66 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
67 static char ID; // Pass identification, replacement for typeid
68 ArgPromotion() : CallGraphSCCPass((intptr_t)&ID) {}
71 bool PromoteArguments(CallGraphNode *CGN);
72 bool isSafeToPromoteArgument(Argument *Arg, bool isByVal) const;
73 Function *DoPromotion(Function *F,
74 SmallPtrSet<Argument*, 8> &ArgsToPromote,
75 SmallPtrSet<Argument*, 8> &ByValArgsToTransform);
78 char ArgPromotion::ID = 0;
79 RegisterPass<ArgPromotion> X("argpromotion",
80 "Promote 'by reference' arguments to scalars");
83 Pass *llvm::createArgumentPromotionPass() {
84 return new ArgPromotion();
87 bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
88 bool Changed = false, LocalChange;
90 do { // Iterate until we stop promoting from this SCC.
92 // Attempt to promote arguments from all functions in this SCC.
93 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
94 LocalChange |= PromoteArguments(SCC[i]);
95 Changed |= LocalChange; // Remember that we changed something.
96 } while (LocalChange);
101 /// PromoteArguments - This method checks the specified function to see if there
102 /// are any promotable arguments and if it is safe to promote the function (for
103 /// example, all callers are direct). If safe to promote some arguments, it
104 /// calls the DoPromotion method.
106 bool ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
107 Function *F = CGN->getFunction();
109 // Make sure that it is local to this module.
110 if (!F || !F->hasInternalLinkage()) return false;
112 // First check: see if there are any pointer arguments! If not, quick exit.
113 SmallVector<std::pair<Argument*, unsigned>, 16> PointerArgs;
115 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
116 I != E; ++I, ++ArgNo)
117 if (isa<PointerType>(I->getType()))
118 PointerArgs.push_back(std::pair<Argument*, unsigned>(I, ArgNo));
119 if (PointerArgs.empty()) return false;
121 // Second check: make sure that all callers are direct callers. We can't
122 // transform functions that have indirect callers.
123 for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
125 CallSite CS = CallSite::get(*UI);
126 if (!CS.getInstruction()) // "Taking the address" of the function
129 // Ensure that this call site is CALLING the function, not passing it as
131 if (UI.getOperandNo() != 0)
135 // Check to see which arguments are promotable. If an argument is promotable,
136 // add it to ArgsToPromote.
137 SmallPtrSet<Argument*, 8> ArgsToPromote;
138 SmallPtrSet<Argument*, 8> ByValArgsToTransform;
139 for (unsigned i = 0; i != PointerArgs.size(); ++i) {
140 bool isByVal = F->paramHasAttr(PointerArgs[i].second+1, ParamAttr::ByVal);
142 // If this is a byval argument, and if the aggregate type is small, just
143 // pass the elements, which is always safe.
144 Argument *PtrArg = PointerArgs[i].first;
146 const Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
147 if (const StructType *STy = dyn_cast<StructType>(AgTy))
148 if (STy->getNumElements() <= 3) {
149 // If all the elements are first class types, we can promote it.
150 bool AllSimple = true;
151 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
152 if (!STy->getElementType(i)->isFirstClassType()) {
157 // Safe to transform, don't even bother trying to "promote" it.
158 // Passing the elements as a scalar will allow scalarrepl to hack on
159 // the new alloca we introduce.
161 ByValArgsToTransform.insert(PtrArg);
167 // Otherwise, see if we can promote the pointer to its value.
168 if (isSafeToPromoteArgument(PtrArg, isByVal))
169 ArgsToPromote.insert(PtrArg);
172 // No promotable pointer arguments.
173 if (ArgsToPromote.empty() && ByValArgsToTransform.empty()) return false;
175 Function *NewF = DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
177 // Update the call graph to know that the function has been transformed.
178 getAnalysis<CallGraph>().changeFunction(F, NewF);
182 /// IsAlwaysValidPointer - Return true if the specified pointer is always legal
184 static bool IsAlwaysValidPointer(Value *V) {
185 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
186 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V))
187 return IsAlwaysValidPointer(GEP->getOperand(0));
188 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
189 if (CE->getOpcode() == Instruction::GetElementPtr)
190 return IsAlwaysValidPointer(CE->getOperand(0));
195 /// AllCalleesPassInValidPointerForArgument - Return true if we can prove that
196 /// all callees pass in a valid pointer for the specified function argument.
197 static bool AllCalleesPassInValidPointerForArgument(Argument *Arg) {
198 Function *Callee = Arg->getParent();
200 unsigned ArgNo = std::distance(Callee->arg_begin(),
201 Function::arg_iterator(Arg));
203 // Look at all call sites of the function. At this pointer we know we only
204 // have direct callees.
205 for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
207 CallSite CS = CallSite::get(*UI);
208 assert(CS.getInstruction() && "Should only have direct calls!");
210 if (!IsAlwaysValidPointer(CS.getArgument(ArgNo)))
217 /// isSafeToPromoteArgument - As you might guess from the name of this method,
218 /// it checks to see if it is both safe and useful to promote the argument.
219 /// This method limits promotion of aggregates to only promote up to three
220 /// elements of the aggregate in order to avoid exploding the number of
221 /// arguments passed in.
222 bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg, bool isByVal) const {
223 // We can only promote this argument if all of the uses are loads, or are GEP
224 // instructions (with constant indices) that are subsequently loaded.
226 // We can also only promote the load if we can guarantee that it will happen.
227 // Promoting a load causes the load to be unconditionally executed in the
228 // caller, so we can't turn a conditional load into an unconditional load in
230 bool SafeToUnconditionallyLoad = false;
231 if (isByVal) // ByVal arguments are always safe to load from.
232 SafeToUnconditionallyLoad = true;
234 BasicBlock *EntryBlock = Arg->getParent()->begin();
235 SmallVector<LoadInst*, 16> Loads;
236 std::vector<SmallVector<ConstantInt*, 8> > GEPIndices;
237 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
239 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
240 if (LI->isVolatile()) return false; // Don't hack volatile loads
243 // If this load occurs in the entry block, then the pointer is
244 // unconditionally loaded.
245 SafeToUnconditionallyLoad |= LI->getParent() == EntryBlock;
246 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
247 if (GEP->use_empty()) {
248 // Dead GEP's cause trouble later. Just remove them if we run into
250 getAnalysis<AliasAnalysis>().deleteValue(GEP);
251 GEP->eraseFromParent();
252 return isSafeToPromoteArgument(Arg, isByVal);
254 // Ensure that all of the indices are constants.
255 SmallVector<ConstantInt*, 8> Operands;
256 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
257 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
258 Operands.push_back(C);
260 return false; // Not a constant operand GEP!
262 // Ensure that the only users of the GEP are load instructions.
263 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
265 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
266 if (LI->isVolatile()) return false; // Don't hack volatile loads
269 // If this load occurs in the entry block, then the pointer is
270 // unconditionally loaded.
271 SafeToUnconditionallyLoad |= LI->getParent() == EntryBlock;
276 // See if there is already a GEP with these indices. If not, check to
277 // make sure that we aren't promoting too many elements. If so, nothing
279 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
281 if (GEPIndices.size() == 3) {
282 DOUT << "argpromotion disable promoting argument '"
283 << Arg->getName() << "' because it would require adding more "
284 << "than 3 arguments to the function.\n";
285 // We limit aggregate promotion to only promoting up to three elements
289 GEPIndices.push_back(Operands);
292 return false; // Not a load or a GEP.
295 if (Loads.empty()) return true; // No users, this is a dead argument.
297 // If we decide that we want to promote this argument, the value is going to
298 // be unconditionally loaded in all callees. This is only safe to do if the
299 // pointer was going to be unconditionally loaded anyway (i.e. there is a load
300 // of the pointer in the entry block of the function) or if we can prove that
301 // all pointers passed in are always to legal locations (for example, no null
302 // pointers are passed in, no pointers to free'd memory, etc).
303 if (!SafeToUnconditionallyLoad &&
304 !AllCalleesPassInValidPointerForArgument(Arg))
305 return false; // Cannot prove that this is safe!!
307 // Okay, now we know that the argument is only used by load instructions and
308 // it is safe to unconditionally load the pointer. Use alias analysis to
309 // check to see if the pointer is guaranteed to not be modified from entry of
310 // the function to each of the load instructions.
312 // Because there could be several/many load instructions, remember which
313 // blocks we know to be transparent to the load.
314 SmallPtrSet<BasicBlock*, 16> TranspBlocks;
316 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
317 TargetData &TD = getAnalysis<TargetData>();
319 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
320 // Check to see if the load is invalidated from the start of the block to
322 LoadInst *Load = Loads[i];
323 BasicBlock *BB = Load->getParent();
325 const PointerType *LoadTy =
326 cast<PointerType>(Load->getOperand(0)->getType());
327 unsigned LoadSize = (unsigned)TD.getTypeStoreSize(LoadTy->getElementType());
329 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
330 return false; // Pointer is invalidated!
332 // Now check every path from the entry block to the load for transparency.
333 // To do this, we perform a depth first search on the inverse CFG from the
335 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
336 for (idf_ext_iterator<BasicBlock*, SmallPtrSet<BasicBlock*, 16> >
337 I = idf_ext_begin(*PI, TranspBlocks),
338 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
339 if (AA.canBasicBlockModify(**I, Arg, LoadSize))
343 // If the path from the entry of the function to each load is free of
344 // instructions that potentially invalidate the load, we can make the
350 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value*
351 /// elements are instances of ConstantInt.
353 struct GEPIdxComparator {
354 bool operator()(const std::vector<Value*> &LHS,
355 const std::vector<Value*> &RHS) const {
357 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
358 if (LHS[idx] != RHS[idx]) {
359 return cast<ConstantInt>(LHS[idx])->getZExtValue() <
360 cast<ConstantInt>(RHS[idx])->getZExtValue();
364 // Return less than if we ran out of stuff in LHS and we didn't run out of
366 return idx == LHS.size() && idx != RHS.size();
372 /// DoPromotion - This method actually performs the promotion of the specified
373 /// arguments, and returns the new function. At this point, we know that it's
375 Function *ArgPromotion::DoPromotion(Function *F,
376 SmallPtrSet<Argument*, 8> &ArgsToPromote,
377 SmallPtrSet<Argument*, 8> &ByValArgsToTransform) {
379 // Start by computing a new prototype for the function, which is the same as
380 // the old function, but has modified arguments.
381 const FunctionType *FTy = F->getFunctionType();
382 std::vector<const Type*> Params;
384 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
386 // ScalarizedElements - If we are promoting a pointer that has elements
387 // accessed out of it, keep track of which elements are accessed so that we
388 // can add one argument for each.
390 // Arguments that are directly loaded will have a zero element value here, to
391 // handle cases where there are both a direct load and GEP accesses.
393 std::map<Argument*, ScalarizeTable> ScalarizedElements;
395 // OriginalLoads - Keep track of a representative load instruction from the
396 // original function so that we can tell the alias analysis implementation
397 // what the new GEP/Load instructions we are inserting look like.
398 std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
400 // ParamAttrs - Keep track of the parameter attributes for the arguments
401 // that we are *not* promoting. For the ones that we do promote, the parameter
402 // attributes are lost
403 SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
404 const PAListPtr &PAL = F->getParamAttrs();
406 // Add any return attributes.
407 if (ParameterAttributes attrs = PAL.getParamAttrs(0))
408 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
410 unsigned ArgIndex = 1;
411 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
413 if (ByValArgsToTransform.count(I)) {
414 // Just add all the struct element types.
415 const Type *AgTy = cast<PointerType>(I->getType())->getElementType();
416 const StructType *STy = cast<StructType>(AgTy);
417 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
418 Params.push_back(STy->getElementType(i));
419 ++NumByValArgsPromoted;
420 } else if (!ArgsToPromote.count(I)) {
421 Params.push_back(I->getType());
422 if (ParameterAttributes attrs = PAL.getParamAttrs(ArgIndex))
423 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), attrs));
424 } else if (I->use_empty()) {
427 // Okay, this is being promoted. Check to see if there are any GEP uses
429 ScalarizeTable &ArgIndices = ScalarizedElements[I];
430 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
432 Instruction *User = cast<Instruction>(*UI);
433 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
434 std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
435 ArgIndices.insert(Indices);
437 if (LoadInst *L = dyn_cast<LoadInst>(User))
440 OrigLoad = cast<LoadInst>(User->use_back());
441 OriginalLoads[Indices] = OrigLoad;
444 // Add a parameter to the function for each element passed in.
445 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
446 E = ArgIndices.end(); SI != E; ++SI)
447 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(),
451 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
452 ++NumArgumentsPromoted;
454 ++NumAggregatesPromoted;
458 const Type *RetTy = FTy->getReturnType();
460 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
461 // have zero fixed arguments.
462 bool ExtraArgHack = false;
463 if (Params.empty() && FTy->isVarArg()) {
465 Params.push_back(Type::Int32Ty);
468 // Construct the new function type using the new arguments.
469 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
471 // Create the new function body and insert it into the module...
472 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
473 NF->setCallingConv(F->getCallingConv());
475 // Recompute the parameter attributes list based on the new arguments for
477 NF->setParamAttrs(PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end()));
478 ParamAttrsVec.clear();
480 if (F->hasCollector())
481 NF->setCollector(F->getCollector());
482 F->getParent()->getFunctionList().insert(F, NF);
484 // Get the alias analysis information that we need to update to reflect our
486 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
488 // Loop over all of the callers of the function, transforming the call sites
489 // to pass in the loaded pointers.
491 SmallVector<Value*, 16> Args;
492 while (!F->use_empty()) {
493 CallSite CS = CallSite::get(F->use_back());
494 Instruction *Call = CS.getInstruction();
495 const PAListPtr &CallPAL = CS.getParamAttrs();
497 // Add any return attributes.
498 if (ParameterAttributes attrs = CallPAL.getParamAttrs(0))
499 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
501 // Loop over the operands, inserting GEP and loads in the caller as
503 CallSite::arg_iterator AI = CS.arg_begin();
505 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
506 I != E; ++I, ++AI, ++ArgIndex)
507 if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
508 Args.push_back(*AI); // Unmodified argument
510 if (ParameterAttributes Attrs = CallPAL.getParamAttrs(ArgIndex))
511 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
513 } else if (ByValArgsToTransform.count(I)) {
514 // Emit a GEP and load for each element of the struct.
515 const Type *AgTy = cast<PointerType>(I->getType())->getElementType();
516 const StructType *STy = cast<StructType>(AgTy);
517 Value *Idxs[2] = { ConstantInt::get(Type::Int32Ty, 0), 0 };
518 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
519 Idxs[1] = ConstantInt::get(Type::Int32Ty, i);
520 Value *Idx = new GetElementPtrInst(*AI, Idxs, Idxs+2,
521 (*AI)->getName()+"."+utostr(i),
523 // TODO: Tell AA about the new values?
524 Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
526 } else if (!I->use_empty()) {
527 // Non-dead argument: insert GEPs and loads as appropriate.
528 ScalarizeTable &ArgIndices = ScalarizedElements[I];
529 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
530 E = ArgIndices.end(); SI != E; ++SI) {
532 LoadInst *OrigLoad = OriginalLoads[*SI];
534 V = new GetElementPtrInst(V, SI->begin(), SI->end(),
535 V->getName()+".idx", Call);
536 AA.copyValue(OrigLoad->getOperand(0), V);
538 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
539 AA.copyValue(OrigLoad, Args.back());
544 Args.push_back(Constant::getNullValue(Type::Int32Ty));
546 // Push any varargs arguments on the list
547 for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
549 if (ParameterAttributes Attrs = CallPAL.getParamAttrs(ArgIndex))
550 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
554 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
555 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
556 Args.begin(), Args.end(), "", Call);
557 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
558 cast<InvokeInst>(New)->setParamAttrs(PAListPtr::get(ParamAttrsVec.begin(),
559 ParamAttrsVec.end()));
561 New = new CallInst(NF, Args.begin(), Args.end(), "", Call);
562 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
563 cast<CallInst>(New)->setParamAttrs(PAListPtr::get(ParamAttrsVec.begin(),
564 ParamAttrsVec.end()));
565 if (cast<CallInst>(Call)->isTailCall())
566 cast<CallInst>(New)->setTailCall();
569 ParamAttrsVec.clear();
571 // Update the alias analysis implementation to know that we are replacing
572 // the old call with a new one.
573 AA.replaceWithNewValue(Call, New);
575 if (!Call->use_empty()) {
576 Call->replaceAllUsesWith(New);
580 // Finally, remove the old call from the program, reducing the use-count of
582 Call->eraseFromParent();
585 // Since we have now created the new function, splice the body of the old
586 // function right into the new function, leaving the old rotting hulk of the
588 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
590 // Loop over the argument list, transfering uses of the old arguments over to
591 // the new arguments, also transfering over the names as well.
593 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
594 I2 = NF->arg_begin(); I != E; ++I) {
595 if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
596 // If this is an unmodified argument, move the name and users over to the
598 I->replaceAllUsesWith(I2);
600 AA.replaceWithNewValue(I, I2);
605 if (ByValArgsToTransform.count(I)) {
606 // In the callee, we create an alloca, and store each of the new incoming
607 // arguments into the alloca.
608 Instruction *InsertPt = NF->begin()->begin();
610 // Just add all the struct element types.
611 const Type *AgTy = cast<PointerType>(I->getType())->getElementType();
612 Value *TheAlloca = new AllocaInst(AgTy, 0, "", InsertPt);
613 const StructType *STy = cast<StructType>(AgTy);
614 Value *Idxs[2] = { ConstantInt::get(Type::Int32Ty, 0), 0 };
616 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
617 Idxs[1] = ConstantInt::get(Type::Int32Ty, i);
618 Value *Idx = new GetElementPtrInst(TheAlloca, Idxs, Idxs+2,
619 TheAlloca->getName()+"."+utostr(i),
621 I2->setName(I->getName()+"."+utostr(i));
622 new StoreInst(I2++, Idx, InsertPt);
625 // Anything that used the arg should now use the alloca.
626 I->replaceAllUsesWith(TheAlloca);
627 TheAlloca->takeName(I);
628 AA.replaceWithNewValue(I, TheAlloca);
632 if (I->use_empty()) {
637 // Otherwise, if we promoted this argument, then all users are load
638 // instructions, and all loads should be using the new argument that we
640 ScalarizeTable &ArgIndices = ScalarizedElements[I];
642 while (!I->use_empty()) {
643 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
644 assert(ArgIndices.begin()->empty() &&
645 "Load element should sort to front!");
646 I2->setName(I->getName()+".val");
647 LI->replaceAllUsesWith(I2);
648 AA.replaceWithNewValue(LI, I2);
649 LI->eraseFromParent();
650 DOUT << "*** Promoted load of argument '" << I->getName()
651 << "' in function '" << F->getName() << "'\n";
653 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
654 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
656 Function::arg_iterator TheArg = I2;
657 for (ScalarizeTable::iterator It = ArgIndices.begin();
658 *It != Operands; ++It, ++TheArg) {
659 assert(It != ArgIndices.end() && "GEP not handled??");
662 std::string NewName = I->getName();
663 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
664 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
665 NewName += "." + CI->getValue().toStringUnsigned(10);
668 TheArg->setName(NewName+".val");
670 DOUT << "*** Promoted agg argument '" << TheArg->getName()
671 << "' of function '" << F->getName() << "'\n";
673 // All of the uses must be load instructions. Replace them all with
674 // the argument specified by ArgNo.
675 while (!GEP->use_empty()) {
676 LoadInst *L = cast<LoadInst>(GEP->use_back());
677 L->replaceAllUsesWith(TheArg);
678 AA.replaceWithNewValue(L, TheArg);
679 L->eraseFromParent();
682 GEP->eraseFromParent();
686 // Increment I2 past all of the arguments added for this promoted pointer.
687 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
691 // Notify the alias analysis implementation that we inserted a new argument.
693 AA.copyValue(Constant::getNullValue(Type::Int32Ty), NF->arg_begin());
696 // Tell the alias analysis that the old function is about to disappear.
697 AA.replaceWithNewValue(F, NF);
699 // Now that the old function is dead, delete it.
700 F->eraseFromParent();