LLVM API Documentation

ArgumentPromotion.cpp
Go to the documentation of this file.
00001 //===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass promotes "by reference" arguments to be "by value" arguments.  In
00011 // practice, this means looking for internal functions that have pointer
00012 // arguments.  If it can prove, through the use of alias analysis, that an
00013 // argument is *only* loaded, then it can pass the value into the function
00014 // instead of the address of the value.  This can cause recursive simplification
00015 // of code and lead to the elimination of allocas (especially in C++ template
00016 // code like the STL).
00017 //
00018 // This pass also handles aggregate arguments that are passed into a function,
00019 // scalarizing them if the elements of the aggregate are only loaded.  Note that
00020 // by default it refuses to scalarize aggregates which would require passing in
00021 // more than three operands to the function, because passing thousands of
00022 // operands for a large array or structure is unprofitable! This limit can be
00023 // configured or disabled, however.
00024 //
00025 // Note that this transformation could also be done for arguments that are only
00026 // stored to (returning the value instead), but does not currently.  This case
00027 // would be best handled when and if LLVM begins supporting multiple return
00028 // values from functions.
00029 //
00030 //===----------------------------------------------------------------------===//
00031 
00032 #include "llvm/Transforms/IPO.h"
00033 #include "llvm/ADT/DepthFirstIterator.h"
00034 #include "llvm/ADT/Statistic.h"
00035 #include "llvm/ADT/StringExtras.h"
00036 #include "llvm/Analysis/AliasAnalysis.h"
00037 #include "llvm/Analysis/CallGraph.h"
00038 #include "llvm/Analysis/CallGraphSCCPass.h"
00039 #include "llvm/IR/CFG.h"
00040 #include "llvm/IR/CallSite.h"
00041 #include "llvm/IR/Constants.h"
00042 #include "llvm/IR/DerivedTypes.h"
00043 #include "llvm/IR/Instructions.h"
00044 #include "llvm/IR/LLVMContext.h"
00045 #include "llvm/IR/Module.h"
00046 #include "llvm/Support/Debug.h"
00047 #include "llvm/Support/raw_ostream.h"
00048 #include <set>
00049 using namespace llvm;
00050 
00051 #define DEBUG_TYPE "argpromotion"
00052 
00053 STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
00054 STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
00055 STATISTIC(NumByValArgsPromoted , "Number of byval arguments promoted");
00056 STATISTIC(NumArgumentsDead     , "Number of dead pointer args eliminated");
00057 
00058 namespace {
00059   /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
00060   ///
00061   struct ArgPromotion : public CallGraphSCCPass {
00062     void getAnalysisUsage(AnalysisUsage &AU) const override {
00063       AU.addRequired<AliasAnalysis>();
00064       CallGraphSCCPass::getAnalysisUsage(AU);
00065     }
00066 
00067     bool runOnSCC(CallGraphSCC &SCC) override;
00068     static char ID; // Pass identification, replacement for typeid
00069     explicit ArgPromotion(unsigned maxElements = 3)
00070         : CallGraphSCCPass(ID), maxElements(maxElements) {
00071       initializeArgPromotionPass(*PassRegistry::getPassRegistry());
00072     }
00073 
00074     /// A vector used to hold the indices of a single GEP instruction
00075     typedef std::vector<uint64_t> IndicesVector;
00076 
00077   private:
00078     CallGraphNode *PromoteArguments(CallGraphNode *CGN);
00079     bool isSafeToPromoteArgument(Argument *Arg, bool isByVal) const;
00080     CallGraphNode *DoPromotion(Function *F,
00081                                SmallPtrSet<Argument*, 8> &ArgsToPromote,
00082                                SmallPtrSet<Argument*, 8> &ByValArgsToTransform);
00083     /// The maximum number of elements to expand, or 0 for unlimited.
00084     unsigned maxElements;
00085   };
00086 }
00087 
00088 char ArgPromotion::ID = 0;
00089 INITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion",
00090                 "Promote 'by reference' arguments to scalars", false, false)
00091 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00092 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
00093 INITIALIZE_PASS_END(ArgPromotion, "argpromotion",
00094                 "Promote 'by reference' arguments to scalars", false, false)
00095 
00096 Pass *llvm::createArgumentPromotionPass(unsigned maxElements) {
00097   return new ArgPromotion(maxElements);
00098 }
00099 
00100 bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
00101   bool Changed = false, LocalChange;
00102 
00103   do {  // Iterate until we stop promoting from this SCC.
00104     LocalChange = false;
00105     // Attempt to promote arguments from all functions in this SCC.
00106     for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
00107       if (CallGraphNode *CGN = PromoteArguments(*I)) {
00108         LocalChange = true;
00109         SCC.ReplaceNode(*I, CGN);
00110       }
00111     }
00112     Changed |= LocalChange;               // Remember that we changed something.
00113   } while (LocalChange);
00114   
00115   return Changed;
00116 }
00117 
00118 /// PromoteArguments - This method checks the specified function to see if there
00119 /// are any promotable arguments and if it is safe to promote the function (for
00120 /// example, all callers are direct).  If safe to promote some arguments, it
00121 /// calls the DoPromotion method.
00122 ///
00123 CallGraphNode *ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
00124   Function *F = CGN->getFunction();
00125 
00126   // Make sure that it is local to this module.
00127   if (!F || !F->hasLocalLinkage()) return 0;
00128 
00129   // First check: see if there are any pointer arguments!  If not, quick exit.
00130   SmallVector<Argument*, 16> PointerArgs;
00131   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
00132     if (I->getType()->isPointerTy())
00133       PointerArgs.push_back(I);
00134   if (PointerArgs.empty()) return 0;
00135 
00136   // Second check: make sure that all callers are direct callers.  We can't
00137   // transform functions that have indirect callers.  Also see if the function
00138   // is self-recursive.
00139   bool isSelfRecursive = false;
00140   for (Use &U : F->uses()) {
00141     CallSite CS(U.getUser());
00142     // Must be a direct call.
00143     if (CS.getInstruction() == 0 || !CS.isCallee(&U)) return 0;
00144     
00145     if (CS.getInstruction()->getParent()->getParent() == F)
00146       isSelfRecursive = true;
00147   }
00148   
00149   // Check to see which arguments are promotable.  If an argument is promotable,
00150   // add it to ArgsToPromote.
00151   SmallPtrSet<Argument*, 8> ArgsToPromote;
00152   SmallPtrSet<Argument*, 8> ByValArgsToTransform;
00153   for (unsigned i = 0, e = PointerArgs.size(); i != e; ++i) {
00154     Argument *PtrArg = PointerArgs[i];
00155     Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
00156 
00157     // If this is a byval argument, and if the aggregate type is small, just
00158     // pass the elements, which is always safe.  This does not apply to
00159     // inalloca.
00160     if (PtrArg->hasByValAttr()) {
00161       if (StructType *STy = dyn_cast<StructType>(AgTy)) {
00162         if (maxElements > 0 && STy->getNumElements() > maxElements) {
00163           DEBUG(dbgs() << "argpromotion disable promoting argument '"
00164                 << PtrArg->getName() << "' because it would require adding more"
00165                 << " than " << maxElements << " arguments to the function.\n");
00166           continue;
00167         }
00168         
00169         // If all the elements are single-value types, we can promote it.
00170         bool AllSimple = true;
00171         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
00172           if (!STy->getElementType(i)->isSingleValueType()) {
00173             AllSimple = false;
00174             break;
00175           }
00176         }
00177 
00178         // Safe to transform, don't even bother trying to "promote" it.
00179         // Passing the elements as a scalar will allow scalarrepl to hack on
00180         // the new alloca we introduce.
00181         if (AllSimple) {
00182           ByValArgsToTransform.insert(PtrArg);
00183           continue;
00184         }
00185       }
00186     }
00187 
00188     // If the argument is a recursive type and we're in a recursive
00189     // function, we could end up infinitely peeling the function argument.
00190     if (isSelfRecursive) {
00191       if (StructType *STy = dyn_cast<StructType>(AgTy)) {
00192         bool RecursiveType = false;
00193         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
00194           if (STy->getElementType(i) == PtrArg->getType()) {
00195             RecursiveType = true;
00196             break;
00197           }
00198         }
00199         if (RecursiveType)
00200           continue;
00201       }
00202     }
00203     
00204     // Otherwise, see if we can promote the pointer to its value.
00205     if (isSafeToPromoteArgument(PtrArg, PtrArg->hasByValOrInAllocaAttr()))
00206       ArgsToPromote.insert(PtrArg);
00207   }
00208 
00209   // No promotable pointer arguments.
00210   if (ArgsToPromote.empty() && ByValArgsToTransform.empty()) 
00211     return 0;
00212 
00213   return DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
00214 }
00215 
00216 /// AllCallersPassInValidPointerForArgument - Return true if we can prove that
00217 /// all callees pass in a valid pointer for the specified function argument.
00218 static bool AllCallersPassInValidPointerForArgument(Argument *Arg) {
00219   Function *Callee = Arg->getParent();
00220 
00221   unsigned ArgNo = Arg->getArgNo();
00222 
00223   // Look at all call sites of the function.  At this pointer we know we only
00224   // have direct callees.
00225   for (User *U : Callee->users()) {
00226     CallSite CS(U);
00227     assert(CS && "Should only have direct calls!");
00228 
00229     if (!CS.getArgument(ArgNo)->isDereferenceablePointer())
00230       return false;
00231   }
00232   return true;
00233 }
00234 
00235 /// Returns true if Prefix is a prefix of longer. That means, Longer has a size
00236 /// that is greater than or equal to the size of prefix, and each of the
00237 /// elements in Prefix is the same as the corresponding elements in Longer.
00238 ///
00239 /// This means it also returns true when Prefix and Longer are equal!
00240 static bool IsPrefix(const ArgPromotion::IndicesVector &Prefix,
00241                      const ArgPromotion::IndicesVector &Longer) {
00242   if (Prefix.size() > Longer.size())
00243     return false;
00244   return std::equal(Prefix.begin(), Prefix.end(), Longer.begin());
00245 }
00246 
00247 
00248 /// Checks if Indices, or a prefix of Indices, is in Set.
00249 static bool PrefixIn(const ArgPromotion::IndicesVector &Indices,
00250                      std::set<ArgPromotion::IndicesVector> &Set) {
00251     std::set<ArgPromotion::IndicesVector>::iterator Low;
00252     Low = Set.upper_bound(Indices);
00253     if (Low != Set.begin())
00254       Low--;
00255     // Low is now the last element smaller than or equal to Indices. This means
00256     // it points to a prefix of Indices (possibly Indices itself), if such
00257     // prefix exists.
00258     //
00259     // This load is safe if any prefix of its operands is safe to load.
00260     return Low != Set.end() && IsPrefix(*Low, Indices);
00261 }
00262 
00263 /// Mark the given indices (ToMark) as safe in the given set of indices
00264 /// (Safe). Marking safe usually means adding ToMark to Safe. However, if there
00265 /// is already a prefix of Indices in Safe, Indices are implicitely marked safe
00266 /// already. Furthermore, any indices that Indices is itself a prefix of, are
00267 /// removed from Safe (since they are implicitely safe because of Indices now).
00268 static void MarkIndicesSafe(const ArgPromotion::IndicesVector &ToMark,
00269                             std::set<ArgPromotion::IndicesVector> &Safe) {
00270   std::set<ArgPromotion::IndicesVector>::iterator Low;
00271   Low = Safe.upper_bound(ToMark);
00272   // Guard against the case where Safe is empty
00273   if (Low != Safe.begin())
00274     Low--;
00275   // Low is now the last element smaller than or equal to Indices. This
00276   // means it points to a prefix of Indices (possibly Indices itself), if
00277   // such prefix exists.
00278   if (Low != Safe.end()) {
00279     if (IsPrefix(*Low, ToMark))
00280       // If there is already a prefix of these indices (or exactly these
00281       // indices) marked a safe, don't bother adding these indices
00282       return;
00283 
00284     // Increment Low, so we can use it as a "insert before" hint
00285     ++Low;
00286   }
00287   // Insert
00288   Low = Safe.insert(Low, ToMark);
00289   ++Low;
00290   // If there we're a prefix of longer index list(s), remove those
00291   std::set<ArgPromotion::IndicesVector>::iterator End = Safe.end();
00292   while (Low != End && IsPrefix(ToMark, *Low)) {
00293     std::set<ArgPromotion::IndicesVector>::iterator Remove = Low;
00294     ++Low;
00295     Safe.erase(Remove);
00296   }
00297 }
00298 
00299 /// isSafeToPromoteArgument - As you might guess from the name of this method,
00300 /// it checks to see if it is both safe and useful to promote the argument.
00301 /// This method limits promotion of aggregates to only promote up to three
00302 /// elements of the aggregate in order to avoid exploding the number of
00303 /// arguments passed in.
00304 bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg,
00305                                            bool isByValOrInAlloca) const {
00306   typedef std::set<IndicesVector> GEPIndicesSet;
00307 
00308   // Quick exit for unused arguments
00309   if (Arg->use_empty())
00310     return true;
00311 
00312   // We can only promote this argument if all of the uses are loads, or are GEP
00313   // instructions (with constant indices) that are subsequently loaded.
00314   //
00315   // Promoting the argument causes it to be loaded in the caller
00316   // unconditionally. This is only safe if we can prove that either the load
00317   // would have happened in the callee anyway (ie, there is a load in the entry
00318   // block) or the pointer passed in at every call site is guaranteed to be
00319   // valid.
00320   // In the former case, invalid loads can happen, but would have happened
00321   // anyway, in the latter case, invalid loads won't happen. This prevents us
00322   // from introducing an invalid load that wouldn't have happened in the
00323   // original code.
00324   //
00325   // This set will contain all sets of indices that are loaded in the entry
00326   // block, and thus are safe to unconditionally load in the caller.
00327   //
00328   // This optimization is also safe for InAlloca parameters, because it verifies
00329   // that the address isn't captured.
00330   GEPIndicesSet SafeToUnconditionallyLoad;
00331 
00332   // This set contains all the sets of indices that we are planning to promote.
00333   // This makes it possible to limit the number of arguments added.
00334   GEPIndicesSet ToPromote;
00335 
00336   // If the pointer is always valid, any load with first index 0 is valid.
00337   if (isByValOrInAlloca || AllCallersPassInValidPointerForArgument(Arg))
00338     SafeToUnconditionallyLoad.insert(IndicesVector(1, 0));
00339 
00340   // First, iterate the entry block and mark loads of (geps of) arguments as
00341   // safe.
00342   BasicBlock *EntryBlock = Arg->getParent()->begin();
00343   // Declare this here so we can reuse it
00344   IndicesVector Indices;
00345   for (BasicBlock::iterator I = EntryBlock->begin(), E = EntryBlock->end();
00346        I != E; ++I)
00347     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00348       Value *V = LI->getPointerOperand();
00349       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
00350         V = GEP->getPointerOperand();
00351         if (V == Arg) {
00352           // This load actually loads (part of) Arg? Check the indices then.
00353           Indices.reserve(GEP->getNumIndices());
00354           for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
00355                II != IE; ++II)
00356             if (ConstantInt *CI = dyn_cast<ConstantInt>(*II))
00357               Indices.push_back(CI->getSExtValue());
00358             else
00359               // We found a non-constant GEP index for this argument? Bail out
00360               // right away, can't promote this argument at all.
00361               return false;
00362 
00363           // Indices checked out, mark them as safe
00364           MarkIndicesSafe(Indices, SafeToUnconditionallyLoad);
00365           Indices.clear();
00366         }
00367       } else if (V == Arg) {
00368         // Direct loads are equivalent to a GEP with a single 0 index.
00369         MarkIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
00370       }
00371     }
00372 
00373   // Now, iterate all uses of the argument to see if there are any uses that are
00374   // not (GEP+)loads, or any (GEP+)loads that are not safe to promote.
00375   SmallVector<LoadInst*, 16> Loads;
00376   IndicesVector Operands;
00377   for (Use &U : Arg->uses()) {
00378     User *UR = U.getUser();
00379     Operands.clear();
00380     if (LoadInst *LI = dyn_cast<LoadInst>(UR)) {
00381       // Don't hack volatile/atomic loads
00382       if (!LI->isSimple()) return false;
00383       Loads.push_back(LI);
00384       // Direct loads are equivalent to a GEP with a zero index and then a load.
00385       Operands.push_back(0);
00386     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UR)) {
00387       if (GEP->use_empty()) {
00388         // Dead GEP's cause trouble later.  Just remove them if we run into
00389         // them.
00390         getAnalysis<AliasAnalysis>().deleteValue(GEP);
00391         GEP->eraseFromParent();
00392         // TODO: This runs the above loop over and over again for dead GEPs
00393         // Couldn't we just do increment the UI iterator earlier and erase the
00394         // use?
00395         return isSafeToPromoteArgument(Arg, isByValOrInAlloca);
00396       }
00397 
00398       // Ensure that all of the indices are constants.
00399       for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end();
00400         i != e; ++i)
00401         if (ConstantInt *C = dyn_cast<ConstantInt>(*i))
00402           Operands.push_back(C->getSExtValue());
00403         else
00404           return false;  // Not a constant operand GEP!
00405 
00406       // Ensure that the only users of the GEP are load instructions.
00407       for (User *GEPU : GEP->users())
00408         if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
00409           // Don't hack volatile/atomic loads
00410           if (!LI->isSimple()) return false;
00411           Loads.push_back(LI);
00412         } else {
00413           // Other uses than load?
00414           return false;
00415         }
00416     } else {
00417       return false;  // Not a load or a GEP.
00418     }
00419 
00420     // Now, see if it is safe to promote this load / loads of this GEP. Loading
00421     // is safe if Operands, or a prefix of Operands, is marked as safe.
00422     if (!PrefixIn(Operands, SafeToUnconditionallyLoad))
00423       return false;
00424 
00425     // See if we are already promoting a load with these indices. If not, check
00426     // to make sure that we aren't promoting too many elements.  If so, nothing
00427     // to do.
00428     if (ToPromote.find(Operands) == ToPromote.end()) {
00429       if (maxElements > 0 && ToPromote.size() == maxElements) {
00430         DEBUG(dbgs() << "argpromotion not promoting argument '"
00431               << Arg->getName() << "' because it would require adding more "
00432               << "than " << maxElements << " arguments to the function.\n");
00433         // We limit aggregate promotion to only promoting up to a fixed number
00434         // of elements of the aggregate.
00435         return false;
00436       }
00437       ToPromote.insert(Operands);
00438     }
00439   }
00440 
00441   if (Loads.empty()) return true;  // No users, this is a dead argument.
00442 
00443   // Okay, now we know that the argument is only used by load instructions and
00444   // it is safe to unconditionally perform all of them. Use alias analysis to
00445   // check to see if the pointer is guaranteed to not be modified from entry of
00446   // the function to each of the load instructions.
00447 
00448   // Because there could be several/many load instructions, remember which
00449   // blocks we know to be transparent to the load.
00450   SmallPtrSet<BasicBlock*, 16> TranspBlocks;
00451 
00452   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
00453 
00454   for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
00455     // Check to see if the load is invalidated from the start of the block to
00456     // the load itself.
00457     LoadInst *Load = Loads[i];
00458     BasicBlock *BB = Load->getParent();
00459 
00460     AliasAnalysis::Location Loc = AA.getLocation(Load);
00461     if (AA.canInstructionRangeModify(BB->front(), *Load, Loc))
00462       return false;  // Pointer is invalidated!
00463 
00464     // Now check every path from the entry block to the load for transparency.
00465     // To do this, we perform a depth first search on the inverse CFG from the
00466     // loading block.
00467     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
00468       BasicBlock *P = *PI;
00469       for (idf_ext_iterator<BasicBlock*, SmallPtrSet<BasicBlock*, 16> >
00470              I = idf_ext_begin(P, TranspBlocks),
00471              E = idf_ext_end(P, TranspBlocks); I != E; ++I)
00472         if (AA.canBasicBlockModify(**I, Loc))
00473           return false;
00474     }
00475   }
00476 
00477   // If the path from the entry of the function to each load is free of
00478   // instructions that potentially invalidate the load, we can make the
00479   // transformation!
00480   return true;
00481 }
00482 
00483 /// DoPromotion - This method actually performs the promotion of the specified
00484 /// arguments, and returns the new function.  At this point, we know that it's
00485 /// safe to do so.
00486 CallGraphNode *ArgPromotion::DoPromotion(Function *F,
00487                                SmallPtrSet<Argument*, 8> &ArgsToPromote,
00488                               SmallPtrSet<Argument*, 8> &ByValArgsToTransform) {
00489 
00490   // Start by computing a new prototype for the function, which is the same as
00491   // the old function, but has modified arguments.
00492   FunctionType *FTy = F->getFunctionType();
00493   std::vector<Type*> Params;
00494 
00495   typedef std::set<IndicesVector> ScalarizeTable;
00496 
00497   // ScalarizedElements - If we are promoting a pointer that has elements
00498   // accessed out of it, keep track of which elements are accessed so that we
00499   // can add one argument for each.
00500   //
00501   // Arguments that are directly loaded will have a zero element value here, to
00502   // handle cases where there are both a direct load and GEP accesses.
00503   //
00504   std::map<Argument*, ScalarizeTable> ScalarizedElements;
00505 
00506   // OriginalLoads - Keep track of a representative load instruction from the
00507   // original function so that we can tell the alias analysis implementation
00508   // what the new GEP/Load instructions we are inserting look like.
00509   // We need to keep the original loads for each argument and the elements
00510   // of the argument that are accessed.
00511   std::map<std::pair<Argument*, IndicesVector>, LoadInst*> OriginalLoads;
00512 
00513   // Attribute - Keep track of the parameter attributes for the arguments
00514   // that we are *not* promoting. For the ones that we do promote, the parameter
00515   // attributes are lost
00516   SmallVector<AttributeSet, 8> AttributesVec;
00517   const AttributeSet &PAL = F->getAttributes();
00518 
00519   // Add any return attributes.
00520   if (PAL.hasAttributes(AttributeSet::ReturnIndex))
00521     AttributesVec.push_back(AttributeSet::get(F->getContext(),
00522                                               PAL.getRetAttributes()));
00523 
00524   // First, determine the new argument list
00525   unsigned ArgIndex = 1;
00526   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
00527        ++I, ++ArgIndex) {
00528     if (ByValArgsToTransform.count(I)) {
00529       // Simple byval argument? Just add all the struct element types.
00530       Type *AgTy = cast<PointerType>(I->getType())->getElementType();
00531       StructType *STy = cast<StructType>(AgTy);
00532       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
00533         Params.push_back(STy->getElementType(i));
00534       ++NumByValArgsPromoted;
00535     } else if (!ArgsToPromote.count(I)) {
00536       // Unchanged argument
00537       Params.push_back(I->getType());
00538       AttributeSet attrs = PAL.getParamAttributes(ArgIndex);
00539       if (attrs.hasAttributes(ArgIndex)) {
00540         AttrBuilder B(attrs, ArgIndex);
00541         AttributesVec.
00542           push_back(AttributeSet::get(F->getContext(), Params.size(), B));
00543       }
00544     } else if (I->use_empty()) {
00545       // Dead argument (which are always marked as promotable)
00546       ++NumArgumentsDead;
00547     } else {
00548       // Okay, this is being promoted. This means that the only uses are loads
00549       // or GEPs which are only used by loads
00550 
00551       // In this table, we will track which indices are loaded from the argument
00552       // (where direct loads are tracked as no indices).
00553       ScalarizeTable &ArgIndices = ScalarizedElements[I];
00554       for (User *U : I->users()) {
00555         Instruction *UI = cast<Instruction>(U);
00556         assert(isa<LoadInst>(UI) || isa<GetElementPtrInst>(UI));
00557         IndicesVector Indices;
00558         Indices.reserve(UI->getNumOperands() - 1);
00559         // Since loads will only have a single operand, and GEPs only a single
00560         // non-index operand, this will record direct loads without any indices,
00561         // and gep+loads with the GEP indices.
00562         for (User::op_iterator II = UI->op_begin() + 1, IE = UI->op_end();
00563              II != IE; ++II)
00564           Indices.push_back(cast<ConstantInt>(*II)->getSExtValue());
00565         // GEPs with a single 0 index can be merged with direct loads
00566         if (Indices.size() == 1 && Indices.front() == 0)
00567           Indices.clear();
00568         ArgIndices.insert(Indices);
00569         LoadInst *OrigLoad;
00570         if (LoadInst *L = dyn_cast<LoadInst>(UI))
00571           OrigLoad = L;
00572         else
00573           // Take any load, we will use it only to update Alias Analysis
00574           OrigLoad = cast<LoadInst>(UI->user_back());
00575         OriginalLoads[std::make_pair(I, Indices)] = OrigLoad;
00576       }
00577 
00578       // Add a parameter to the function for each element passed in.
00579       for (ScalarizeTable::iterator SI = ArgIndices.begin(),
00580              E = ArgIndices.end(); SI != E; ++SI) {
00581         // not allowed to dereference ->begin() if size() is 0
00582         Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
00583         assert(Params.back());
00584       }
00585 
00586       if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
00587         ++NumArgumentsPromoted;
00588       else
00589         ++NumAggregatesPromoted;
00590     }
00591   }
00592 
00593   // Add any function attributes.
00594   if (PAL.hasAttributes(AttributeSet::FunctionIndex))
00595     AttributesVec.push_back(AttributeSet::get(FTy->getContext(),
00596                                               PAL.getFnAttributes()));
00597 
00598   Type *RetTy = FTy->getReturnType();
00599 
00600   // Construct the new function type using the new arguments.
00601   FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
00602 
00603   // Create the new function body and insert it into the module.
00604   Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
00605   NF->copyAttributesFrom(F);
00606 
00607   
00608   DEBUG(dbgs() << "ARG PROMOTION:  Promoting to:" << *NF << "\n"
00609         << "From: " << *F);
00610   
00611   // Recompute the parameter attributes list based on the new arguments for
00612   // the function.
00613   NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec));
00614   AttributesVec.clear();
00615 
00616   F->getParent()->getFunctionList().insert(F, NF);
00617   NF->takeName(F);
00618 
00619   // Get the alias analysis information that we need to update to reflect our
00620   // changes.
00621   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
00622 
00623   // Get the callgraph information that we need to update to reflect our
00624   // changes.
00625   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
00626 
00627   // Get a new callgraph node for NF.
00628   CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
00629 
00630   // Loop over all of the callers of the function, transforming the call sites
00631   // to pass in the loaded pointers.
00632   //
00633   SmallVector<Value*, 16> Args;
00634   while (!F->use_empty()) {
00635     CallSite CS(F->user_back());
00636     assert(CS.getCalledFunction() == F);
00637     Instruction *Call = CS.getInstruction();
00638     const AttributeSet &CallPAL = CS.getAttributes();
00639 
00640     // Add any return attributes.
00641     if (CallPAL.hasAttributes(AttributeSet::ReturnIndex))
00642       AttributesVec.push_back(AttributeSet::get(F->getContext(),
00643                                                 CallPAL.getRetAttributes()));
00644 
00645     // Loop over the operands, inserting GEP and loads in the caller as
00646     // appropriate.
00647     CallSite::arg_iterator AI = CS.arg_begin();
00648     ArgIndex = 1;
00649     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
00650          I != E; ++I, ++AI, ++ArgIndex)
00651       if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
00652         Args.push_back(*AI);          // Unmodified argument
00653 
00654         if (CallPAL.hasAttributes(ArgIndex)) {
00655           AttrBuilder B(CallPAL, ArgIndex);
00656           AttributesVec.
00657             push_back(AttributeSet::get(F->getContext(), Args.size(), B));
00658         }
00659       } else if (ByValArgsToTransform.count(I)) {
00660         // Emit a GEP and load for each element of the struct.
00661         Type *AgTy = cast<PointerType>(I->getType())->getElementType();
00662         StructType *STy = cast<StructType>(AgTy);
00663         Value *Idxs[2] = {
00664               ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), 0 };
00665         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
00666           Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
00667           Value *Idx = GetElementPtrInst::Create(*AI, Idxs,
00668                                                  (*AI)->getName()+"."+utostr(i),
00669                                                  Call);
00670           // TODO: Tell AA about the new values?
00671           Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
00672         }
00673       } else if (!I->use_empty()) {
00674         // Non-dead argument: insert GEPs and loads as appropriate.
00675         ScalarizeTable &ArgIndices = ScalarizedElements[I];
00676         // Store the Value* version of the indices in here, but declare it now
00677         // for reuse.
00678         std::vector<Value*> Ops;
00679         for (ScalarizeTable::iterator SI = ArgIndices.begin(),
00680                E = ArgIndices.end(); SI != E; ++SI) {
00681           Value *V = *AI;
00682           LoadInst *OrigLoad = OriginalLoads[std::make_pair(I, *SI)];
00683           if (!SI->empty()) {
00684             Ops.reserve(SI->size());
00685             Type *ElTy = V->getType();
00686             for (IndicesVector::const_iterator II = SI->begin(),
00687                  IE = SI->end(); II != IE; ++II) {
00688               // Use i32 to index structs, and i64 for others (pointers/arrays).
00689               // This satisfies GEP constraints.
00690               Type *IdxTy = (ElTy->isStructTy() ?
00691                     Type::getInt32Ty(F->getContext()) : 
00692                     Type::getInt64Ty(F->getContext()));
00693               Ops.push_back(ConstantInt::get(IdxTy, *II));
00694               // Keep track of the type we're currently indexing.
00695               ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(*II);
00696             }
00697             // And create a GEP to extract those indices.
00698             V = GetElementPtrInst::Create(V, Ops, V->getName()+".idx", Call);
00699             Ops.clear();
00700             AA.copyValue(OrigLoad->getOperand(0), V);
00701           }
00702           // Since we're replacing a load make sure we take the alignment
00703           // of the previous load.
00704           LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call);
00705           newLoad->setAlignment(OrigLoad->getAlignment());
00706           // Transfer the TBAA info too.
00707           newLoad->setMetadata(LLVMContext::MD_tbaa,
00708                                OrigLoad->getMetadata(LLVMContext::MD_tbaa));
00709           Args.push_back(newLoad);
00710           AA.copyValue(OrigLoad, Args.back());
00711         }
00712       }
00713 
00714     // Push any varargs arguments on the list.
00715     for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
00716       Args.push_back(*AI);
00717       if (CallPAL.hasAttributes(ArgIndex)) {
00718         AttrBuilder B(CallPAL, ArgIndex);
00719         AttributesVec.
00720           push_back(AttributeSet::get(F->getContext(), Args.size(), B));
00721       }
00722     }
00723 
00724     // Add any function attributes.
00725     if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
00726       AttributesVec.push_back(AttributeSet::get(Call->getContext(),
00727                                                 CallPAL.getFnAttributes()));
00728 
00729     Instruction *New;
00730     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
00731       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
00732                                Args, "", Call);
00733       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
00734       cast<InvokeInst>(New)->setAttributes(AttributeSet::get(II->getContext(),
00735                                                             AttributesVec));
00736     } else {
00737       New = CallInst::Create(NF, Args, "", Call);
00738       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
00739       cast<CallInst>(New)->setAttributes(AttributeSet::get(New->getContext(),
00740                                                           AttributesVec));
00741       if (cast<CallInst>(Call)->isTailCall())
00742         cast<CallInst>(New)->setTailCall();
00743     }
00744     Args.clear();
00745     AttributesVec.clear();
00746 
00747     // Update the alias analysis implementation to know that we are replacing
00748     // the old call with a new one.
00749     AA.replaceWithNewValue(Call, New);
00750 
00751     // Update the callgraph to know that the callsite has been transformed.
00752     CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
00753     CalleeNode->replaceCallEdge(Call, New, NF_CGN);
00754 
00755     if (!Call->use_empty()) {
00756       Call->replaceAllUsesWith(New);
00757       New->takeName(Call);
00758     }
00759 
00760     // Finally, remove the old call from the program, reducing the use-count of
00761     // F.
00762     Call->eraseFromParent();
00763   }
00764 
00765   // Since we have now created the new function, splice the body of the old
00766   // function right into the new function, leaving the old rotting hulk of the
00767   // function empty.
00768   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
00769 
00770   // Loop over the argument list, transferring uses of the old arguments over to
00771   // the new arguments, also transferring over the names as well.
00772   //
00773   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
00774        I2 = NF->arg_begin(); I != E; ++I) {
00775     if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
00776       // If this is an unmodified argument, move the name and users over to the
00777       // new version.
00778       I->replaceAllUsesWith(I2);
00779       I2->takeName(I);
00780       AA.replaceWithNewValue(I, I2);
00781       ++I2;
00782       continue;
00783     }
00784 
00785     if (ByValArgsToTransform.count(I)) {
00786       // In the callee, we create an alloca, and store each of the new incoming
00787       // arguments into the alloca.
00788       Instruction *InsertPt = NF->begin()->begin();
00789 
00790       // Just add all the struct element types.
00791       Type *AgTy = cast<PointerType>(I->getType())->getElementType();
00792       Value *TheAlloca = new AllocaInst(AgTy, 0, "", InsertPt);
00793       StructType *STy = cast<StructType>(AgTy);
00794       Value *Idxs[2] = {
00795             ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), 0 };
00796 
00797       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
00798         Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
00799         Value *Idx = 
00800           GetElementPtrInst::Create(TheAlloca, Idxs,
00801                                     TheAlloca->getName()+"."+Twine(i), 
00802                                     InsertPt);
00803         I2->setName(I->getName()+"."+Twine(i));
00804         new StoreInst(I2++, Idx, InsertPt);
00805       }
00806 
00807       // Anything that used the arg should now use the alloca.
00808       I->replaceAllUsesWith(TheAlloca);
00809       TheAlloca->takeName(I);
00810       AA.replaceWithNewValue(I, TheAlloca);
00811 
00812       // If the alloca is used in a call, we must clear the tail flag since
00813       // the callee now uses an alloca from the caller.
00814       for (User *U : TheAlloca->users()) {
00815         CallInst *Call = dyn_cast<CallInst>(U);
00816         if (!Call)
00817           continue;
00818         Call->setTailCall(false);
00819       }
00820       continue;
00821     }
00822 
00823     if (I->use_empty()) {
00824       AA.deleteValue(I);
00825       continue;
00826     }
00827 
00828     // Otherwise, if we promoted this argument, then all users are load
00829     // instructions (or GEPs with only load users), and all loads should be
00830     // using the new argument that we added.
00831     ScalarizeTable &ArgIndices = ScalarizedElements[I];
00832 
00833     while (!I->use_empty()) {
00834       if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) {
00835         assert(ArgIndices.begin()->empty() &&
00836                "Load element should sort to front!");
00837         I2->setName(I->getName()+".val");
00838         LI->replaceAllUsesWith(I2);
00839         AA.replaceWithNewValue(LI, I2);
00840         LI->eraseFromParent();
00841         DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
00842               << "' in function '" << F->getName() << "'\n");
00843       } else {
00844         GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->user_back());
00845         IndicesVector Operands;
00846         Operands.reserve(GEP->getNumIndices());
00847         for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
00848              II != IE; ++II)
00849           Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
00850 
00851         // GEPs with a single 0 index can be merged with direct loads
00852         if (Operands.size() == 1 && Operands.front() == 0)
00853           Operands.clear();
00854 
00855         Function::arg_iterator TheArg = I2;
00856         for (ScalarizeTable::iterator It = ArgIndices.begin();
00857              *It != Operands; ++It, ++TheArg) {
00858           assert(It != ArgIndices.end() && "GEP not handled??");
00859         }
00860 
00861         std::string NewName = I->getName();
00862         for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
00863             NewName += "." + utostr(Operands[i]);
00864         }
00865         NewName += ".val";
00866         TheArg->setName(NewName);
00867 
00868         DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
00869               << "' of function '" << NF->getName() << "'\n");
00870 
00871         // All of the uses must be load instructions.  Replace them all with
00872         // the argument specified by ArgNo.
00873         while (!GEP->use_empty()) {
00874           LoadInst *L = cast<LoadInst>(GEP->user_back());
00875           L->replaceAllUsesWith(TheArg);
00876           AA.replaceWithNewValue(L, TheArg);
00877           L->eraseFromParent();
00878         }
00879         AA.deleteValue(GEP);
00880         GEP->eraseFromParent();
00881       }
00882     }
00883 
00884     // Increment I2 past all of the arguments added for this promoted pointer.
00885     std::advance(I2, ArgIndices.size());
00886   }
00887 
00888   // Tell the alias analysis that the old function is about to disappear.
00889   AA.replaceWithNewValue(F, NF);
00890 
00891   
00892   NF_CGN->stealCalledFunctionsFrom(CG[F]);
00893   
00894   // Now that the old function is dead, delete it.  If there is a dangling
00895   // reference to the CallgraphNode, just leave the dead function around for
00896   // someone else to nuke.
00897   CallGraphNode *CGN = CG[F];
00898   if (CGN->getNumReferences() == 0)
00899     delete CG.removeFunctionFromModule(CGN);
00900   else
00901     F->setLinkage(Function::ExternalLinkage);
00902   
00903   return NF_CGN;
00904 }