1 //===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass promotes "by reference" arguments to be "by value" arguments. In
11 // practice, this means looking for internal functions that have pointer
12 // arguments. If it can prove, through the use of alias analysis, that an
13 // argument is *only* loaded, then it can pass the value into the function
14 // instead of the address of the value. This can cause recursive simplification
15 // of code and lead to the elimination of allocas (especially in C++ template
16 // code like the STL).
18 // This pass also handles aggregate arguments that are passed into a function,
19 // scalarizing them if the elements of the aggregate are only loaded. Note that
20 // by default it refuses to scalarize aggregates which would require passing in
21 // more than three operands to the function, because passing thousands of
22 // operands for a large array or structure is unprofitable! This limit can be
23 // configured or disabled, however.
25 // Note that this transformation could also be done for arguments that are only
26 // stored to (returning the value instead), but does not currently. This case
27 // would be best handled when and if LLVM begins supporting multiple return
28 // values from functions.
30 //===----------------------------------------------------------------------===//
32 #include "llvm/Transforms/IPO.h"
33 #include "llvm/ADT/DepthFirstIterator.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringExtras.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Analysis/CallGraph.h"
38 #include "llvm/Analysis/CallGraphSCCPass.h"
39 #include "llvm/IR/CFG.h"
40 #include "llvm/IR/CallSite.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DataLayout.h"
43 #include "llvm/IR/DebugInfo.h"
44 #include "llvm/IR/DerivedTypes.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/LLVMContext.h"
47 #include "llvm/IR/Module.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/raw_ostream.h"
53 #define DEBUG_TYPE "argpromotion"
55 STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
56 STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
57 STATISTIC(NumByValArgsPromoted , "Number of byval arguments promoted");
58 STATISTIC(NumArgumentsDead , "Number of dead pointer args eliminated");
61 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
63 struct ArgPromotion : public CallGraphSCCPass {
64 void getAnalysisUsage(AnalysisUsage &AU) const override {
65 AU.addRequired<AliasAnalysis>();
66 CallGraphSCCPass::getAnalysisUsage(AU);
69 bool runOnSCC(CallGraphSCC &SCC) override;
70 static char ID; // Pass identification, replacement for typeid
71 explicit ArgPromotion(unsigned maxElements = 3)
72 : CallGraphSCCPass(ID), maxElements(maxElements) {
73 initializeArgPromotionPass(*PassRegistry::getPassRegistry());
76 /// A vector used to hold the indices of a single GEP instruction
77 typedef std::vector<uint64_t> IndicesVector;
80 bool isDenselyPacked(Type *type, const DataLayout &DL);
81 bool canPaddingBeAccessed(Argument *Arg);
82 CallGraphNode *PromoteArguments(CallGraphNode *CGN);
83 bool isSafeToPromoteArgument(Argument *Arg, bool isByVal) const;
84 CallGraphNode *DoPromotion(Function *F,
85 SmallPtrSetImpl<Argument*> &ArgsToPromote,
86 SmallPtrSetImpl<Argument*> &ByValArgsToTransform);
88 using llvm::Pass::doInitialization;
89 bool doInitialization(CallGraph &CG) override;
90 /// The maximum number of elements to expand, or 0 for unlimited.
92 DenseMap<const Function *, DISubprogram> FunctionDIs;
96 char ArgPromotion::ID = 0;
97 INITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion",
98 "Promote 'by reference' arguments to scalars", false, false)
99 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
100 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
101 INITIALIZE_PASS_END(ArgPromotion, "argpromotion",
102 "Promote 'by reference' arguments to scalars", false, false)
104 Pass *llvm::createArgumentPromotionPass(unsigned maxElements) {
105 return new ArgPromotion(maxElements);
108 bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
109 bool Changed = false, LocalChange;
111 do { // Iterate until we stop promoting from this SCC.
113 // Attempt to promote arguments from all functions in this SCC.
114 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
115 if (CallGraphNode *CGN = PromoteArguments(*I)) {
117 SCC.ReplaceNode(*I, CGN);
120 Changed |= LocalChange; // Remember that we changed something.
121 } while (LocalChange);
126 /// \brief Checks if a type could have padding bytes.
127 bool ArgPromotion::isDenselyPacked(Type *type, const DataLayout &DL) {
129 // There is no size information, so be conservative.
130 if (!type->isSized())
133 // If the alloc size is not equal to the storage size, then there are padding
134 // bytes. For x86_fp80 on x86-64, size: 80 alloc size: 128.
135 if (DL.getTypeSizeInBits(type) != DL.getTypeAllocSizeInBits(type))
138 if (!isa<CompositeType>(type))
141 // For homogenous sequential types, check for padding within members.
142 if (SequentialType *seqTy = dyn_cast<SequentialType>(type))
143 return isa<PointerType>(seqTy) ||
144 isDenselyPacked(seqTy->getElementType(), DL);
146 // Check for padding within and between elements of a struct.
147 StructType *StructTy = cast<StructType>(type);
148 const StructLayout *Layout = DL.getStructLayout(StructTy);
149 uint64_t StartPos = 0;
150 for (unsigned i = 0, E = StructTy->getNumElements(); i < E; ++i) {
151 Type *ElTy = StructTy->getElementType(i);
152 if (!isDenselyPacked(ElTy, DL))
154 if (StartPos != Layout->getElementOffsetInBits(i))
156 StartPos += DL.getTypeAllocSizeInBits(ElTy);
162 /// \brief Checks if the padding bytes of an argument could be accessed.
163 bool ArgPromotion::canPaddingBeAccessed(Argument *arg) {
165 assert(arg->hasByValAttr());
167 // Track all the pointers to the argument to make sure they are not captured.
168 SmallPtrSet<Value *, 16> PtrValues;
169 PtrValues.insert(arg);
171 // Track all of the stores.
172 SmallVector<StoreInst *, 16> Stores;
174 // Scan through the uses recursively to make sure the pointer is always used
176 SmallVector<Value *, 16> WorkList;
177 WorkList.insert(WorkList.end(), arg->user_begin(), arg->user_end());
178 while (!WorkList.empty()) {
179 Value *V = WorkList.back();
181 if (isa<GetElementPtrInst>(V) || isa<PHINode>(V)) {
182 if (PtrValues.insert(V).second)
183 WorkList.insert(WorkList.end(), V->user_begin(), V->user_end());
184 } else if (StoreInst *Store = dyn_cast<StoreInst>(V)) {
185 Stores.push_back(Store);
186 } else if (!isa<LoadInst>(V)) {
191 // Check to make sure the pointers aren't captured
192 for (StoreInst *Store : Stores)
193 if (PtrValues.count(Store->getValueOperand()))
199 /// PromoteArguments - This method checks the specified function to see if there
200 /// are any promotable arguments and if it is safe to promote the function (for
201 /// example, all callers are direct). If safe to promote some arguments, it
202 /// calls the DoPromotion method.
204 CallGraphNode *ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
205 Function *F = CGN->getFunction();
207 // Make sure that it is local to this module.
208 if (!F || !F->hasLocalLinkage()) return nullptr;
210 // First check: see if there are any pointer arguments! If not, quick exit.
211 SmallVector<Argument*, 16> PointerArgs;
212 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
213 if (I->getType()->isPointerTy())
214 PointerArgs.push_back(I);
215 if (PointerArgs.empty()) return nullptr;
217 // Second check: make sure that all callers are direct callers. We can't
218 // transform functions that have indirect callers. Also see if the function
219 // is self-recursive.
220 bool isSelfRecursive = false;
221 for (Use &U : F->uses()) {
222 CallSite CS(U.getUser());
223 // Must be a direct call.
224 if (CS.getInstruction() == nullptr || !CS.isCallee(&U)) return nullptr;
226 if (CS.getInstruction()->getParent()->getParent() == F)
227 isSelfRecursive = true;
230 // Don't promote arguments for variadic functions. Adding, removing, or
231 // changing non-pack parameters can change the classification of pack
232 // parameters. Frontends encode that classification at the call site in the
233 // IR, while in the callee the classification is determined dynamically based
234 // on the number of registers consumed so far.
235 if (F->isVarArg()) return nullptr;
236 const DataLayout &DL = F->getParent()->getDataLayout();
238 // Check to see which arguments are promotable. If an argument is promotable,
239 // add it to ArgsToPromote.
240 SmallPtrSet<Argument*, 8> ArgsToPromote;
241 SmallPtrSet<Argument*, 8> ByValArgsToTransform;
242 for (unsigned i = 0, e = PointerArgs.size(); i != e; ++i) {
243 Argument *PtrArg = PointerArgs[i];
244 Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
246 // If this is a byval argument, and if the aggregate type is small, just
247 // pass the elements, which is always safe, if the passed value is densely
248 // packed or if we can prove the padding bytes are never accessed. This does
249 // not apply to inalloca.
250 bool isSafeToPromote =
251 PtrArg->hasByValAttr() &&
252 (isDenselyPacked(AgTy, DL) || !canPaddingBeAccessed(PtrArg));
253 if (isSafeToPromote) {
254 if (StructType *STy = dyn_cast<StructType>(AgTy)) {
255 if (maxElements > 0 && STy->getNumElements() > maxElements) {
256 DEBUG(dbgs() << "argpromotion disable promoting argument '"
257 << PtrArg->getName() << "' because it would require adding more"
258 << " than " << maxElements << " arguments to the function.\n");
262 // If all the elements are single-value types, we can promote it.
263 bool AllSimple = true;
264 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
265 if (!STy->getElementType(i)->isSingleValueType()) {
271 // Safe to transform, don't even bother trying to "promote" it.
272 // Passing the elements as a scalar will allow scalarrepl to hack on
273 // the new alloca we introduce.
275 ByValArgsToTransform.insert(PtrArg);
281 // If the argument is a recursive type and we're in a recursive
282 // function, we could end up infinitely peeling the function argument.
283 if (isSelfRecursive) {
284 if (StructType *STy = dyn_cast<StructType>(AgTy)) {
285 bool RecursiveType = false;
286 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
287 if (STy->getElementType(i) == PtrArg->getType()) {
288 RecursiveType = true;
297 // Otherwise, see if we can promote the pointer to its value.
298 if (isSafeToPromoteArgument(PtrArg, PtrArg->hasByValOrInAllocaAttr()))
299 ArgsToPromote.insert(PtrArg);
302 // No promotable pointer arguments.
303 if (ArgsToPromote.empty() && ByValArgsToTransform.empty())
306 return DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
309 /// AllCallersPassInValidPointerForArgument - Return true if we can prove that
310 /// all callees pass in a valid pointer for the specified function argument.
311 static bool AllCallersPassInValidPointerForArgument(Argument *Arg) {
312 Function *Callee = Arg->getParent();
313 const DataLayout &DL = Callee->getParent()->getDataLayout();
315 unsigned ArgNo = Arg->getArgNo();
317 // Look at all call sites of the function. At this pointer we know we only
318 // have direct callees.
319 for (User *U : Callee->users()) {
321 assert(CS && "Should only have direct calls!");
323 if (!CS.getArgument(ArgNo)->isDereferenceablePointer(DL))
329 /// Returns true if Prefix is a prefix of longer. That means, Longer has a size
330 /// that is greater than or equal to the size of prefix, and each of the
331 /// elements in Prefix is the same as the corresponding elements in Longer.
333 /// This means it also returns true when Prefix and Longer are equal!
334 static bool IsPrefix(const ArgPromotion::IndicesVector &Prefix,
335 const ArgPromotion::IndicesVector &Longer) {
336 if (Prefix.size() > Longer.size())
338 return std::equal(Prefix.begin(), Prefix.end(), Longer.begin());
342 /// Checks if Indices, or a prefix of Indices, is in Set.
343 static bool PrefixIn(const ArgPromotion::IndicesVector &Indices,
344 std::set<ArgPromotion::IndicesVector> &Set) {
345 std::set<ArgPromotion::IndicesVector>::iterator Low;
346 Low = Set.upper_bound(Indices);
347 if (Low != Set.begin())
349 // Low is now the last element smaller than or equal to Indices. This means
350 // it points to a prefix of Indices (possibly Indices itself), if such
353 // This load is safe if any prefix of its operands is safe to load.
354 return Low != Set.end() && IsPrefix(*Low, Indices);
357 /// Mark the given indices (ToMark) as safe in the given set of indices
358 /// (Safe). Marking safe usually means adding ToMark to Safe. However, if there
359 /// is already a prefix of Indices in Safe, Indices are implicitely marked safe
360 /// already. Furthermore, any indices that Indices is itself a prefix of, are
361 /// removed from Safe (since they are implicitely safe because of Indices now).
362 static void MarkIndicesSafe(const ArgPromotion::IndicesVector &ToMark,
363 std::set<ArgPromotion::IndicesVector> &Safe) {
364 std::set<ArgPromotion::IndicesVector>::iterator Low;
365 Low = Safe.upper_bound(ToMark);
366 // Guard against the case where Safe is empty
367 if (Low != Safe.begin())
369 // Low is now the last element smaller than or equal to Indices. This
370 // means it points to a prefix of Indices (possibly Indices itself), if
371 // such prefix exists.
372 if (Low != Safe.end()) {
373 if (IsPrefix(*Low, ToMark))
374 // If there is already a prefix of these indices (or exactly these
375 // indices) marked a safe, don't bother adding these indices
378 // Increment Low, so we can use it as a "insert before" hint
382 Low = Safe.insert(Low, ToMark);
384 // If there we're a prefix of longer index list(s), remove those
385 std::set<ArgPromotion::IndicesVector>::iterator End = Safe.end();
386 while (Low != End && IsPrefix(ToMark, *Low)) {
387 std::set<ArgPromotion::IndicesVector>::iterator Remove = Low;
393 /// isSafeToPromoteArgument - As you might guess from the name of this method,
394 /// it checks to see if it is both safe and useful to promote the argument.
395 /// This method limits promotion of aggregates to only promote up to three
396 /// elements of the aggregate in order to avoid exploding the number of
397 /// arguments passed in.
398 bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg,
399 bool isByValOrInAlloca) const {
400 typedef std::set<IndicesVector> GEPIndicesSet;
402 // Quick exit for unused arguments
403 if (Arg->use_empty())
406 // We can only promote this argument if all of the uses are loads, or are GEP
407 // instructions (with constant indices) that are subsequently loaded.
409 // Promoting the argument causes it to be loaded in the caller
410 // unconditionally. This is only safe if we can prove that either the load
411 // would have happened in the callee anyway (ie, there is a load in the entry
412 // block) or the pointer passed in at every call site is guaranteed to be
414 // In the former case, invalid loads can happen, but would have happened
415 // anyway, in the latter case, invalid loads won't happen. This prevents us
416 // from introducing an invalid load that wouldn't have happened in the
419 // This set will contain all sets of indices that are loaded in the entry
420 // block, and thus are safe to unconditionally load in the caller.
422 // This optimization is also safe for InAlloca parameters, because it verifies
423 // that the address isn't captured.
424 GEPIndicesSet SafeToUnconditionallyLoad;
426 // This set contains all the sets of indices that we are planning to promote.
427 // This makes it possible to limit the number of arguments added.
428 GEPIndicesSet ToPromote;
430 // If the pointer is always valid, any load with first index 0 is valid.
431 if (isByValOrInAlloca || AllCallersPassInValidPointerForArgument(Arg))
432 SafeToUnconditionallyLoad.insert(IndicesVector(1, 0));
434 // First, iterate the entry block and mark loads of (geps of) arguments as
436 BasicBlock *EntryBlock = Arg->getParent()->begin();
437 // Declare this here so we can reuse it
438 IndicesVector Indices;
439 for (BasicBlock::iterator I = EntryBlock->begin(), E = EntryBlock->end();
441 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
442 Value *V = LI->getPointerOperand();
443 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
444 V = GEP->getPointerOperand();
446 // This load actually loads (part of) Arg? Check the indices then.
447 Indices.reserve(GEP->getNumIndices());
448 for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
450 if (ConstantInt *CI = dyn_cast<ConstantInt>(*II))
451 Indices.push_back(CI->getSExtValue());
453 // We found a non-constant GEP index for this argument? Bail out
454 // right away, can't promote this argument at all.
457 // Indices checked out, mark them as safe
458 MarkIndicesSafe(Indices, SafeToUnconditionallyLoad);
461 } else if (V == Arg) {
462 // Direct loads are equivalent to a GEP with a single 0 index.
463 MarkIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
467 // Now, iterate all uses of the argument to see if there are any uses that are
468 // not (GEP+)loads, or any (GEP+)loads that are not safe to promote.
469 SmallVector<LoadInst*, 16> Loads;
470 IndicesVector Operands;
471 for (Use &U : Arg->uses()) {
472 User *UR = U.getUser();
474 if (LoadInst *LI = dyn_cast<LoadInst>(UR)) {
475 // Don't hack volatile/atomic loads
476 if (!LI->isSimple()) return false;
478 // Direct loads are equivalent to a GEP with a zero index and then a load.
479 Operands.push_back(0);
480 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UR)) {
481 if (GEP->use_empty()) {
482 // Dead GEP's cause trouble later. Just remove them if we run into
484 getAnalysis<AliasAnalysis>().deleteValue(GEP);
485 GEP->eraseFromParent();
486 // TODO: This runs the above loop over and over again for dead GEPs
487 // Couldn't we just do increment the UI iterator earlier and erase the
489 return isSafeToPromoteArgument(Arg, isByValOrInAlloca);
492 // Ensure that all of the indices are constants.
493 for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end();
495 if (ConstantInt *C = dyn_cast<ConstantInt>(*i))
496 Operands.push_back(C->getSExtValue());
498 return false; // Not a constant operand GEP!
500 // Ensure that the only users of the GEP are load instructions.
501 for (User *GEPU : GEP->users())
502 if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
503 // Don't hack volatile/atomic loads
504 if (!LI->isSimple()) return false;
507 // Other uses than load?
511 return false; // Not a load or a GEP.
514 // Now, see if it is safe to promote this load / loads of this GEP. Loading
515 // is safe if Operands, or a prefix of Operands, is marked as safe.
516 if (!PrefixIn(Operands, SafeToUnconditionallyLoad))
519 // See if we are already promoting a load with these indices. If not, check
520 // to make sure that we aren't promoting too many elements. If so, nothing
522 if (ToPromote.find(Operands) == ToPromote.end()) {
523 if (maxElements > 0 && ToPromote.size() == maxElements) {
524 DEBUG(dbgs() << "argpromotion not promoting argument '"
525 << Arg->getName() << "' because it would require adding more "
526 << "than " << maxElements << " arguments to the function.\n");
527 // We limit aggregate promotion to only promoting up to a fixed number
528 // of elements of the aggregate.
531 ToPromote.insert(std::move(Operands));
535 if (Loads.empty()) return true; // No users, this is a dead argument.
537 // Okay, now we know that the argument is only used by load instructions and
538 // it is safe to unconditionally perform all of them. Use alias analysis to
539 // check to see if the pointer is guaranteed to not be modified from entry of
540 // the function to each of the load instructions.
542 // Because there could be several/many load instructions, remember which
543 // blocks we know to be transparent to the load.
544 SmallPtrSet<BasicBlock*, 16> TranspBlocks;
546 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
548 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
549 // Check to see if the load is invalidated from the start of the block to
551 LoadInst *Load = Loads[i];
552 BasicBlock *BB = Load->getParent();
554 AliasAnalysis::Location Loc = AA.getLocation(Load);
555 if (AA.canInstructionRangeModRef(BB->front(), *Load, Loc,
557 return false; // Pointer is invalidated!
559 // Now check every path from the entry block to the load for transparency.
560 // To do this, we perform a depth first search on the inverse CFG from the
562 for (BasicBlock *P : predecessors(BB)) {
563 for (BasicBlock *TranspBB : inverse_depth_first_ext(P, TranspBlocks))
564 if (AA.canBasicBlockModify(*TranspBB, Loc))
569 // If the path from the entry of the function to each load is free of
570 // instructions that potentially invalidate the load, we can make the
575 /// DoPromotion - This method actually performs the promotion of the specified
576 /// arguments, and returns the new function. At this point, we know that it's
578 CallGraphNode *ArgPromotion::DoPromotion(Function *F,
579 SmallPtrSetImpl<Argument*> &ArgsToPromote,
580 SmallPtrSetImpl<Argument*> &ByValArgsToTransform) {
582 // Start by computing a new prototype for the function, which is the same as
583 // the old function, but has modified arguments.
584 FunctionType *FTy = F->getFunctionType();
585 std::vector<Type*> Params;
587 typedef std::set<std::pair<Type *, IndicesVector>> ScalarizeTable;
589 // ScalarizedElements - If we are promoting a pointer that has elements
590 // accessed out of it, keep track of which elements are accessed so that we
591 // can add one argument for each.
593 // Arguments that are directly loaded will have a zero element value here, to
594 // handle cases where there are both a direct load and GEP accesses.
596 std::map<Argument*, ScalarizeTable> ScalarizedElements;
598 // OriginalLoads - Keep track of a representative load instruction from the
599 // original function so that we can tell the alias analysis implementation
600 // what the new GEP/Load instructions we are inserting look like.
601 // We need to keep the original loads for each argument and the elements
602 // of the argument that are accessed.
603 std::map<std::pair<Argument*, IndicesVector>, LoadInst*> OriginalLoads;
605 // Attribute - Keep track of the parameter attributes for the arguments
606 // that we are *not* promoting. For the ones that we do promote, the parameter
607 // attributes are lost
608 SmallVector<AttributeSet, 8> AttributesVec;
609 const AttributeSet &PAL = F->getAttributes();
611 // Add any return attributes.
612 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
613 AttributesVec.push_back(AttributeSet::get(F->getContext(),
614 PAL.getRetAttributes()));
616 // First, determine the new argument list
617 unsigned ArgIndex = 1;
618 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
620 if (ByValArgsToTransform.count(I)) {
621 // Simple byval argument? Just add all the struct element types.
622 Type *AgTy = cast<PointerType>(I->getType())->getElementType();
623 StructType *STy = cast<StructType>(AgTy);
624 Params.insert(Params.end(), STy->element_begin(), STy->element_end());
625 ++NumByValArgsPromoted;
626 } else if (!ArgsToPromote.count(I)) {
627 // Unchanged argument
628 Params.push_back(I->getType());
629 AttributeSet attrs = PAL.getParamAttributes(ArgIndex);
630 if (attrs.hasAttributes(ArgIndex)) {
631 AttrBuilder B(attrs, ArgIndex);
633 push_back(AttributeSet::get(F->getContext(), Params.size(), B));
635 } else if (I->use_empty()) {
636 // Dead argument (which are always marked as promotable)
639 // Okay, this is being promoted. This means that the only uses are loads
640 // or GEPs which are only used by loads
642 // In this table, we will track which indices are loaded from the argument
643 // (where direct loads are tracked as no indices).
644 ScalarizeTable &ArgIndices = ScalarizedElements[I];
645 for (User *U : I->users()) {
646 Instruction *UI = cast<Instruction>(U);
648 if (LoadInst *L = dyn_cast<LoadInst>(UI))
649 SrcTy = L->getType();
651 SrcTy = cast<GetElementPtrInst>(UI)->getSourceElementType();
652 IndicesVector Indices;
653 Indices.reserve(UI->getNumOperands() - 1);
654 // Since loads will only have a single operand, and GEPs only a single
655 // non-index operand, this will record direct loads without any indices,
656 // and gep+loads with the GEP indices.
657 for (User::op_iterator II = UI->op_begin() + 1, IE = UI->op_end();
659 Indices.push_back(cast<ConstantInt>(*II)->getSExtValue());
660 // GEPs with a single 0 index can be merged with direct loads
661 if (Indices.size() == 1 && Indices.front() == 0)
663 ArgIndices.insert(std::make_pair(SrcTy, Indices));
665 if (LoadInst *L = dyn_cast<LoadInst>(UI))
668 // Take any load, we will use it only to update Alias Analysis
669 OrigLoad = cast<LoadInst>(UI->user_back());
670 OriginalLoads[std::make_pair(I, Indices)] = OrigLoad;
673 // Add a parameter to the function for each element passed in.
674 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
675 E = ArgIndices.end(); SI != E; ++SI) {
676 // not allowed to dereference ->begin() if size() is 0
678 GetElementPtrInst::getIndexedType(I->getType(), SI->second));
679 assert(Params.back());
682 if (ArgIndices.size() == 1 && ArgIndices.begin()->second.empty())
683 ++NumArgumentsPromoted;
685 ++NumAggregatesPromoted;
689 // Add any function attributes.
690 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
691 AttributesVec.push_back(AttributeSet::get(FTy->getContext(),
692 PAL.getFnAttributes()));
694 Type *RetTy = FTy->getReturnType();
696 // Construct the new function type using the new arguments.
697 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
699 // Create the new function body and insert it into the module.
700 Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
701 NF->copyAttributesFrom(F);
703 // Patch the pointer to LLVM function in debug info descriptor.
704 auto DI = FunctionDIs.find(F);
705 if (DI != FunctionDIs.end()) {
706 DISubprogram SP = DI->second;
707 SP.replaceFunction(NF);
708 // Ensure the map is updated so it can be reused on subsequent argument
709 // promotions of the same function.
710 FunctionDIs.erase(DI);
711 FunctionDIs[NF] = SP;
714 DEBUG(dbgs() << "ARG PROMOTION: Promoting to:" << *NF << "\n"
717 // Recompute the parameter attributes list based on the new arguments for
719 NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec));
720 AttributesVec.clear();
722 F->getParent()->getFunctionList().insert(F, NF);
725 // Get the alias analysis information that we need to update to reflect our
727 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
729 // Get the callgraph information that we need to update to reflect our
731 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
733 // Get a new callgraph node for NF.
734 CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
736 // Loop over all of the callers of the function, transforming the call sites
737 // to pass in the loaded pointers.
739 SmallVector<Value*, 16> Args;
740 while (!F->use_empty()) {
741 CallSite CS(F->user_back());
742 assert(CS.getCalledFunction() == F);
743 Instruction *Call = CS.getInstruction();
744 const AttributeSet &CallPAL = CS.getAttributes();
746 // Add any return attributes.
747 if (CallPAL.hasAttributes(AttributeSet::ReturnIndex))
748 AttributesVec.push_back(AttributeSet::get(F->getContext(),
749 CallPAL.getRetAttributes()));
751 // Loop over the operands, inserting GEP and loads in the caller as
753 CallSite::arg_iterator AI = CS.arg_begin();
755 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
756 I != E; ++I, ++AI, ++ArgIndex)
757 if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
758 Args.push_back(*AI); // Unmodified argument
760 if (CallPAL.hasAttributes(ArgIndex)) {
761 AttrBuilder B(CallPAL, ArgIndex);
763 push_back(AttributeSet::get(F->getContext(), Args.size(), B));
765 } else if (ByValArgsToTransform.count(I)) {
766 // Emit a GEP and load for each element of the struct.
767 Type *AgTy = cast<PointerType>(I->getType())->getElementType();
768 StructType *STy = cast<StructType>(AgTy);
770 ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr };
771 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
772 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
773 Value *Idx = GetElementPtrInst::Create(
774 STy, *AI, Idxs, (*AI)->getName() + "." + utostr(i), Call);
775 // TODO: Tell AA about the new values?
776 Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
778 } else if (!I->use_empty()) {
779 // Non-dead argument: insert GEPs and loads as appropriate.
780 ScalarizeTable &ArgIndices = ScalarizedElements[I];
781 // Store the Value* version of the indices in here, but declare it now
783 std::vector<Value*> Ops;
784 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
785 E = ArgIndices.end(); SI != E; ++SI) {
787 LoadInst *OrigLoad = OriginalLoads[std::make_pair(I, SI->second)];
788 if (!SI->second.empty()) {
789 Ops.reserve(SI->second.size());
790 Type *ElTy = V->getType();
791 for (IndicesVector::const_iterator II = SI->second.begin(),
792 IE = SI->second.end();
794 // Use i32 to index structs, and i64 for others (pointers/arrays).
795 // This satisfies GEP constraints.
796 Type *IdxTy = (ElTy->isStructTy() ?
797 Type::getInt32Ty(F->getContext()) :
798 Type::getInt64Ty(F->getContext()));
799 Ops.push_back(ConstantInt::get(IdxTy, *II));
800 // Keep track of the type we're currently indexing.
801 ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(*II);
803 // And create a GEP to extract those indices.
804 V = GetElementPtrInst::Create(SI->first, V, Ops,
805 V->getName() + ".idx", Call);
807 AA.copyValue(OrigLoad->getOperand(0), V);
809 // Since we're replacing a load make sure we take the alignment
810 // of the previous load.
811 LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call);
812 newLoad->setAlignment(OrigLoad->getAlignment());
813 // Transfer the AA info too.
815 OrigLoad->getAAMetadata(AAInfo);
816 newLoad->setAAMetadata(AAInfo);
818 Args.push_back(newLoad);
819 AA.copyValue(OrigLoad, Args.back());
823 // Push any varargs arguments on the list.
824 for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
826 if (CallPAL.hasAttributes(ArgIndex)) {
827 AttrBuilder B(CallPAL, ArgIndex);
829 push_back(AttributeSet::get(F->getContext(), Args.size(), B));
833 // Add any function attributes.
834 if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
835 AttributesVec.push_back(AttributeSet::get(Call->getContext(),
836 CallPAL.getFnAttributes()));
839 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
840 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
842 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
843 cast<InvokeInst>(New)->setAttributes(AttributeSet::get(II->getContext(),
846 New = CallInst::Create(NF, Args, "", Call);
847 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
848 cast<CallInst>(New)->setAttributes(AttributeSet::get(New->getContext(),
850 if (cast<CallInst>(Call)->isTailCall())
851 cast<CallInst>(New)->setTailCall();
853 New->setDebugLoc(Call->getDebugLoc());
855 AttributesVec.clear();
857 // Update the alias analysis implementation to know that we are replacing
858 // the old call with a new one.
859 AA.replaceWithNewValue(Call, New);
861 // Update the callgraph to know that the callsite has been transformed.
862 CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
863 CalleeNode->replaceCallEdge(Call, New, NF_CGN);
865 if (!Call->use_empty()) {
866 Call->replaceAllUsesWith(New);
870 // Finally, remove the old call from the program, reducing the use-count of
872 Call->eraseFromParent();
875 // Since we have now created the new function, splice the body of the old
876 // function right into the new function, leaving the old rotting hulk of the
878 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
880 // Loop over the argument list, transferring uses of the old arguments over to
881 // the new arguments, also transferring over the names as well.
883 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
884 I2 = NF->arg_begin(); I != E; ++I) {
885 if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
886 // If this is an unmodified argument, move the name and users over to the
888 I->replaceAllUsesWith(I2);
890 AA.replaceWithNewValue(I, I2);
895 if (ByValArgsToTransform.count(I)) {
896 // In the callee, we create an alloca, and store each of the new incoming
897 // arguments into the alloca.
898 Instruction *InsertPt = NF->begin()->begin();
900 // Just add all the struct element types.
901 Type *AgTy = cast<PointerType>(I->getType())->getElementType();
902 Value *TheAlloca = new AllocaInst(AgTy, nullptr, "", InsertPt);
903 StructType *STy = cast<StructType>(AgTy);
905 ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr };
907 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
908 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
909 Value *Idx = GetElementPtrInst::Create(
910 AgTy, TheAlloca, Idxs, TheAlloca->getName() + "." + Twine(i),
912 I2->setName(I->getName()+"."+Twine(i));
913 new StoreInst(I2++, Idx, InsertPt);
916 // Anything that used the arg should now use the alloca.
917 I->replaceAllUsesWith(TheAlloca);
918 TheAlloca->takeName(I);
919 AA.replaceWithNewValue(I, TheAlloca);
921 // If the alloca is used in a call, we must clear the tail flag since
922 // the callee now uses an alloca from the caller.
923 for (User *U : TheAlloca->users()) {
924 CallInst *Call = dyn_cast<CallInst>(U);
927 Call->setTailCall(false);
932 if (I->use_empty()) {
937 // Otherwise, if we promoted this argument, then all users are load
938 // instructions (or GEPs with only load users), and all loads should be
939 // using the new argument that we added.
940 ScalarizeTable &ArgIndices = ScalarizedElements[I];
942 while (!I->use_empty()) {
943 if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) {
944 assert(ArgIndices.begin()->second.empty() &&
945 "Load element should sort to front!");
946 I2->setName(I->getName()+".val");
947 LI->replaceAllUsesWith(I2);
948 AA.replaceWithNewValue(LI, I2);
949 LI->eraseFromParent();
950 DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
951 << "' in function '" << F->getName() << "'\n");
953 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->user_back());
954 IndicesVector Operands;
955 Operands.reserve(GEP->getNumIndices());
956 for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
958 Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
960 // GEPs with a single 0 index can be merged with direct loads
961 if (Operands.size() == 1 && Operands.front() == 0)
964 Function::arg_iterator TheArg = I2;
965 for (ScalarizeTable::iterator It = ArgIndices.begin();
966 It->second != Operands; ++It, ++TheArg) {
967 assert(It != ArgIndices.end() && "GEP not handled??");
970 std::string NewName = I->getName();
971 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
972 NewName += "." + utostr(Operands[i]);
975 TheArg->setName(NewName);
977 DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
978 << "' of function '" << NF->getName() << "'\n");
980 // All of the uses must be load instructions. Replace them all with
981 // the argument specified by ArgNo.
982 while (!GEP->use_empty()) {
983 LoadInst *L = cast<LoadInst>(GEP->user_back());
984 L->replaceAllUsesWith(TheArg);
985 AA.replaceWithNewValue(L, TheArg);
986 L->eraseFromParent();
989 GEP->eraseFromParent();
993 // Increment I2 past all of the arguments added for this promoted pointer.
994 std::advance(I2, ArgIndices.size());
997 // Tell the alias analysis that the old function is about to disappear.
998 AA.replaceWithNewValue(F, NF);
1001 NF_CGN->stealCalledFunctionsFrom(CG[F]);
1003 // Now that the old function is dead, delete it. If there is a dangling
1004 // reference to the CallgraphNode, just leave the dead function around for
1005 // someone else to nuke.
1006 CallGraphNode *CGN = CG[F];
1007 if (CGN->getNumReferences() == 0)
1008 delete CG.removeFunctionFromModule(CGN);
1010 F->setLinkage(Function::ExternalLinkage);
1015 bool ArgPromotion::doInitialization(CallGraph &CG) {
1016 FunctionDIs = makeSubprogramMap(CG.getModule());
1017 return CallGraphSCCPass::doInitialization(CG);