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