DataLayout is mandatory, update the API to reflect it with references.
[oota-llvm.git] / lib / Transforms / IPO / ArgumentPromotion.cpp
1 //===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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).
17 //
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.
24 //
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.
29 //
30 //===----------------------------------------------------------------------===//
31
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"
50 #include <set>
51 using namespace llvm;
52
53 #define DEBUG_TYPE "argpromotion"
54
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");
59
60 namespace {
61   /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
62   ///
63   struct ArgPromotion : public CallGraphSCCPass {
64     void getAnalysisUsage(AnalysisUsage &AU) const override {
65       AU.addRequired<AliasAnalysis>();
66       CallGraphSCCPass::getAnalysisUsage(AU);
67     }
68
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());
74     }
75
76     /// A vector used to hold the indices of a single GEP instruction
77     typedef std::vector<uint64_t> IndicesVector;
78
79   private:
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);
87     
88     using llvm::Pass::doInitialization;
89     bool doInitialization(CallGraph &CG) override;
90     /// The maximum number of elements to expand, or 0 for unlimited.
91     unsigned maxElements;
92     DenseMap<const Function *, DISubprogram> FunctionDIs;
93   };
94 }
95
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)
103
104 Pass *llvm::createArgumentPromotionPass(unsigned maxElements) {
105   return new ArgPromotion(maxElements);
106 }
107
108 bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
109   bool Changed = false, LocalChange;
110
111   do {  // Iterate until we stop promoting from this SCC.
112     LocalChange = false;
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)) {
116         LocalChange = true;
117         SCC.ReplaceNode(*I, CGN);
118       }
119     }
120     Changed |= LocalChange;               // Remember that we changed something.
121   } while (LocalChange);
122   
123   return Changed;
124 }
125
126 /// \brief Checks if a type could have padding bytes.
127 bool ArgPromotion::isDenselyPacked(Type *type, const DataLayout &DL) {
128
129   // There is no size information, so be conservative.
130   if (!type->isSized())
131     return false;
132
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))
136     return false;
137
138   if (!isa<CompositeType>(type))
139     return true;
140
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);
145
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))
153       return false;
154     if (StartPos != Layout->getElementOffsetInBits(i))
155       return false;
156     StartPos += DL.getTypeAllocSizeInBits(ElTy);
157   }
158
159   return true;
160 }
161
162 /// \brief Checks if the padding bytes of an argument could be accessed.
163 bool ArgPromotion::canPaddingBeAccessed(Argument *arg) {
164
165   assert(arg->hasByValAttr());
166
167   // Track all the pointers to the argument to make sure they are not captured.
168   SmallPtrSet<Value *, 16> PtrValues;
169   PtrValues.insert(arg);
170
171   // Track all of the stores.
172   SmallVector<StoreInst *, 16> Stores;
173
174   // Scan through the uses recursively to make sure the pointer is always used
175   // sanely.
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();
180     WorkList.pop_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)) {
187       return true;
188     }
189   }
190
191 // Check to make sure the pointers aren't captured
192   for (StoreInst *Store : Stores)
193     if (PtrValues.count(Store->getValueOperand()))
194       return true;
195
196   return false;
197 }
198
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.
203 ///
204 CallGraphNode *ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
205   Function *F = CGN->getFunction();
206
207   // Make sure that it is local to this module.
208   if (!F || !F->hasLocalLinkage()) return nullptr;
209
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;
216
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;
225     
226     if (CS.getInstruction()->getParent()->getParent() == F)
227       isSelfRecursive = true;
228   }
229   
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();
237
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();
245
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");
259           continue;
260         }
261         
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()) {
266             AllSimple = false;
267             break;
268           }
269         }
270
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.
274         if (AllSimple) {
275           ByValArgsToTransform.insert(PtrArg);
276           continue;
277         }
278       }
279     }
280
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;
289             break;
290           }
291         }
292         if (RecursiveType)
293           continue;
294       }
295     }
296     
297     // Otherwise, see if we can promote the pointer to its value.
298     if (isSafeToPromoteArgument(PtrArg, PtrArg->hasByValOrInAllocaAttr()))
299       ArgsToPromote.insert(PtrArg);
300   }
301
302   // No promotable pointer arguments.
303   if (ArgsToPromote.empty() && ByValArgsToTransform.empty()) 
304     return nullptr;
305
306   return DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
307 }
308
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();
314
315   unsigned ArgNo = Arg->getArgNo();
316
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()) {
320     CallSite CS(U);
321     assert(CS && "Should only have direct calls!");
322
323     if (!CS.getArgument(ArgNo)->isDereferenceablePointer(DL))
324       return false;
325   }
326   return true;
327 }
328
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.
332 ///
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())
337     return false;
338   return std::equal(Prefix.begin(), Prefix.end(), Longer.begin());
339 }
340
341
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())
348       Low--;
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
351     // prefix exists.
352     //
353     // This load is safe if any prefix of its operands is safe to load.
354     return Low != Set.end() && IsPrefix(*Low, Indices);
355 }
356
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())
368     Low--;
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
376       return;
377
378     // Increment Low, so we can use it as a "insert before" hint
379     ++Low;
380   }
381   // Insert
382   Low = Safe.insert(Low, ToMark);
383   ++Low;
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;
388     ++Low;
389     Safe.erase(Remove);
390   }
391 }
392
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;
401
402   // Quick exit for unused arguments
403   if (Arg->use_empty())
404     return true;
405
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.
408   //
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
413   // valid.
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
417   // original code.
418   //
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.
421   //
422   // This optimization is also safe for InAlloca parameters, because it verifies
423   // that the address isn't captured.
424   GEPIndicesSet SafeToUnconditionallyLoad;
425
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;
429
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));
433
434   // First, iterate the entry block and mark loads of (geps of) arguments as
435   // safe.
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();
440        I != E; ++I)
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();
445         if (V == Arg) {
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();
449                II != IE; ++II)
450             if (ConstantInt *CI = dyn_cast<ConstantInt>(*II))
451               Indices.push_back(CI->getSExtValue());
452             else
453               // We found a non-constant GEP index for this argument? Bail out
454               // right away, can't promote this argument at all.
455               return false;
456
457           // Indices checked out, mark them as safe
458           MarkIndicesSafe(Indices, SafeToUnconditionallyLoad);
459           Indices.clear();
460         }
461       } else if (V == Arg) {
462         // Direct loads are equivalent to a GEP with a single 0 index.
463         MarkIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
464       }
465     }
466
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();
473     Operands.clear();
474     if (LoadInst *LI = dyn_cast<LoadInst>(UR)) {
475       // Don't hack volatile/atomic loads
476       if (!LI->isSimple()) return false;
477       Loads.push_back(LI);
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
483         // them.
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
488         // use?
489         return isSafeToPromoteArgument(Arg, isByValOrInAlloca);
490       }
491
492       // Ensure that all of the indices are constants.
493       for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end();
494         i != e; ++i)
495         if (ConstantInt *C = dyn_cast<ConstantInt>(*i))
496           Operands.push_back(C->getSExtValue());
497         else
498           return false;  // Not a constant operand GEP!
499
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;
505           Loads.push_back(LI);
506         } else {
507           // Other uses than load?
508           return false;
509         }
510     } else {
511       return false;  // Not a load or a GEP.
512     }
513
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))
517       return false;
518
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
521     // to do.
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.
529         return false;
530       }
531       ToPromote.insert(std::move(Operands));
532     }
533   }
534
535   if (Loads.empty()) return true;  // No users, this is a dead argument.
536
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.
541
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;
545
546   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
547
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
550     // the load itself.
551     LoadInst *Load = Loads[i];
552     BasicBlock *BB = Load->getParent();
553
554     AliasAnalysis::Location Loc = AA.getLocation(Load);
555     if (AA.canInstructionRangeModRef(BB->front(), *Load, Loc,
556         AliasAnalysis::Mod))
557       return false;  // Pointer is invalidated!
558
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
561     // loading block.
562     for (BasicBlock *P : predecessors(BB)) {
563       for (BasicBlock *TranspBB : inverse_depth_first_ext(P, TranspBlocks))
564         if (AA.canBasicBlockModify(*TranspBB, Loc))
565           return false;
566     }
567   }
568
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
571   // transformation!
572   return true;
573 }
574
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
577 /// safe to do so.
578 CallGraphNode *ArgPromotion::DoPromotion(Function *F,
579                              SmallPtrSetImpl<Argument*> &ArgsToPromote,
580                              SmallPtrSetImpl<Argument*> &ByValArgsToTransform) {
581
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;
586
587   typedef std::set<IndicesVector> ScalarizeTable;
588
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.
592   //
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.
595   //
596   std::map<Argument*, ScalarizeTable> ScalarizedElements;
597
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;
604
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();
610
611   // Add any return attributes.
612   if (PAL.hasAttributes(AttributeSet::ReturnIndex))
613     AttributesVec.push_back(AttributeSet::get(F->getContext(),
614                                               PAL.getRetAttributes()));
615
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;
619        ++I, ++ArgIndex) {
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);
632         AttributesVec.
633           push_back(AttributeSet::get(F->getContext(), Params.size(), B));
634       }
635     } else if (I->use_empty()) {
636       // Dead argument (which are always marked as promotable)
637       ++NumArgumentsDead;
638     } else {
639       // Okay, this is being promoted. This means that the only uses are loads
640       // or GEPs which are only used by loads
641
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);
647         assert(isa<LoadInst>(UI) || isa<GetElementPtrInst>(UI));
648         IndicesVector Indices;
649         Indices.reserve(UI->getNumOperands() - 1);
650         // Since loads will only have a single operand, and GEPs only a single
651         // non-index operand, this will record direct loads without any indices,
652         // and gep+loads with the GEP indices.
653         for (User::op_iterator II = UI->op_begin() + 1, IE = UI->op_end();
654              II != IE; ++II)
655           Indices.push_back(cast<ConstantInt>(*II)->getSExtValue());
656         // GEPs with a single 0 index can be merged with direct loads
657         if (Indices.size() == 1 && Indices.front() == 0)
658           Indices.clear();
659         ArgIndices.insert(Indices);
660         LoadInst *OrigLoad;
661         if (LoadInst *L = dyn_cast<LoadInst>(UI))
662           OrigLoad = L;
663         else
664           // Take any load, we will use it only to update Alias Analysis
665           OrigLoad = cast<LoadInst>(UI->user_back());
666         OriginalLoads[std::make_pair(I, Indices)] = OrigLoad;
667       }
668
669       // Add a parameter to the function for each element passed in.
670       for (ScalarizeTable::iterator SI = ArgIndices.begin(),
671              E = ArgIndices.end(); SI != E; ++SI) {
672         // not allowed to dereference ->begin() if size() is 0
673         Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
674         assert(Params.back());
675       }
676
677       if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
678         ++NumArgumentsPromoted;
679       else
680         ++NumAggregatesPromoted;
681     }
682   }
683
684   // Add any function attributes.
685   if (PAL.hasAttributes(AttributeSet::FunctionIndex))
686     AttributesVec.push_back(AttributeSet::get(FTy->getContext(),
687                                               PAL.getFnAttributes()));
688
689   Type *RetTy = FTy->getReturnType();
690
691   // Construct the new function type using the new arguments.
692   FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
693
694   // Create the new function body and insert it into the module.
695   Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
696   NF->copyAttributesFrom(F);
697
698   // Patch the pointer to LLVM function in debug info descriptor.
699   auto DI = FunctionDIs.find(F);
700   if (DI != FunctionDIs.end()) {
701     DISubprogram SP = DI->second;
702     SP.replaceFunction(NF);
703     // Ensure the map is updated so it can be reused on subsequent argument
704     // promotions of the same function.
705     FunctionDIs.erase(DI);
706     FunctionDIs[NF] = SP;
707   }
708
709   DEBUG(dbgs() << "ARG PROMOTION:  Promoting to:" << *NF << "\n"
710         << "From: " << *F);
711   
712   // Recompute the parameter attributes list based on the new arguments for
713   // the function.
714   NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec));
715   AttributesVec.clear();
716
717   F->getParent()->getFunctionList().insert(F, NF);
718   NF->takeName(F);
719
720   // Get the alias analysis information that we need to update to reflect our
721   // changes.
722   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
723
724   // Get the callgraph information that we need to update to reflect our
725   // changes.
726   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
727
728   // Get a new callgraph node for NF.
729   CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
730
731   // Loop over all of the callers of the function, transforming the call sites
732   // to pass in the loaded pointers.
733   //
734   SmallVector<Value*, 16> Args;
735   while (!F->use_empty()) {
736     CallSite CS(F->user_back());
737     assert(CS.getCalledFunction() == F);
738     Instruction *Call = CS.getInstruction();
739     const AttributeSet &CallPAL = CS.getAttributes();
740
741     // Add any return attributes.
742     if (CallPAL.hasAttributes(AttributeSet::ReturnIndex))
743       AttributesVec.push_back(AttributeSet::get(F->getContext(),
744                                                 CallPAL.getRetAttributes()));
745
746     // Loop over the operands, inserting GEP and loads in the caller as
747     // appropriate.
748     CallSite::arg_iterator AI = CS.arg_begin();
749     ArgIndex = 1;
750     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
751          I != E; ++I, ++AI, ++ArgIndex)
752       if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
753         Args.push_back(*AI);          // Unmodified argument
754
755         if (CallPAL.hasAttributes(ArgIndex)) {
756           AttrBuilder B(CallPAL, ArgIndex);
757           AttributesVec.
758             push_back(AttributeSet::get(F->getContext(), Args.size(), B));
759         }
760       } else if (ByValArgsToTransform.count(I)) {
761         // Emit a GEP and load for each element of the struct.
762         Type *AgTy = cast<PointerType>(I->getType())->getElementType();
763         StructType *STy = cast<StructType>(AgTy);
764         Value *Idxs[2] = {
765               ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr };
766         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
767           Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
768           Value *Idx = GetElementPtrInst::Create(*AI, Idxs,
769                                                  (*AI)->getName()+"."+utostr(i),
770                                                  Call);
771           // TODO: Tell AA about the new values?
772           Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
773         }
774       } else if (!I->use_empty()) {
775         // Non-dead argument: insert GEPs and loads as appropriate.
776         ScalarizeTable &ArgIndices = ScalarizedElements[I];
777         // Store the Value* version of the indices in here, but declare it now
778         // for reuse.
779         std::vector<Value*> Ops;
780         for (ScalarizeTable::iterator SI = ArgIndices.begin(),
781                E = ArgIndices.end(); SI != E; ++SI) {
782           Value *V = *AI;
783           LoadInst *OrigLoad = OriginalLoads[std::make_pair(I, *SI)];
784           if (!SI->empty()) {
785             Ops.reserve(SI->size());
786             Type *ElTy = V->getType();
787             for (IndicesVector::const_iterator II = SI->begin(),
788                  IE = SI->end(); II != IE; ++II) {
789               // Use i32 to index structs, and i64 for others (pointers/arrays).
790               // This satisfies GEP constraints.
791               Type *IdxTy = (ElTy->isStructTy() ?
792                     Type::getInt32Ty(F->getContext()) : 
793                     Type::getInt64Ty(F->getContext()));
794               Ops.push_back(ConstantInt::get(IdxTy, *II));
795               // Keep track of the type we're currently indexing.
796               ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(*II);
797             }
798             // And create a GEP to extract those indices.
799             V = GetElementPtrInst::Create(V, Ops, V->getName()+".idx", Call);
800             Ops.clear();
801             AA.copyValue(OrigLoad->getOperand(0), V);
802           }
803           // Since we're replacing a load make sure we take the alignment
804           // of the previous load.
805           LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call);
806           newLoad->setAlignment(OrigLoad->getAlignment());
807           // Transfer the AA info too.
808           AAMDNodes AAInfo;
809           OrigLoad->getAAMetadata(AAInfo);
810           newLoad->setAAMetadata(AAInfo);
811
812           Args.push_back(newLoad);
813           AA.copyValue(OrigLoad, Args.back());
814         }
815       }
816
817     // Push any varargs arguments on the list.
818     for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
819       Args.push_back(*AI);
820       if (CallPAL.hasAttributes(ArgIndex)) {
821         AttrBuilder B(CallPAL, ArgIndex);
822         AttributesVec.
823           push_back(AttributeSet::get(F->getContext(), Args.size(), B));
824       }
825     }
826
827     // Add any function attributes.
828     if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
829       AttributesVec.push_back(AttributeSet::get(Call->getContext(),
830                                                 CallPAL.getFnAttributes()));
831
832     Instruction *New;
833     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
834       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
835                                Args, "", Call);
836       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
837       cast<InvokeInst>(New)->setAttributes(AttributeSet::get(II->getContext(),
838                                                             AttributesVec));
839     } else {
840       New = CallInst::Create(NF, Args, "", Call);
841       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
842       cast<CallInst>(New)->setAttributes(AttributeSet::get(New->getContext(),
843                                                           AttributesVec));
844       if (cast<CallInst>(Call)->isTailCall())
845         cast<CallInst>(New)->setTailCall();
846     }
847     New->setDebugLoc(Call->getDebugLoc());
848     Args.clear();
849     AttributesVec.clear();
850
851     // Update the alias analysis implementation to know that we are replacing
852     // the old call with a new one.
853     AA.replaceWithNewValue(Call, New);
854
855     // Update the callgraph to know that the callsite has been transformed.
856     CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
857     CalleeNode->replaceCallEdge(Call, New, NF_CGN);
858
859     if (!Call->use_empty()) {
860       Call->replaceAllUsesWith(New);
861       New->takeName(Call);
862     }
863
864     // Finally, remove the old call from the program, reducing the use-count of
865     // F.
866     Call->eraseFromParent();
867   }
868
869   // Since we have now created the new function, splice the body of the old
870   // function right into the new function, leaving the old rotting hulk of the
871   // function empty.
872   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
873
874   // Loop over the argument list, transferring uses of the old arguments over to
875   // the new arguments, also transferring over the names as well.
876   //
877   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
878        I2 = NF->arg_begin(); I != E; ++I) {
879     if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
880       // If this is an unmodified argument, move the name and users over to the
881       // new version.
882       I->replaceAllUsesWith(I2);
883       I2->takeName(I);
884       AA.replaceWithNewValue(I, I2);
885       ++I2;
886       continue;
887     }
888
889     if (ByValArgsToTransform.count(I)) {
890       // In the callee, we create an alloca, and store each of the new incoming
891       // arguments into the alloca.
892       Instruction *InsertPt = NF->begin()->begin();
893
894       // Just add all the struct element types.
895       Type *AgTy = cast<PointerType>(I->getType())->getElementType();
896       Value *TheAlloca = new AllocaInst(AgTy, nullptr, "", InsertPt);
897       StructType *STy = cast<StructType>(AgTy);
898       Value *Idxs[2] = {
899             ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr };
900
901       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
902         Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
903         Value *Idx = 
904           GetElementPtrInst::Create(TheAlloca, Idxs,
905                                     TheAlloca->getName()+"."+Twine(i), 
906                                     InsertPt);
907         I2->setName(I->getName()+"."+Twine(i));
908         new StoreInst(I2++, Idx, InsertPt);
909       }
910
911       // Anything that used the arg should now use the alloca.
912       I->replaceAllUsesWith(TheAlloca);
913       TheAlloca->takeName(I);
914       AA.replaceWithNewValue(I, TheAlloca);
915
916       // If the alloca is used in a call, we must clear the tail flag since
917       // the callee now uses an alloca from the caller.
918       for (User *U : TheAlloca->users()) {
919         CallInst *Call = dyn_cast<CallInst>(U);
920         if (!Call)
921           continue;
922         Call->setTailCall(false);
923       }
924       continue;
925     }
926
927     if (I->use_empty()) {
928       AA.deleteValue(I);
929       continue;
930     }
931
932     // Otherwise, if we promoted this argument, then all users are load
933     // instructions (or GEPs with only load users), and all loads should be
934     // using the new argument that we added.
935     ScalarizeTable &ArgIndices = ScalarizedElements[I];
936
937     while (!I->use_empty()) {
938       if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) {
939         assert(ArgIndices.begin()->empty() &&
940                "Load element should sort to front!");
941         I2->setName(I->getName()+".val");
942         LI->replaceAllUsesWith(I2);
943         AA.replaceWithNewValue(LI, I2);
944         LI->eraseFromParent();
945         DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
946               << "' in function '" << F->getName() << "'\n");
947       } else {
948         GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->user_back());
949         IndicesVector Operands;
950         Operands.reserve(GEP->getNumIndices());
951         for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
952              II != IE; ++II)
953           Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
954
955         // GEPs with a single 0 index can be merged with direct loads
956         if (Operands.size() == 1 && Operands.front() == 0)
957           Operands.clear();
958
959         Function::arg_iterator TheArg = I2;
960         for (ScalarizeTable::iterator It = ArgIndices.begin();
961              *It != Operands; ++It, ++TheArg) {
962           assert(It != ArgIndices.end() && "GEP not handled??");
963         }
964
965         std::string NewName = I->getName();
966         for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
967             NewName += "." + utostr(Operands[i]);
968         }
969         NewName += ".val";
970         TheArg->setName(NewName);
971
972         DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
973               << "' of function '" << NF->getName() << "'\n");
974
975         // All of the uses must be load instructions.  Replace them all with
976         // the argument specified by ArgNo.
977         while (!GEP->use_empty()) {
978           LoadInst *L = cast<LoadInst>(GEP->user_back());
979           L->replaceAllUsesWith(TheArg);
980           AA.replaceWithNewValue(L, TheArg);
981           L->eraseFromParent();
982         }
983         AA.deleteValue(GEP);
984         GEP->eraseFromParent();
985       }
986     }
987
988     // Increment I2 past all of the arguments added for this promoted pointer.
989     std::advance(I2, ArgIndices.size());
990   }
991
992   // Tell the alias analysis that the old function is about to disappear.
993   AA.replaceWithNewValue(F, NF);
994
995   
996   NF_CGN->stealCalledFunctionsFrom(CG[F]);
997   
998   // Now that the old function is dead, delete it.  If there is a dangling
999   // reference to the CallgraphNode, just leave the dead function around for
1000   // someone else to nuke.
1001   CallGraphNode *CGN = CG[F];
1002   if (CGN->getNumReferences() == 0)
1003     delete CG.removeFunctionFromModule(CGN);
1004   else
1005     F->setLinkage(Function::ExternalLinkage);
1006   
1007   return NF_CGN;
1008 }
1009
1010 bool ArgPromotion::doInitialization(CallGraph &CG) {
1011   FunctionDIs = makeSubprogramMap(CG.getModule());
1012   return CallGraphSCCPass::doInitialization(CG);
1013 }