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