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