ArgumentPromotion.cpp revision 252723
118334Speter//===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===// 218334Speter// 318334Speter// The LLVM Compiler Infrastructure 418334Speter// 518334Speter// This file is distributed under the University of Illinois Open Source 618334Speter// License. See LICENSE.TXT for details. 718334Speter// 818334Speter//===----------------------------------------------------------------------===// 918334Speter// 1018334Speter// This pass promotes "by reference" arguments to be "by value" arguments. In 1118334Speter// practice, this means looking for internal functions that have pointer 1218334Speter// arguments. If it can prove, through the use of alias analysis, that an 1318334Speter// argument is *only* loaded, then it can pass the value into the function 1418334Speter// instead of the address of the value. This can cause recursive simplification 1518334Speter// of code and lead to the elimination of allocas (especially in C++ template 1618334Speter// code like the STL). 1718334Speter// 1818334Speter// This pass also handles aggregate arguments that are passed into a function, 1918334Speter// scalarizing them if the elements of the aggregate are only loaded. Note that 2018334Speter// by default it refuses to scalarize aggregates which would require passing in 2118334Speter// more than three operands to the function, because passing thousands of 2218334Speter// operands for a large array or structure is unprofitable! This limit can be 2318334Speter// configured or disabled, however. 2418334Speter// 2518334Speter// Note that this transformation could also be done for arguments that are only 2618334Speter// stored to (returning the value instead), but does not currently. This case 2718334Speter// would be best handled when and if LLVM begins supporting multiple return 2818334Speter// values from functions. 2918334Speter// 3018334Speter//===----------------------------------------------------------------------===// 3118334Speter 3218334Speter#define DEBUG_TYPE "argpromotion" 3318334Speter#include "llvm/Transforms/IPO.h" 3418334Speter#include "llvm/ADT/DepthFirstIterator.h" 3518334Speter#include "llvm/ADT/Statistic.h" 3618334Speter#include "llvm/ADT/StringExtras.h" 3718334Speter#include "llvm/Analysis/AliasAnalysis.h" 3818334Speter#include "llvm/Analysis/CallGraph.h" 3918334Speter#include "llvm/Analysis/CallGraphSCCPass.h" 4018334Speter#include "llvm/IR/Constants.h" 4118334Speter#include "llvm/IR/DerivedTypes.h" 4218334Speter#include "llvm/IR/Instructions.h" 4318334Speter#include "llvm/IR/LLVMContext.h" 4418334Speter#include "llvm/IR/Module.h" 4518334Speter#include "llvm/Support/CFG.h" 4618334Speter#include "llvm/Support/CallSite.h" 4718334Speter#include "llvm/Support/Debug.h" 4818334Speter#include "llvm/Support/raw_ostream.h" 4918334Speter#include <set> 5018334Speterusing namespace llvm; 5118334Speter 5218334SpeterSTATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted"); 5318334SpeterSTATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted"); 5418334SpeterSTATISTIC(NumByValArgsPromoted , "Number of byval arguments promoted"); 5518334SpeterSTATISTIC(NumArgumentsDead , "Number of dead pointer args eliminated"); 5618334Speter 5718334Speternamespace { 5818334Speter /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass. 5918334Speter /// 6018334Speter struct ArgPromotion : public CallGraphSCCPass { 6118334Speter virtual void getAnalysisUsage(AnalysisUsage &AU) const { 6218334Speter AU.addRequired<AliasAnalysis>(); 6318334Speter CallGraphSCCPass::getAnalysisUsage(AU); 6418334Speter } 6518334Speter 6618334Speter virtual bool runOnSCC(CallGraphSCC &SCC); 6718334Speter static char ID; // Pass identification, replacement for typeid 6818334Speter explicit ArgPromotion(unsigned maxElements = 3) 6918334Speter : CallGraphSCCPass(ID), maxElements(maxElements) { 7018334Speter initializeArgPromotionPass(*PassRegistry::getPassRegistry()); 7118334Speter } 7218334Speter 7318334Speter /// A vector used to hold the indices of a single GEP instruction 7418334Speter typedef std::vector<uint64_t> IndicesVector; 7518334Speter 7618334Speter private: 7718334Speter CallGraphNode *PromoteArguments(CallGraphNode *CGN); 7818334Speter bool isSafeToPromoteArgument(Argument *Arg, bool isByVal) const; 7918334Speter CallGraphNode *DoPromotion(Function *F, 8018334Speter SmallPtrSet<Argument*, 8> &ArgsToPromote, 8118334Speter SmallPtrSet<Argument*, 8> &ByValArgsToTransform); 8218334Speter /// The maximum number of elements to expand, or 0 for unlimited. 8318334Speter unsigned maxElements; 8418334Speter }; 8518334Speter} 8618334Speter 8718334Speterchar ArgPromotion::ID = 0; 8818334SpeterINITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion", 8918334Speter "Promote 'by reference' arguments to scalars", false, false) 9018334SpeterINITIALIZE_AG_DEPENDENCY(AliasAnalysis) 9118334SpeterINITIALIZE_AG_DEPENDENCY(CallGraph) 9218334SpeterINITIALIZE_PASS_END(ArgPromotion, "argpromotion", 9318334Speter "Promote 'by reference' arguments to scalars", false, false) 9418334Speter 9518334SpeterPass *llvm::createArgumentPromotionPass(unsigned maxElements) { 9618334Speter return new ArgPromotion(maxElements); 9718334Speter} 9818334Speter 9918334Speterbool ArgPromotion::runOnSCC(CallGraphSCC &SCC) { 10018334Speter bool Changed = false, LocalChange; 10118334Speter 10218334Speter do { // Iterate until we stop promoting from this SCC. 10318334Speter LocalChange = false; 10418334Speter // Attempt to promote arguments from all functions in this SCC. 10518334Speter for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) { 10618334Speter if (CallGraphNode *CGN = PromoteArguments(*I)) { 10718334Speter LocalChange = true; 10818334Speter SCC.ReplaceNode(*I, CGN); 10918334Speter } 11018334Speter } 11118334Speter Changed |= LocalChange; // Remember that we changed something. 11218334Speter } while (LocalChange); 11318334Speter 11418334Speter return Changed; 11518334Speter} 11618334Speter 11718334Speter/// PromoteArguments - This method checks the specified function to see if there 11818334Speter/// are any promotable arguments and if it is safe to promote the function (for 11918334Speter/// example, all callers are direct). If safe to promote some arguments, it 12018334Speter/// calls the DoPromotion method. 12118334Speter/// 12218334SpeterCallGraphNode *ArgPromotion::PromoteArguments(CallGraphNode *CGN) { 12318334Speter Function *F = CGN->getFunction(); 12418334Speter 12518334Speter // Make sure that it is local to this module. 12618334Speter if (!F || !F->hasLocalLinkage()) return 0; 12718334Speter 12818334Speter // First check: see if there are any pointer arguments! If not, quick exit. 12918334Speter SmallVector<std::pair<Argument*, unsigned>, 16> PointerArgs; 13018334Speter unsigned ArgNo = 0; 13118334Speter for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); 13218334Speter I != E; ++I, ++ArgNo) 13318334Speter if (I->getType()->isPointerTy()) 13418334Speter PointerArgs.push_back(std::pair<Argument*, unsigned>(I, ArgNo)); 13518334Speter if (PointerArgs.empty()) return 0; 13618334Speter 13718334Speter // Second check: make sure that all callers are direct callers. We can't 13818334Speter // transform functions that have indirect callers. Also see if the function 13918334Speter // is self-recursive. 14018334Speter bool isSelfRecursive = false; 14118334Speter for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); 14218334Speter UI != E; ++UI) { 14318334Speter CallSite CS(*UI); 14418334Speter // Must be a direct call. 14518334Speter if (CS.getInstruction() == 0 || !CS.isCallee(UI)) return 0; 14618334Speter 14718334Speter if (CS.getInstruction()->getParent()->getParent() == F) 14818334Speter isSelfRecursive = true; 14918334Speter } 15018334Speter 15118334Speter // Check to see which arguments are promotable. If an argument is promotable, 15218334Speter // add it to ArgsToPromote. 15318334Speter SmallPtrSet<Argument*, 8> ArgsToPromote; 15418334Speter SmallPtrSet<Argument*, 8> ByValArgsToTransform; 15518334Speter for (unsigned i = 0; i != PointerArgs.size(); ++i) { 15618334Speter bool isByVal=F->getAttributes(). 15718334Speter hasAttribute(PointerArgs[i].second+1, Attribute::ByVal); 15818334Speter Argument *PtrArg = PointerArgs[i].first; 15918334Speter Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType(); 16018334Speter 16118334Speter // If this is a byval argument, and if the aggregate type is small, just 16218334Speter // pass the elements, which is always safe. 16318334Speter if (isByVal) { 16418334Speter if (StructType *STy = dyn_cast<StructType>(AgTy)) { 16518334Speter if (maxElements > 0 && STy->getNumElements() > maxElements) { 16618334Speter DEBUG(dbgs() << "argpromotion disable promoting argument '" 16718334Speter << PtrArg->getName() << "' because it would require adding more" 16818334Speter << " than " << maxElements << " arguments to the function.\n"); 16918334Speter continue; 17018334Speter } 17118334Speter 17218334Speter // If all the elements are single-value types, we can promote it. 17318334Speter bool AllSimple = true; 17418334Speter for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 17518334Speter if (!STy->getElementType(i)->isSingleValueType()) { 17618334Speter AllSimple = false; 17718334Speter break; 17818334Speter } 17918334Speter } 18018334Speter 18118334Speter // Safe to transform, don't even bother trying to "promote" it. 18218334Speter // Passing the elements as a scalar will allow scalarrepl to hack on 18318334Speter // the new alloca we introduce. 18418334Speter if (AllSimple) { 18518334Speter ByValArgsToTransform.insert(PtrArg); 18618334Speter continue; 18718334Speter } 18818334Speter } 18918334Speter } 19018334Speter 19118334Speter // If the argument is a recursive type and we're in a recursive 19218334Speter // function, we could end up infinitely peeling the function argument. 19318334Speter if (isSelfRecursive) { 19418334Speter if (StructType *STy = dyn_cast<StructType>(AgTy)) { 19518334Speter bool RecursiveType = false; 19618334Speter for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 19718334Speter if (STy->getElementType(i) == PtrArg->getType()) { 19818334Speter RecursiveType = true; 19918334Speter break; 20018334Speter } 20118334Speter } 20218334Speter if (RecursiveType) 20318334Speter continue; 20418334Speter } 20518334Speter } 20618334Speter 20718334Speter // Otherwise, see if we can promote the pointer to its value. 20818334Speter if (isSafeToPromoteArgument(PtrArg, isByVal)) 20918334Speter ArgsToPromote.insert(PtrArg); 21018334Speter } 21118334Speter 21218334Speter // No promotable pointer arguments. 21318334Speter if (ArgsToPromote.empty() && ByValArgsToTransform.empty()) 21418334Speter return 0; 21518334Speter 21618334Speter return DoPromotion(F, ArgsToPromote, ByValArgsToTransform); 21718334Speter} 21818334Speter 21918334Speter/// AllCallersPassInValidPointerForArgument - Return true if we can prove that 22018334Speter/// all callees pass in a valid pointer for the specified function argument. 22118334Speterstatic bool AllCallersPassInValidPointerForArgument(Argument *Arg) { 22218334Speter Function *Callee = Arg->getParent(); 22318334Speter 22418334Speter unsigned ArgNo = std::distance(Callee->arg_begin(), 22518334Speter Function::arg_iterator(Arg)); 22618334Speter 22718334Speter // Look at all call sites of the function. At this pointer we know we only 22818334Speter // have direct callees. 22918334Speter for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end(); 23018334Speter UI != E; ++UI) { 23118334Speter CallSite CS(*UI); 23218334Speter assert(CS && "Should only have direct calls!"); 23318334Speter 23418334Speter if (!CS.getArgument(ArgNo)->isDereferenceablePointer()) 23518334Speter return false; 23618334Speter } 23718334Speter return true; 23818334Speter} 23918334Speter 24018334Speter/// Returns true if Prefix is a prefix of longer. That means, Longer has a size 24118334Speter/// that is greater than or equal to the size of prefix, and each of the 24218334Speter/// elements in Prefix is the same as the corresponding elements in Longer. 24318334Speter/// 24418334Speter/// This means it also returns true when Prefix and Longer are equal! 24518334Speterstatic bool IsPrefix(const ArgPromotion::IndicesVector &Prefix, 24618334Speter const ArgPromotion::IndicesVector &Longer) { 24718334Speter if (Prefix.size() > Longer.size()) 24818334Speter return false; 24918334Speter return std::equal(Prefix.begin(), Prefix.end(), Longer.begin()); 25018334Speter} 25118334Speter 25218334Speter 25318334Speter/// Checks if Indices, or a prefix of Indices, is in Set. 25418334Speterstatic bool PrefixIn(const ArgPromotion::IndicesVector &Indices, 25518334Speter std::set<ArgPromotion::IndicesVector> &Set) { 25618334Speter std::set<ArgPromotion::IndicesVector>::iterator Low; 25718334Speter Low = Set.upper_bound(Indices); 25818334Speter if (Low != Set.begin()) 25918334Speter Low--; 26018334Speter // Low is now the last element smaller than or equal to Indices. This means 26118334Speter // it points to a prefix of Indices (possibly Indices itself), if such 26218334Speter // prefix exists. 26318334Speter // 26418334Speter // This load is safe if any prefix of its operands is safe to load. 26518334Speter return Low != Set.end() && IsPrefix(*Low, Indices); 26618334Speter} 26718334Speter 26818334Speter/// Mark the given indices (ToMark) as safe in the given set of indices 26918334Speter/// (Safe). Marking safe usually means adding ToMark to Safe. However, if there 27018334Speter/// is already a prefix of Indices in Safe, Indices are implicitely marked safe 27118334Speter/// already. Furthermore, any indices that Indices is itself a prefix of, are 27218334Speter/// removed from Safe (since they are implicitely safe because of Indices now). 27318334Speterstatic void MarkIndicesSafe(const ArgPromotion::IndicesVector &ToMark, 27418334Speter std::set<ArgPromotion::IndicesVector> &Safe) { 27518334Speter std::set<ArgPromotion::IndicesVector>::iterator Low; 27618334Speter Low = Safe.upper_bound(ToMark); 27718334Speter // Guard against the case where Safe is empty 27818334Speter if (Low != Safe.begin()) 27918334Speter Low--; 28018334Speter // Low is now the last element smaller than or equal to Indices. This 28118334Speter // means it points to a prefix of Indices (possibly Indices itself), if 28218334Speter // such prefix exists. 28318334Speter if (Low != Safe.end()) { 28418334Speter if (IsPrefix(*Low, ToMark)) 28518334Speter // If there is already a prefix of these indices (or exactly these 28618334Speter // indices) marked a safe, don't bother adding these indices 28718334Speter return; 28818334Speter 28918334Speter // Increment Low, so we can use it as a "insert before" hint 29018334Speter ++Low; 29118334Speter } 29218334Speter // Insert 29318334Speter Low = Safe.insert(Low, ToMark); 29418334Speter ++Low; 29518334Speter // If there we're a prefix of longer index list(s), remove those 29618334Speter std::set<ArgPromotion::IndicesVector>::iterator End = Safe.end(); 29718334Speter while (Low != End && IsPrefix(ToMark, *Low)) { 29818334Speter std::set<ArgPromotion::IndicesVector>::iterator Remove = Low; 29918334Speter ++Low; 30018334Speter Safe.erase(Remove); 30118334Speter } 30218334Speter} 30318334Speter 30418334Speter/// isSafeToPromoteArgument - As you might guess from the name of this method, 30518334Speter/// it checks to see if it is both safe and useful to promote the argument. 30618334Speter/// This method limits promotion of aggregates to only promote up to three 30718334Speter/// elements of the aggregate in order to avoid exploding the number of 30818334Speter/// arguments passed in. 30918334Speterbool ArgPromotion::isSafeToPromoteArgument(Argument *Arg, bool isByVal) const { 31018334Speter typedef std::set<IndicesVector> GEPIndicesSet; 31118334Speter 31218334Speter // Quick exit for unused arguments 31318334Speter if (Arg->use_empty()) 31418334Speter return true; 31518334Speter 31618334Speter // We can only promote this argument if all of the uses are loads, or are GEP 31718334Speter // instructions (with constant indices) that are subsequently loaded. 31818334Speter // 31918334Speter // Promoting the argument causes it to be loaded in the caller 32018334Speter // unconditionally. This is only safe if we can prove that either the load 32118334Speter // would have happened in the callee anyway (ie, there is a load in the entry 32218334Speter // block) or the pointer passed in at every call site is guaranteed to be 32318334Speter // valid. 32418334Speter // In the former case, invalid loads can happen, but would have happened 32518334Speter // anyway, in the latter case, invalid loads won't happen. This prevents us 32618334Speter // from introducing an invalid load that wouldn't have happened in the 32718334Speter // original code. 32818334Speter // 32918334Speter // This set will contain all sets of indices that are loaded in the entry 33018334Speter // block, and thus are safe to unconditionally load in the caller. 33118334Speter GEPIndicesSet SafeToUnconditionallyLoad; 33218334Speter 33318334Speter // This set contains all the sets of indices that we are planning to promote. 33418334Speter // This makes it possible to limit the number of arguments added. 33518334Speter GEPIndicesSet ToPromote; 33618334Speter 33718334Speter // If the pointer is always valid, any load with first index 0 is valid. 33818334Speter if (isByVal || AllCallersPassInValidPointerForArgument(Arg)) 33918334Speter SafeToUnconditionallyLoad.insert(IndicesVector(1, 0)); 34018334Speter 34118334Speter // First, iterate the entry block and mark loads of (geps of) arguments as 34218334Speter // safe. 34318334Speter BasicBlock *EntryBlock = Arg->getParent()->begin(); 34418334Speter // Declare this here so we can reuse it 34518334Speter IndicesVector Indices; 34618334Speter for (BasicBlock::iterator I = EntryBlock->begin(), E = EntryBlock->end(); 34718334Speter I != E; ++I) 34818334Speter if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 34918334Speter Value *V = LI->getPointerOperand(); 35018334Speter if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) { 35118334Speter V = GEP->getPointerOperand(); 35218334Speter if (V == Arg) { 35318334Speter // This load actually loads (part of) Arg? Check the indices then. 35418334Speter Indices.reserve(GEP->getNumIndices()); 35518334Speter for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end(); 35618334Speter II != IE; ++II) 35718334Speter if (ConstantInt *CI = dyn_cast<ConstantInt>(*II)) 35818334Speter Indices.push_back(CI->getSExtValue()); 35918334Speter else 36018334Speter // We found a non-constant GEP index for this argument? Bail out 36118334Speter // right away, can't promote this argument at all. 36218334Speter return false; 36318334Speter 36418334Speter // Indices checked out, mark them as safe 36518334Speter MarkIndicesSafe(Indices, SafeToUnconditionallyLoad); 36618334Speter Indices.clear(); 36718334Speter } 36818334Speter } else if (V == Arg) { 36918334Speter // Direct loads are equivalent to a GEP with a single 0 index. 37018334Speter MarkIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad); 37118334Speter } 37218334Speter } 37318334Speter 37418334Speter // Now, iterate all uses of the argument to see if there are any uses that are 37518334Speter // not (GEP+)loads, or any (GEP+)loads that are not safe to promote. 37618334Speter SmallVector<LoadInst*, 16> Loads; 37718334Speter IndicesVector Operands; 37818334Speter for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end(); 37918334Speter UI != E; ++UI) { 38018334Speter User *U = *UI; 38118334Speter Operands.clear(); 38218334Speter if (LoadInst *LI = dyn_cast<LoadInst>(U)) { 38318334Speter // Don't hack volatile/atomic loads 38418334Speter if (!LI->isSimple()) return false; 38518334Speter Loads.push_back(LI); 38618334Speter // Direct loads are equivalent to a GEP with a zero index and then a load. 38718334Speter Operands.push_back(0); 38818334Speter } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) { 38918334Speter if (GEP->use_empty()) { 39018334Speter // Dead GEP's cause trouble later. Just remove them if we run into 39118334Speter // them. 39218334Speter getAnalysis<AliasAnalysis>().deleteValue(GEP); 39318334Speter GEP->eraseFromParent(); 39418334Speter // TODO: This runs the above loop over and over again for dead GEPs 39518334Speter // Couldn't we just do increment the UI iterator earlier and erase the 39618334Speter // use? 39718334Speter return isSafeToPromoteArgument(Arg, isByVal); 39818334Speter } 39918334Speter 40018334Speter // Ensure that all of the indices are constants. 40118334Speter for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end(); 40218334Speter i != e; ++i) 40318334Speter if (ConstantInt *C = dyn_cast<ConstantInt>(*i)) 40418334Speter Operands.push_back(C->getSExtValue()); 40518334Speter else 40618334Speter return false; // Not a constant operand GEP! 40718334Speter 40818334Speter // Ensure that the only users of the GEP are load instructions. 40918334Speter for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end(); 41018334Speter UI != E; ++UI) 41118334Speter if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) { 41218334Speter // Don't hack volatile/atomic loads 41318334Speter if (!LI->isSimple()) return false; 41418334Speter Loads.push_back(LI); 41518334Speter } else { 41618334Speter // Other uses than load? 41718334Speter return false; 41818334Speter } 41918334Speter } else { 42018334Speter return false; // Not a load or a GEP. 42118334Speter } 42218334Speter 42318334Speter // Now, see if it is safe to promote this load / loads of this GEP. Loading 42418334Speter // is safe if Operands, or a prefix of Operands, is marked as safe. 42518334Speter if (!PrefixIn(Operands, SafeToUnconditionallyLoad)) 42618334Speter return false; 42718334Speter 42818334Speter // See if we are already promoting a load with these indices. If not, check 42918334Speter // to make sure that we aren't promoting too many elements. If so, nothing 43018334Speter // to do. 43118334Speter if (ToPromote.find(Operands) == ToPromote.end()) { 43218334Speter if (maxElements > 0 && ToPromote.size() == maxElements) { 43318334Speter DEBUG(dbgs() << "argpromotion not promoting argument '" 43418334Speter << Arg->getName() << "' because it would require adding more " 43518334Speter << "than " << maxElements << " arguments to the function.\n"); 43618334Speter // We limit aggregate promotion to only promoting up to a fixed number 43718334Speter // of elements of the aggregate. 43818334Speter return false; 43918334Speter } 44018334Speter ToPromote.insert(Operands); 44118334Speter } 44218334Speter } 44318334Speter 44418334Speter if (Loads.empty()) return true; // No users, this is a dead argument. 44518334Speter 44618334Speter // Okay, now we know that the argument is only used by load instructions and 44718334Speter // it is safe to unconditionally perform all of them. Use alias analysis to 44818334Speter // check to see if the pointer is guaranteed to not be modified from entry of 44918334Speter // the function to each of the load instructions. 45018334Speter 45118334Speter // Because there could be several/many load instructions, remember which 45218334Speter // blocks we know to be transparent to the load. 45318334Speter SmallPtrSet<BasicBlock*, 16> TranspBlocks; 45418334Speter 45518334Speter AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); 45618334Speter 45718334Speter for (unsigned i = 0, e = Loads.size(); i != e; ++i) { 45818334Speter // Check to see if the load is invalidated from the start of the block to 45918334Speter // the load itself. 46018334Speter LoadInst *Load = Loads[i]; 46118334Speter BasicBlock *BB = Load->getParent(); 46218334Speter 46318334Speter AliasAnalysis::Location Loc = AA.getLocation(Load); 46418334Speter if (AA.canInstructionRangeModify(BB->front(), *Load, Loc)) 46518334Speter return false; // Pointer is invalidated! 46618334Speter 46718334Speter // Now check every path from the entry block to the load for transparency. 46818334Speter // To do this, we perform a depth first search on the inverse CFG from the 46918334Speter // loading block. 47018334Speter for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 47118334Speter BasicBlock *P = *PI; 47218334Speter for (idf_ext_iterator<BasicBlock*, SmallPtrSet<BasicBlock*, 16> > 47318334Speter I = idf_ext_begin(P, TranspBlocks), 47418334Speter E = idf_ext_end(P, TranspBlocks); I != E; ++I) 47518334Speter if (AA.canBasicBlockModify(**I, Loc)) 47618334Speter return false; 47718334Speter } 47818334Speter } 47918334Speter 48018334Speter // If the path from the entry of the function to each load is free of 48118334Speter // instructions that potentially invalidate the load, we can make the 48218334Speter // transformation! 48318334Speter return true; 48418334Speter} 48518334Speter 48618334Speter/// DoPromotion - This method actually performs the promotion of the specified 48718334Speter/// arguments, and returns the new function. At this point, we know that it's 48818334Speter/// safe to do so. 48918334SpeterCallGraphNode *ArgPromotion::DoPromotion(Function *F, 49018334Speter SmallPtrSet<Argument*, 8> &ArgsToPromote, 49118334Speter SmallPtrSet<Argument*, 8> &ByValArgsToTransform) { 49218334Speter 49318334Speter // Start by computing a new prototype for the function, which is the same as 49418334Speter // the old function, but has modified arguments. 49518334Speter FunctionType *FTy = F->getFunctionType(); 49618334Speter std::vector<Type*> Params; 49718334Speter 49818334Speter typedef std::set<IndicesVector> ScalarizeTable; 49918334Speter 50018334Speter // ScalarizedElements - If we are promoting a pointer that has elements 50118334Speter // accessed out of it, keep track of which elements are accessed so that we 50218334Speter // can add one argument for each. 50318334Speter // 50418334Speter // Arguments that are directly loaded will have a zero element value here, to 50518334Speter // handle cases where there are both a direct load and GEP accesses. 50618334Speter // 50718334Speter std::map<Argument*, ScalarizeTable> ScalarizedElements; 50818334Speter 50918334Speter // OriginalLoads - Keep track of a representative load instruction from the 51018334Speter // original function so that we can tell the alias analysis implementation 51118334Speter // what the new GEP/Load instructions we are inserting look like. 51218334Speter std::map<IndicesVector, LoadInst*> OriginalLoads; 51318334Speter 51418334Speter // Attribute - Keep track of the parameter attributes for the arguments 51518334Speter // that we are *not* promoting. For the ones that we do promote, the parameter 51618334Speter // attributes are lost 51718334Speter SmallVector<AttributeSet, 8> AttributesVec; 51818334Speter const AttributeSet &PAL = F->getAttributes(); 51918334Speter 52018334Speter // Add any return attributes. 52118334Speter if (PAL.hasAttributes(AttributeSet::ReturnIndex)) 52218334Speter AttributesVec.push_back(AttributeSet::get(F->getContext(), 52318334Speter PAL.getRetAttributes())); 52418334Speter 52518334Speter // First, determine the new argument list 52618334Speter unsigned ArgIndex = 1; 52718334Speter for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; 52818334Speter ++I, ++ArgIndex) { 52918334Speter if (ByValArgsToTransform.count(I)) { 53018334Speter // Simple byval argument? Just add all the struct element types. 53118334Speter Type *AgTy = cast<PointerType>(I->getType())->getElementType(); 53218334Speter StructType *STy = cast<StructType>(AgTy); 53318334Speter for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 53418334Speter Params.push_back(STy->getElementType(i)); 53518334Speter ++NumByValArgsPromoted; 53618334Speter } else if (!ArgsToPromote.count(I)) { 53718334Speter // Unchanged argument 53818334Speter Params.push_back(I->getType()); 53918334Speter AttributeSet attrs = PAL.getParamAttributes(ArgIndex); 54018334Speter if (attrs.hasAttributes(ArgIndex)) { 54118334Speter AttrBuilder B(attrs, ArgIndex); 54218334Speter AttributesVec. 54318334Speter push_back(AttributeSet::get(F->getContext(), Params.size(), B)); 54418334Speter } 54518334Speter } else if (I->use_empty()) { 54618334Speter // Dead argument (which are always marked as promotable) 54718334Speter ++NumArgumentsDead; 54818334Speter } else { 54918334Speter // Okay, this is being promoted. This means that the only uses are loads 55018334Speter // or GEPs which are only used by loads 55118334Speter 55218334Speter // In this table, we will track which indices are loaded from the argument 55318334Speter // (where direct loads are tracked as no indices). 55418334Speter ScalarizeTable &ArgIndices = ScalarizedElements[I]; 55518334Speter for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; 55618334Speter ++UI) { 55718334Speter Instruction *User = cast<Instruction>(*UI); 55818334Speter assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User)); 55918334Speter IndicesVector Indices; 56018334Speter Indices.reserve(User->getNumOperands() - 1); 56118334Speter // Since loads will only have a single operand, and GEPs only a single 56218334Speter // non-index operand, this will record direct loads without any indices, 56318334Speter // and gep+loads with the GEP indices. 56418334Speter for (User::op_iterator II = User->op_begin() + 1, IE = User->op_end(); 56518334Speter II != IE; ++II) 56618334Speter Indices.push_back(cast<ConstantInt>(*II)->getSExtValue()); 56718334Speter // GEPs with a single 0 index can be merged with direct loads 56818334Speter if (Indices.size() == 1 && Indices.front() == 0) 56918334Speter Indices.clear(); 57018334Speter ArgIndices.insert(Indices); 57118334Speter LoadInst *OrigLoad; 57218334Speter if (LoadInst *L = dyn_cast<LoadInst>(User)) 57318334Speter OrigLoad = L; 57418334Speter else 57518334Speter // Take any load, we will use it only to update Alias Analysis 57618334Speter OrigLoad = cast<LoadInst>(User->use_back()); 57718334Speter OriginalLoads[Indices] = OrigLoad; 57818334Speter } 57918334Speter 58018334Speter // Add a parameter to the function for each element passed in. 58118334Speter for (ScalarizeTable::iterator SI = ArgIndices.begin(), 58218334Speter E = ArgIndices.end(); SI != E; ++SI) { 58318334Speter // not allowed to dereference ->begin() if size() is 0 58418334Speter Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI)); 58518334Speter assert(Params.back()); 58618334Speter } 58718334Speter 58818334Speter if (ArgIndices.size() == 1 && ArgIndices.begin()->empty()) 58918334Speter ++NumArgumentsPromoted; 59018334Speter else 59118334Speter ++NumAggregatesPromoted; 59218334Speter } 59318334Speter } 59418334Speter 59518334Speter // Add any function attributes. 59618334Speter if (PAL.hasAttributes(AttributeSet::FunctionIndex)) 59718334Speter AttributesVec.push_back(AttributeSet::get(FTy->getContext(), 59818334Speter PAL.getFnAttributes())); 59918334Speter 60018334Speter Type *RetTy = FTy->getReturnType(); 60118334Speter 60218334Speter // Construct the new function type using the new arguments. 60318334Speter FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg()); 60418334Speter 60518334Speter // Create the new function body and insert it into the module. 60618334Speter Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName()); 60718334Speter NF->copyAttributesFrom(F); 60818334Speter 60918334Speter 61018334Speter DEBUG(dbgs() << "ARG PROMOTION: Promoting to:" << *NF << "\n" 61118334Speter << "From: " << *F); 61218334Speter 61318334Speter // Recompute the parameter attributes list based on the new arguments for 61418334Speter // the function. 61518334Speter NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec)); 61618334Speter AttributesVec.clear(); 61718334Speter 61818334Speter F->getParent()->getFunctionList().insert(F, NF); 61918334Speter NF->takeName(F); 62018334Speter 62118334Speter // Get the alias analysis information that we need to update to reflect our 62218334Speter // changes. 62318334Speter AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); 62418334Speter 62518334Speter // Get the callgraph information that we need to update to reflect our 62618334Speter // changes. 62718334Speter CallGraph &CG = getAnalysis<CallGraph>(); 62818334Speter 62918334Speter // Get a new callgraph node for NF. 63018334Speter CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF); 63118334Speter 63218334Speter // Loop over all of the callers of the function, transforming the call sites 63318334Speter // to pass in the loaded pointers. 63418334Speter // 63518334Speter SmallVector<Value*, 16> Args; 63618334Speter while (!F->use_empty()) { 63718334Speter CallSite CS(F->use_back()); 63818334Speter assert(CS.getCalledFunction() == F); 63918334Speter Instruction *Call = CS.getInstruction(); 64018334Speter const AttributeSet &CallPAL = CS.getAttributes(); 64118334Speter 64218334Speter // Add any return attributes. 64318334Speter if (CallPAL.hasAttributes(AttributeSet::ReturnIndex)) 64418334Speter AttributesVec.push_back(AttributeSet::get(F->getContext(), 64518334Speter CallPAL.getRetAttributes())); 64618334Speter 64718334Speter // Loop over the operands, inserting GEP and loads in the caller as 64818334Speter // appropriate. 64918334Speter CallSite::arg_iterator AI = CS.arg_begin(); 65018334Speter ArgIndex = 1; 65118334Speter for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); 65218334Speter I != E; ++I, ++AI, ++ArgIndex) 65318334Speter if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) { 65418334Speter Args.push_back(*AI); // Unmodified argument 65518334Speter 65618334Speter if (CallPAL.hasAttributes(ArgIndex)) { 65718334Speter AttrBuilder B(CallPAL, ArgIndex); 65818334Speter AttributesVec. 65918334Speter push_back(AttributeSet::get(F->getContext(), Args.size(), B)); 66018334Speter } 66118334Speter } else if (ByValArgsToTransform.count(I)) { 66218334Speter // Emit a GEP and load for each element of the struct. 66318334Speter Type *AgTy = cast<PointerType>(I->getType())->getElementType(); 66418334Speter StructType *STy = cast<StructType>(AgTy); 66518334Speter Value *Idxs[2] = { 66618334Speter ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), 0 }; 66718334Speter for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 66818334Speter Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i); 66918334Speter Value *Idx = GetElementPtrInst::Create(*AI, Idxs, 67018334Speter (*AI)->getName()+"."+utostr(i), 67118334Speter Call); 67218334Speter // TODO: Tell AA about the new values? 67318334Speter Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call)); 67418334Speter } 67518334Speter } else if (!I->use_empty()) { 67618334Speter // Non-dead argument: insert GEPs and loads as appropriate. 67718334Speter ScalarizeTable &ArgIndices = ScalarizedElements[I]; 67818334Speter // Store the Value* version of the indices in here, but declare it now 67918334Speter // for reuse. 68018334Speter std::vector<Value*> Ops; 68118334Speter for (ScalarizeTable::iterator SI = ArgIndices.begin(), 68218334Speter E = ArgIndices.end(); SI != E; ++SI) { 68318334Speter Value *V = *AI; 68418334Speter LoadInst *OrigLoad = OriginalLoads[*SI]; 68518334Speter if (!SI->empty()) { 68618334Speter Ops.reserve(SI->size()); 68718334Speter Type *ElTy = V->getType(); 68818334Speter for (IndicesVector::const_iterator II = SI->begin(), 68918334Speter IE = SI->end(); II != IE; ++II) { 69018334Speter // Use i32 to index structs, and i64 for others (pointers/arrays). 69118334Speter // This satisfies GEP constraints. 69218334Speter Type *IdxTy = (ElTy->isStructTy() ? 69318334Speter Type::getInt32Ty(F->getContext()) : 69418334Speter Type::getInt64Ty(F->getContext())); 69518334Speter Ops.push_back(ConstantInt::get(IdxTy, *II)); 69618334Speter // Keep track of the type we're currently indexing. 69718334Speter ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(*II); 69818334Speter } 69918334Speter // And create a GEP to extract those indices. 70018334Speter V = GetElementPtrInst::Create(V, Ops, V->getName()+".idx", Call); 70118334Speter Ops.clear(); 70218334Speter AA.copyValue(OrigLoad->getOperand(0), V); 70318334Speter } 70418334Speter // Since we're replacing a load make sure we take the alignment 70518334Speter // of the previous load. 70618334Speter LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call); 70718334Speter newLoad->setAlignment(OrigLoad->getAlignment()); 70818334Speter // Transfer the TBAA info too. 70918334Speter newLoad->setMetadata(LLVMContext::MD_tbaa, 71018334Speter OrigLoad->getMetadata(LLVMContext::MD_tbaa)); 71118334Speter Args.push_back(newLoad); 71218334Speter AA.copyValue(OrigLoad, Args.back()); 71318334Speter } 71418334Speter } 71518334Speter 71618334Speter // Push any varargs arguments on the list. 71718334Speter for (; AI != CS.arg_end(); ++AI, ++ArgIndex) { 71818334Speter Args.push_back(*AI); 71918334Speter if (CallPAL.hasAttributes(ArgIndex)) { 72018334Speter AttrBuilder B(CallPAL, ArgIndex); 72118334Speter AttributesVec. 72218334Speter push_back(AttributeSet::get(F->getContext(), Args.size(), B)); 72318334Speter } 72418334Speter } 72518334Speter 72618334Speter // Add any function attributes. 72718334Speter if (CallPAL.hasAttributes(AttributeSet::FunctionIndex)) 72818334Speter AttributesVec.push_back(AttributeSet::get(Call->getContext(), 72918334Speter CallPAL.getFnAttributes())); 73018334Speter 73118334Speter Instruction *New; 73218334Speter if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 73318334Speter New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(), 73418334Speter Args, "", Call); 73518334Speter cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv()); 73618334Speter cast<InvokeInst>(New)->setAttributes(AttributeSet::get(II->getContext(), 73718334Speter AttributesVec)); 73818334Speter } else { 73918334Speter New = CallInst::Create(NF, Args, "", Call); 74018334Speter cast<CallInst>(New)->setCallingConv(CS.getCallingConv()); 74118334Speter cast<CallInst>(New)->setAttributes(AttributeSet::get(New->getContext(), 74218334Speter AttributesVec)); 74318334Speter if (cast<CallInst>(Call)->isTailCall()) 74418334Speter cast<CallInst>(New)->setTailCall(); 74518334Speter } 74618334Speter Args.clear(); 74718334Speter AttributesVec.clear(); 74818334Speter 74918334Speter // Update the alias analysis implementation to know that we are replacing 75018334Speter // the old call with a new one. 75118334Speter AA.replaceWithNewValue(Call, New); 75218334Speter 75318334Speter // Update the callgraph to know that the callsite has been transformed. 75418334Speter CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()]; 75518334Speter CalleeNode->replaceCallEdge(Call, New, NF_CGN); 75618334Speter 75718334Speter if (!Call->use_empty()) { 75818334Speter Call->replaceAllUsesWith(New); 75918334Speter New->takeName(Call); 76018334Speter } 76118334Speter 76218334Speter // Finally, remove the old call from the program, reducing the use-count of 76318334Speter // F. 76418334Speter Call->eraseFromParent(); 76518334Speter } 76618334Speter 76718334Speter // Since we have now created the new function, splice the body of the old 76818334Speter // function right into the new function, leaving the old rotting hulk of the 76918334Speter // function empty. 77018334Speter NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList()); 77118334Speter 77218334Speter // Loop over the argument list, transferring uses of the old arguments over to 77318334Speter // the new arguments, also transferring over the names as well. 77418334Speter // 77518334Speter for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(), 77618334Speter I2 = NF->arg_begin(); I != E; ++I) { 77718334Speter if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) { 77818334Speter // If this is an unmodified argument, move the name and users over to the 77918334Speter // new version. 78018334Speter I->replaceAllUsesWith(I2); 78118334Speter I2->takeName(I); 78218334Speter AA.replaceWithNewValue(I, I2); 78318334Speter ++I2; 78418334Speter continue; 78518334Speter } 78618334Speter 78718334Speter if (ByValArgsToTransform.count(I)) { 78818334Speter // In the callee, we create an alloca, and store each of the new incoming 78918334Speter // arguments into the alloca. 79018334Speter Instruction *InsertPt = NF->begin()->begin(); 79118334Speter 79218334Speter // Just add all the struct element types. 79318334Speter Type *AgTy = cast<PointerType>(I->getType())->getElementType(); 79418334Speter Value *TheAlloca = new AllocaInst(AgTy, 0, "", InsertPt); 79518334Speter StructType *STy = cast<StructType>(AgTy); 79618334Speter Value *Idxs[2] = { 79718334Speter ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), 0 }; 79818334Speter 79918334Speter for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 80018334Speter Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i); 80118334Speter Value *Idx = 80218334Speter GetElementPtrInst::Create(TheAlloca, Idxs, 80318334Speter TheAlloca->getName()+"."+Twine(i), 80418334Speter InsertPt); 80518334Speter I2->setName(I->getName()+"."+Twine(i)); 80618334Speter new StoreInst(I2++, Idx, InsertPt); 80718334Speter } 80818334Speter 80918334Speter // Anything that used the arg should now use the alloca. 81018334Speter I->replaceAllUsesWith(TheAlloca); 81118334Speter TheAlloca->takeName(I); 81218334Speter AA.replaceWithNewValue(I, TheAlloca); 81318334Speter continue; 81418334Speter } 81518334Speter 81618334Speter if (I->use_empty()) { 81718334Speter AA.deleteValue(I); 81818334Speter continue; 81918334Speter } 82018334Speter 82118334Speter // Otherwise, if we promoted this argument, then all users are load 82218334Speter // instructions (or GEPs with only load users), and all loads should be 82318334Speter // using the new argument that we added. 82418334Speter ScalarizeTable &ArgIndices = ScalarizedElements[I]; 82518334Speter 82618334Speter while (!I->use_empty()) { 82718334Speter if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) { 82818334Speter assert(ArgIndices.begin()->empty() && 82918334Speter "Load element should sort to front!"); 83018334Speter I2->setName(I->getName()+".val"); 83118334Speter LI->replaceAllUsesWith(I2); 83218334Speter AA.replaceWithNewValue(LI, I2); 83318334Speter LI->eraseFromParent(); 83418334Speter DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName() 83518334Speter << "' in function '" << F->getName() << "'\n"); 83618334Speter } else { 83718334Speter GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back()); 83818334Speter IndicesVector Operands; 83918334Speter Operands.reserve(GEP->getNumIndices()); 84018334Speter for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end(); 84118334Speter II != IE; ++II) 84218334Speter Operands.push_back(cast<ConstantInt>(*II)->getSExtValue()); 84318334Speter 84418334Speter // GEPs with a single 0 index can be merged with direct loads 84518334Speter if (Operands.size() == 1 && Operands.front() == 0) 84618334Speter Operands.clear(); 84718334Speter 84818334Speter Function::arg_iterator TheArg = I2; 84918334Speter for (ScalarizeTable::iterator It = ArgIndices.begin(); 85018334Speter *It != Operands; ++It, ++TheArg) { 85118334Speter assert(It != ArgIndices.end() && "GEP not handled??"); 85218334Speter } 85318334Speter 85418334Speter std::string NewName = I->getName(); 85518334Speter for (unsigned i = 0, e = Operands.size(); i != e; ++i) { 85618334Speter NewName += "." + utostr(Operands[i]); 85718334Speter } 85818334Speter NewName += ".val"; 85918334Speter TheArg->setName(NewName); 86018334Speter 86118334Speter DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName() 86218334Speter << "' of function '" << NF->getName() << "'\n"); 86318334Speter 86418334Speter // All of the uses must be load instructions. Replace them all with 86518334Speter // the argument specified by ArgNo. 86618334Speter while (!GEP->use_empty()) { 86718334Speter LoadInst *L = cast<LoadInst>(GEP->use_back()); 86818334Speter L->replaceAllUsesWith(TheArg); 86918334Speter AA.replaceWithNewValue(L, TheArg); 87018334Speter L->eraseFromParent(); 87118334Speter } 87218334Speter AA.deleteValue(GEP); 87318334Speter GEP->eraseFromParent(); 87418334Speter } 87518334Speter } 87618334Speter 87718334Speter // Increment I2 past all of the arguments added for this promoted pointer. 87818334Speter std::advance(I2, ArgIndices.size()); 87918334Speter } 88018334Speter 88118334Speter // Tell the alias analysis that the old function is about to disappear. 88218334Speter AA.replaceWithNewValue(F, NF); 88318334Speter 88418334Speter 88518334Speter NF_CGN->stealCalledFunctionsFrom(CG[F]); 88618334Speter 88718334Speter // Now that the old function is dead, delete it. If there is a dangling 88818334Speter // reference to the CallgraphNode, just leave the dead function around for 88918334Speter // someone else to nuke. 89018334Speter CallGraphNode *CGN = CG[F]; 89118334Speter if (CGN->getNumReferences() == 0) 89218334Speter delete CG.removeFunctionFromModule(CGN); 89318334Speter else 89418334Speter F->setLinkage(Function::ExternalLinkage); 89518334Speter 89618334Speter return NF_CGN; 89718334Speter} 89818334Speter