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), DL(nullptr), 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;
81 CallGraphNode *PromoteArguments(CallGraphNode *CGN);
82 bool isSafeToPromoteArgument(Argument *Arg, bool isByVal) const;
83 CallGraphNode *DoPromotion(Function *F,
84 SmallPtrSetImpl<Argument*> &ArgsToPromote,
85 SmallPtrSetImpl<Argument*> &ByValArgsToTransform);
87 using llvm::Pass::doInitialization;
88 bool doInitialization(CallGraph &CG) override;
89 /// The maximum number of elements to expand, or 0 for unlimited.
91 DenseMap<const Function *, DISubprogram> FunctionDIs;
95 char ArgPromotion::ID = 0;
96 INITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion",
97 "Promote 'by reference' arguments to scalars", false, false)
98 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
99 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
100 INITIALIZE_PASS_END(ArgPromotion, "argpromotion",
101 "Promote 'by reference' arguments to scalars", false, false)
103 Pass *llvm::createArgumentPromotionPass(unsigned maxElements) {
104 return new ArgPromotion(maxElements);
107 bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
108 bool Changed = false, LocalChange;
110 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
111 DL = DLP ? &DLP->getDataLayout() : nullptr;
113 do { // Iterate until we stop promoting from this SCC.
115 // Attempt to promote arguments from all functions in this SCC.
116 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
117 if (CallGraphNode *CGN = PromoteArguments(*I)) {
119 SCC.ReplaceNode(*I, CGN);
122 Changed |= LocalChange; // Remember that we changed something.
123 } while (LocalChange);
128 /// PromoteArguments - This method checks the specified function to see if there
129 /// are any promotable arguments and if it is safe to promote the function (for
130 /// example, all callers are direct). If safe to promote some arguments, it
131 /// calls the DoPromotion method.
133 CallGraphNode *ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
134 Function *F = CGN->getFunction();
136 // Make sure that it is local to this module.
137 if (!F || !F->hasLocalLinkage()) return nullptr;
139 // First check: see if there are any pointer arguments! If not, quick exit.
140 SmallVector<Argument*, 16> PointerArgs;
141 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
142 if (I->getType()->isPointerTy())
143 PointerArgs.push_back(I);
144 if (PointerArgs.empty()) return nullptr;
146 // Second check: make sure that all callers are direct callers. We can't
147 // transform functions that have indirect callers. Also see if the function
148 // is self-recursive.
149 bool isSelfRecursive = false;
150 for (Use &U : F->uses()) {
151 CallSite CS(U.getUser());
152 // Must be a direct call.
153 if (CS.getInstruction() == nullptr || !CS.isCallee(&U)) return nullptr;
155 if (CS.getInstruction()->getParent()->getParent() == F)
156 isSelfRecursive = true;
159 // Don't promote arguments for variadic functions. Adding, removing, or
160 // changing non-pack parameters can change the classification of pack
161 // parameters. Frontends encode that classification at the call site in the
162 // IR, while in the callee the classification is determined dynamically based
163 // on the number of registers consumed so far.
164 if (F->isVarArg()) return nullptr;
166 // Check to see which arguments are promotable. If an argument is promotable,
167 // add it to ArgsToPromote.
168 SmallPtrSet<Argument*, 8> ArgsToPromote;
169 SmallPtrSet<Argument*, 8> ByValArgsToTransform;
170 for (unsigned i = 0, e = PointerArgs.size(); i != e; ++i) {
171 Argument *PtrArg = PointerArgs[i];
172 Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
174 // If this is a byval argument, and if the aggregate type is small, just
175 // pass the elements, which is always safe. This does not apply to
177 if (PtrArg->hasByValAttr()) {
178 if (StructType *STy = dyn_cast<StructType>(AgTy)) {
179 if (maxElements > 0 && STy->getNumElements() > maxElements) {
180 DEBUG(dbgs() << "argpromotion disable promoting argument '"
181 << PtrArg->getName() << "' because it would require adding more"
182 << " than " << maxElements << " arguments to the function.\n");
186 // If all the elements are single-value types, we can promote it.
187 bool AllSimple = true;
188 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
189 if (!STy->getElementType(i)->isSingleValueType()) {
195 // Safe to transform, don't even bother trying to "promote" it.
196 // Passing the elements as a scalar will allow scalarrepl to hack on
197 // the new alloca we introduce.
199 ByValArgsToTransform.insert(PtrArg);
205 // If the argument is a recursive type and we're in a recursive
206 // function, we could end up infinitely peeling the function argument.
207 if (isSelfRecursive) {
208 if (StructType *STy = dyn_cast<StructType>(AgTy)) {
209 bool RecursiveType = false;
210 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
211 if (STy->getElementType(i) == PtrArg->getType()) {
212 RecursiveType = true;
221 // Otherwise, see if we can promote the pointer to its value.
222 if (isSafeToPromoteArgument(PtrArg, PtrArg->hasByValOrInAllocaAttr()))
223 ArgsToPromote.insert(PtrArg);
226 // No promotable pointer arguments.
227 if (ArgsToPromote.empty() && ByValArgsToTransform.empty())
230 return DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
233 /// AllCallersPassInValidPointerForArgument - Return true if we can prove that
234 /// all callees pass in a valid pointer for the specified function argument.
235 static bool AllCallersPassInValidPointerForArgument(Argument *Arg,
236 const DataLayout *DL) {
237 Function *Callee = Arg->getParent();
239 unsigned ArgNo = Arg->getArgNo();
241 // Look at all call sites of the function. At this pointer we know we only
242 // have direct callees.
243 for (User *U : Callee->users()) {
245 assert(CS && "Should only have direct calls!");
247 if (!CS.getArgument(ArgNo)->isDereferenceablePointer(DL))
253 /// Returns true if Prefix is a prefix of longer. That means, Longer has a size
254 /// that is greater than or equal to the size of prefix, and each of the
255 /// elements in Prefix is the same as the corresponding elements in Longer.
257 /// This means it also returns true when Prefix and Longer are equal!
258 static bool IsPrefix(const ArgPromotion::IndicesVector &Prefix,
259 const ArgPromotion::IndicesVector &Longer) {
260 if (Prefix.size() > Longer.size())
262 return std::equal(Prefix.begin(), Prefix.end(), Longer.begin());
266 /// Checks if Indices, or a prefix of Indices, is in Set.
267 static bool PrefixIn(const ArgPromotion::IndicesVector &Indices,
268 std::set<ArgPromotion::IndicesVector> &Set) {
269 std::set<ArgPromotion::IndicesVector>::iterator Low;
270 Low = Set.upper_bound(Indices);
271 if (Low != Set.begin())
273 // Low is now the last element smaller than or equal to Indices. This means
274 // it points to a prefix of Indices (possibly Indices itself), if such
277 // This load is safe if any prefix of its operands is safe to load.
278 return Low != Set.end() && IsPrefix(*Low, Indices);
281 /// Mark the given indices (ToMark) as safe in the given set of indices
282 /// (Safe). Marking safe usually means adding ToMark to Safe. However, if there
283 /// is already a prefix of Indices in Safe, Indices are implicitely marked safe
284 /// already. Furthermore, any indices that Indices is itself a prefix of, are
285 /// removed from Safe (since they are implicitely safe because of Indices now).
286 static void MarkIndicesSafe(const ArgPromotion::IndicesVector &ToMark,
287 std::set<ArgPromotion::IndicesVector> &Safe) {
288 std::set<ArgPromotion::IndicesVector>::iterator Low;
289 Low = Safe.upper_bound(ToMark);
290 // Guard against the case where Safe is empty
291 if (Low != Safe.begin())
293 // Low is now the last element smaller than or equal to Indices. This
294 // means it points to a prefix of Indices (possibly Indices itself), if
295 // such prefix exists.
296 if (Low != Safe.end()) {
297 if (IsPrefix(*Low, ToMark))
298 // If there is already a prefix of these indices (or exactly these
299 // indices) marked a safe, don't bother adding these indices
302 // Increment Low, so we can use it as a "insert before" hint
306 Low = Safe.insert(Low, ToMark);
308 // If there we're a prefix of longer index list(s), remove those
309 std::set<ArgPromotion::IndicesVector>::iterator End = Safe.end();
310 while (Low != End && IsPrefix(ToMark, *Low)) {
311 std::set<ArgPromotion::IndicesVector>::iterator Remove = Low;
317 /// isSafeToPromoteArgument - As you might guess from the name of this method,
318 /// it checks to see if it is both safe and useful to promote the argument.
319 /// This method limits promotion of aggregates to only promote up to three
320 /// elements of the aggregate in order to avoid exploding the number of
321 /// arguments passed in.
322 bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg,
323 bool isByValOrInAlloca) const {
324 typedef std::set<IndicesVector> GEPIndicesSet;
326 // Quick exit for unused arguments
327 if (Arg->use_empty())
330 // We can only promote this argument if all of the uses are loads, or are GEP
331 // instructions (with constant indices) that are subsequently loaded.
333 // Promoting the argument causes it to be loaded in the caller
334 // unconditionally. This is only safe if we can prove that either the load
335 // would have happened in the callee anyway (ie, there is a load in the entry
336 // block) or the pointer passed in at every call site is guaranteed to be
338 // In the former case, invalid loads can happen, but would have happened
339 // anyway, in the latter case, invalid loads won't happen. This prevents us
340 // from introducing an invalid load that wouldn't have happened in the
343 // This set will contain all sets of indices that are loaded in the entry
344 // block, and thus are safe to unconditionally load in the caller.
346 // This optimization is also safe for InAlloca parameters, because it verifies
347 // that the address isn't captured.
348 GEPIndicesSet SafeToUnconditionallyLoad;
350 // This set contains all the sets of indices that we are planning to promote.
351 // This makes it possible to limit the number of arguments added.
352 GEPIndicesSet ToPromote;
354 // If the pointer is always valid, any load with first index 0 is valid.
355 if (isByValOrInAlloca || AllCallersPassInValidPointerForArgument(Arg, DL))
356 SafeToUnconditionallyLoad.insert(IndicesVector(1, 0));
358 // First, iterate the entry block and mark loads of (geps of) arguments as
360 BasicBlock *EntryBlock = Arg->getParent()->begin();
361 // Declare this here so we can reuse it
362 IndicesVector Indices;
363 for (BasicBlock::iterator I = EntryBlock->begin(), E = EntryBlock->end();
365 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
366 Value *V = LI->getPointerOperand();
367 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
368 V = GEP->getPointerOperand();
370 // This load actually loads (part of) Arg? Check the indices then.
371 Indices.reserve(GEP->getNumIndices());
372 for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
374 if (ConstantInt *CI = dyn_cast<ConstantInt>(*II))
375 Indices.push_back(CI->getSExtValue());
377 // We found a non-constant GEP index for this argument? Bail out
378 // right away, can't promote this argument at all.
381 // Indices checked out, mark them as safe
382 MarkIndicesSafe(Indices, SafeToUnconditionallyLoad);
385 } else if (V == Arg) {
386 // Direct loads are equivalent to a GEP with a single 0 index.
387 MarkIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
391 // Now, iterate all uses of the argument to see if there are any uses that are
392 // not (GEP+)loads, or any (GEP+)loads that are not safe to promote.
393 SmallVector<LoadInst*, 16> Loads;
394 IndicesVector Operands;
395 for (Use &U : Arg->uses()) {
396 User *UR = U.getUser();
398 if (LoadInst *LI = dyn_cast<LoadInst>(UR)) {
399 // Don't hack volatile/atomic loads
400 if (!LI->isSimple()) return false;
402 // Direct loads are equivalent to a GEP with a zero index and then a load.
403 Operands.push_back(0);
404 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UR)) {
405 if (GEP->use_empty()) {
406 // Dead GEP's cause trouble later. Just remove them if we run into
408 getAnalysis<AliasAnalysis>().deleteValue(GEP);
409 GEP->eraseFromParent();
410 // TODO: This runs the above loop over and over again for dead GEPs
411 // Couldn't we just do increment the UI iterator earlier and erase the
413 return isSafeToPromoteArgument(Arg, isByValOrInAlloca);
416 // Ensure that all of the indices are constants.
417 for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end();
419 if (ConstantInt *C = dyn_cast<ConstantInt>(*i))
420 Operands.push_back(C->getSExtValue());
422 return false; // Not a constant operand GEP!
424 // Ensure that the only users of the GEP are load instructions.
425 for (User *GEPU : GEP->users())
426 if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
427 // Don't hack volatile/atomic loads
428 if (!LI->isSimple()) return false;
431 // Other uses than load?
435 return false; // Not a load or a GEP.
438 // Now, see if it is safe to promote this load / loads of this GEP. Loading
439 // is safe if Operands, or a prefix of Operands, is marked as safe.
440 if (!PrefixIn(Operands, SafeToUnconditionallyLoad))
443 // See if we are already promoting a load with these indices. If not, check
444 // to make sure that we aren't promoting too many elements. If so, nothing
446 if (ToPromote.find(Operands) == ToPromote.end()) {
447 if (maxElements > 0 && ToPromote.size() == maxElements) {
448 DEBUG(dbgs() << "argpromotion not promoting argument '"
449 << Arg->getName() << "' because it would require adding more "
450 << "than " << maxElements << " arguments to the function.\n");
451 // We limit aggregate promotion to only promoting up to a fixed number
452 // of elements of the aggregate.
455 ToPromote.insert(Operands);
459 if (Loads.empty()) return true; // No users, this is a dead argument.
461 // Okay, now we know that the argument is only used by load instructions and
462 // it is safe to unconditionally perform all of them. Use alias analysis to
463 // check to see if the pointer is guaranteed to not be modified from entry of
464 // the function to each of the load instructions.
466 // Because there could be several/many load instructions, remember which
467 // blocks we know to be transparent to the load.
468 SmallPtrSet<BasicBlock*, 16> TranspBlocks;
470 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
472 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
473 // Check to see if the load is invalidated from the start of the block to
475 LoadInst *Load = Loads[i];
476 BasicBlock *BB = Load->getParent();
478 AliasAnalysis::Location Loc = AA.getLocation(Load);
479 if (AA.canInstructionRangeModify(BB->front(), *Load, Loc))
480 return false; // Pointer is invalidated!
482 // Now check every path from the entry block to the load for transparency.
483 // To do this, we perform a depth first search on the inverse CFG from the
485 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
487 for (BasicBlock *TranspBB : inverse_depth_first_ext(P, TranspBlocks))
488 if (AA.canBasicBlockModify(*TranspBB, Loc))
493 // If the path from the entry of the function to each load is free of
494 // instructions that potentially invalidate the load, we can make the
499 /// DoPromotion - This method actually performs the promotion of the specified
500 /// arguments, and returns the new function. At this point, we know that it's
502 CallGraphNode *ArgPromotion::DoPromotion(Function *F,
503 SmallPtrSetImpl<Argument*> &ArgsToPromote,
504 SmallPtrSetImpl<Argument*> &ByValArgsToTransform) {
506 // Start by computing a new prototype for the function, which is the same as
507 // the old function, but has modified arguments.
508 FunctionType *FTy = F->getFunctionType();
509 std::vector<Type*> Params;
511 typedef std::set<IndicesVector> ScalarizeTable;
513 // ScalarizedElements - If we are promoting a pointer that has elements
514 // accessed out of it, keep track of which elements are accessed so that we
515 // can add one argument for each.
517 // Arguments that are directly loaded will have a zero element value here, to
518 // handle cases where there are both a direct load and GEP accesses.
520 std::map<Argument*, ScalarizeTable> ScalarizedElements;
522 // OriginalLoads - Keep track of a representative load instruction from the
523 // original function so that we can tell the alias analysis implementation
524 // what the new GEP/Load instructions we are inserting look like.
525 // We need to keep the original loads for each argument and the elements
526 // of the argument that are accessed.
527 std::map<std::pair<Argument*, IndicesVector>, LoadInst*> OriginalLoads;
529 // Attribute - Keep track of the parameter attributes for the arguments
530 // that we are *not* promoting. For the ones that we do promote, the parameter
531 // attributes are lost
532 SmallVector<AttributeSet, 8> AttributesVec;
533 const AttributeSet &PAL = F->getAttributes();
535 // Add any return attributes.
536 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
537 AttributesVec.push_back(AttributeSet::get(F->getContext(),
538 PAL.getRetAttributes()));
540 // First, determine the new argument list
541 unsigned ArgIndex = 1;
542 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
544 if (ByValArgsToTransform.count(I)) {
545 // Simple byval argument? Just add all the struct element types.
546 Type *AgTy = cast<PointerType>(I->getType())->getElementType();
547 StructType *STy = cast<StructType>(AgTy);
548 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
549 Params.push_back(STy->getElementType(i));
550 ++NumByValArgsPromoted;
551 } else if (!ArgsToPromote.count(I)) {
552 // Unchanged argument
553 Params.push_back(I->getType());
554 AttributeSet attrs = PAL.getParamAttributes(ArgIndex);
555 if (attrs.hasAttributes(ArgIndex)) {
556 AttrBuilder B(attrs, ArgIndex);
558 push_back(AttributeSet::get(F->getContext(), Params.size(), B));
560 } else if (I->use_empty()) {
561 // Dead argument (which are always marked as promotable)
564 // Okay, this is being promoted. This means that the only uses are loads
565 // or GEPs which are only used by loads
567 // In this table, we will track which indices are loaded from the argument
568 // (where direct loads are tracked as no indices).
569 ScalarizeTable &ArgIndices = ScalarizedElements[I];
570 for (User *U : I->users()) {
571 Instruction *UI = cast<Instruction>(U);
572 assert(isa<LoadInst>(UI) || isa<GetElementPtrInst>(UI));
573 IndicesVector Indices;
574 Indices.reserve(UI->getNumOperands() - 1);
575 // Since loads will only have a single operand, and GEPs only a single
576 // non-index operand, this will record direct loads without any indices,
577 // and gep+loads with the GEP indices.
578 for (User::op_iterator II = UI->op_begin() + 1, IE = UI->op_end();
580 Indices.push_back(cast<ConstantInt>(*II)->getSExtValue());
581 // GEPs with a single 0 index can be merged with direct loads
582 if (Indices.size() == 1 && Indices.front() == 0)
584 ArgIndices.insert(Indices);
586 if (LoadInst *L = dyn_cast<LoadInst>(UI))
589 // Take any load, we will use it only to update Alias Analysis
590 OrigLoad = cast<LoadInst>(UI->user_back());
591 OriginalLoads[std::make_pair(I, Indices)] = OrigLoad;
594 // Add a parameter to the function for each element passed in.
595 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
596 E = ArgIndices.end(); SI != E; ++SI) {
597 // not allowed to dereference ->begin() if size() is 0
598 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
599 assert(Params.back());
602 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
603 ++NumArgumentsPromoted;
605 ++NumAggregatesPromoted;
609 // Add any function attributes.
610 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
611 AttributesVec.push_back(AttributeSet::get(FTy->getContext(),
612 PAL.getFnAttributes()));
614 Type *RetTy = FTy->getReturnType();
616 // Construct the new function type using the new arguments.
617 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
619 // Create the new function body and insert it into the module.
620 Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
621 NF->copyAttributesFrom(F);
623 // Patch the pointer to LLVM function in debug info descriptor.
624 auto DI = FunctionDIs.find(F);
625 if (DI != FunctionDIs.end()) {
626 DISubprogram SP = DI->second;
627 SP.replaceFunction(NF);
628 FunctionDIs.erase(DI);
629 FunctionDIs[NF] = SP;
632 DEBUG(dbgs() << "ARG PROMOTION: Promoting to:" << *NF << "\n"
635 // Recompute the parameter attributes list based on the new arguments for
637 NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec));
638 AttributesVec.clear();
640 F->getParent()->getFunctionList().insert(F, NF);
643 // Get the alias analysis information that we need to update to reflect our
645 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
647 // Get the callgraph information that we need to update to reflect our
649 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
651 // Get a new callgraph node for NF.
652 CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
654 // Loop over all of the callers of the function, transforming the call sites
655 // to pass in the loaded pointers.
657 SmallVector<Value*, 16> Args;
658 while (!F->use_empty()) {
659 CallSite CS(F->user_back());
660 assert(CS.getCalledFunction() == F);
661 Instruction *Call = CS.getInstruction();
662 const AttributeSet &CallPAL = CS.getAttributes();
664 // Add any return attributes.
665 if (CallPAL.hasAttributes(AttributeSet::ReturnIndex))
666 AttributesVec.push_back(AttributeSet::get(F->getContext(),
667 CallPAL.getRetAttributes()));
669 // Loop over the operands, inserting GEP and loads in the caller as
671 CallSite::arg_iterator AI = CS.arg_begin();
673 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
674 I != E; ++I, ++AI, ++ArgIndex)
675 if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
676 Args.push_back(*AI); // Unmodified argument
678 if (CallPAL.hasAttributes(ArgIndex)) {
679 AttrBuilder B(CallPAL, ArgIndex);
681 push_back(AttributeSet::get(F->getContext(), Args.size(), B));
683 } else if (ByValArgsToTransform.count(I)) {
684 // Emit a GEP and load for each element of the struct.
685 Type *AgTy = cast<PointerType>(I->getType())->getElementType();
686 StructType *STy = cast<StructType>(AgTy);
688 ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr };
689 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
690 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
691 Value *Idx = GetElementPtrInst::Create(*AI, Idxs,
692 (*AI)->getName()+"."+utostr(i),
694 // TODO: Tell AA about the new values?
695 Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
697 } else if (!I->use_empty()) {
698 // Non-dead argument: insert GEPs and loads as appropriate.
699 ScalarizeTable &ArgIndices = ScalarizedElements[I];
700 // Store the Value* version of the indices in here, but declare it now
702 std::vector<Value*> Ops;
703 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
704 E = ArgIndices.end(); SI != E; ++SI) {
706 LoadInst *OrigLoad = OriginalLoads[std::make_pair(I, *SI)];
708 Ops.reserve(SI->size());
709 Type *ElTy = V->getType();
710 for (IndicesVector::const_iterator II = SI->begin(),
711 IE = SI->end(); II != IE; ++II) {
712 // Use i32 to index structs, and i64 for others (pointers/arrays).
713 // This satisfies GEP constraints.
714 Type *IdxTy = (ElTy->isStructTy() ?
715 Type::getInt32Ty(F->getContext()) :
716 Type::getInt64Ty(F->getContext()));
717 Ops.push_back(ConstantInt::get(IdxTy, *II));
718 // Keep track of the type we're currently indexing.
719 ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(*II);
721 // And create a GEP to extract those indices.
722 V = GetElementPtrInst::Create(V, Ops, V->getName()+".idx", Call);
724 AA.copyValue(OrigLoad->getOperand(0), V);
726 // Since we're replacing a load make sure we take the alignment
727 // of the previous load.
728 LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call);
729 newLoad->setAlignment(OrigLoad->getAlignment());
730 // Transfer the AA info too.
732 OrigLoad->getAAMetadata(AAInfo);
733 newLoad->setAAMetadata(AAInfo);
735 Args.push_back(newLoad);
736 AA.copyValue(OrigLoad, Args.back());
740 // Push any varargs arguments on the list.
741 for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
743 if (CallPAL.hasAttributes(ArgIndex)) {
744 AttrBuilder B(CallPAL, ArgIndex);
746 push_back(AttributeSet::get(F->getContext(), Args.size(), B));
750 // Add any function attributes.
751 if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
752 AttributesVec.push_back(AttributeSet::get(Call->getContext(),
753 CallPAL.getFnAttributes()));
756 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
757 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
759 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
760 cast<InvokeInst>(New)->setAttributes(AttributeSet::get(II->getContext(),
763 New = CallInst::Create(NF, Args, "", Call);
764 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
765 cast<CallInst>(New)->setAttributes(AttributeSet::get(New->getContext(),
767 if (cast<CallInst>(Call)->isTailCall())
768 cast<CallInst>(New)->setTailCall();
770 New->setDebugLoc(Call->getDebugLoc());
772 AttributesVec.clear();
774 // Update the alias analysis implementation to know that we are replacing
775 // the old call with a new one.
776 AA.replaceWithNewValue(Call, New);
778 // Update the callgraph to know that the callsite has been transformed.
779 CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
780 CalleeNode->replaceCallEdge(Call, New, NF_CGN);
782 if (!Call->use_empty()) {
783 Call->replaceAllUsesWith(New);
787 // Finally, remove the old call from the program, reducing the use-count of
789 Call->eraseFromParent();
792 // Since we have now created the new function, splice the body of the old
793 // function right into the new function, leaving the old rotting hulk of the
795 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
797 // Loop over the argument list, transferring uses of the old arguments over to
798 // the new arguments, also transferring over the names as well.
800 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
801 I2 = NF->arg_begin(); I != E; ++I) {
802 if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
803 // If this is an unmodified argument, move the name and users over to the
805 I->replaceAllUsesWith(I2);
807 AA.replaceWithNewValue(I, I2);
812 if (ByValArgsToTransform.count(I)) {
813 // In the callee, we create an alloca, and store each of the new incoming
814 // arguments into the alloca.
815 Instruction *InsertPt = NF->begin()->begin();
817 // Just add all the struct element types.
818 Type *AgTy = cast<PointerType>(I->getType())->getElementType();
819 Value *TheAlloca = new AllocaInst(AgTy, nullptr, "", InsertPt);
820 StructType *STy = cast<StructType>(AgTy);
822 ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr };
824 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
825 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
827 GetElementPtrInst::Create(TheAlloca, Idxs,
828 TheAlloca->getName()+"."+Twine(i),
830 I2->setName(I->getName()+"."+Twine(i));
831 new StoreInst(I2++, Idx, InsertPt);
834 // Anything that used the arg should now use the alloca.
835 I->replaceAllUsesWith(TheAlloca);
836 TheAlloca->takeName(I);
837 AA.replaceWithNewValue(I, TheAlloca);
839 // If the alloca is used in a call, we must clear the tail flag since
840 // the callee now uses an alloca from the caller.
841 for (User *U : TheAlloca->users()) {
842 CallInst *Call = dyn_cast<CallInst>(U);
845 Call->setTailCall(false);
850 if (I->use_empty()) {
855 // Otherwise, if we promoted this argument, then all users are load
856 // instructions (or GEPs with only load users), and all loads should be
857 // using the new argument that we added.
858 ScalarizeTable &ArgIndices = ScalarizedElements[I];
860 while (!I->use_empty()) {
861 if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) {
862 assert(ArgIndices.begin()->empty() &&
863 "Load element should sort to front!");
864 I2->setName(I->getName()+".val");
865 LI->replaceAllUsesWith(I2);
866 AA.replaceWithNewValue(LI, I2);
867 LI->eraseFromParent();
868 DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
869 << "' in function '" << F->getName() << "'\n");
871 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->user_back());
872 IndicesVector Operands;
873 Operands.reserve(GEP->getNumIndices());
874 for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
876 Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
878 // GEPs with a single 0 index can be merged with direct loads
879 if (Operands.size() == 1 && Operands.front() == 0)
882 Function::arg_iterator TheArg = I2;
883 for (ScalarizeTable::iterator It = ArgIndices.begin();
884 *It != Operands; ++It, ++TheArg) {
885 assert(It != ArgIndices.end() && "GEP not handled??");
888 std::string NewName = I->getName();
889 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
890 NewName += "." + utostr(Operands[i]);
893 TheArg->setName(NewName);
895 DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
896 << "' of function '" << NF->getName() << "'\n");
898 // All of the uses must be load instructions. Replace them all with
899 // the argument specified by ArgNo.
900 while (!GEP->use_empty()) {
901 LoadInst *L = cast<LoadInst>(GEP->user_back());
902 L->replaceAllUsesWith(TheArg);
903 AA.replaceWithNewValue(L, TheArg);
904 L->eraseFromParent();
907 GEP->eraseFromParent();
911 // Increment I2 past all of the arguments added for this promoted pointer.
912 std::advance(I2, ArgIndices.size());
915 // Tell the alias analysis that the old function is about to disappear.
916 AA.replaceWithNewValue(F, NF);
919 NF_CGN->stealCalledFunctionsFrom(CG[F]);
921 // Now that the old function is dead, delete it. If there is a dangling
922 // reference to the CallgraphNode, just leave the dead function around for
923 // someone else to nuke.
924 CallGraphNode *CGN = CG[F];
925 if (CGN->getNumReferences() == 0)
926 delete CG.removeFunctionFromModule(CGN);
928 F->setLinkage(Function::ExternalLinkage);
933 bool ArgPromotion::doInitialization(CallGraph &CG) {
934 FunctionDIs = makeSubprogramMap(CG.getModule());
935 return CallGraphSCCPass::doInitialization(CG);