d2f407b9e55559526576709be48dab704523bf76
[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), DL(nullptr), 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     const DataLayout *DL;
80   private:
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);
86     
87     using llvm::Pass::doInitialization;
88     bool doInitialization(CallGraph &CG) override;
89     /// The maximum number of elements to expand, or 0 for unlimited.
90     unsigned maxElements;
91     DenseMap<const Function *, DISubprogram> FunctionDIs;
92   };
93 }
94
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)
102
103 Pass *llvm::createArgumentPromotionPass(unsigned maxElements) {
104   return new ArgPromotion(maxElements);
105 }
106
107 bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
108   bool Changed = false, LocalChange;
109
110   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
111   DL = DLP ? &DLP->getDataLayout() : nullptr;
112
113   do {  // Iterate until we stop promoting from this SCC.
114     LocalChange = false;
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)) {
118         LocalChange = true;
119         SCC.ReplaceNode(*I, CGN);
120       }
121     }
122     Changed |= LocalChange;               // Remember that we changed something.
123   } while (LocalChange);
124   
125   return Changed;
126 }
127
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.
132 ///
133 CallGraphNode *ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
134   Function *F = CGN->getFunction();
135
136   // Make sure that it is local to this module.
137   if (!F || !F->hasLocalLinkage()) return nullptr;
138
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;
145
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;
154     
155     if (CS.getInstruction()->getParent()->getParent() == F)
156       isSelfRecursive = true;
157   }
158   
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;
165
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();
173
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
176     // inalloca.
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");
183           continue;
184         }
185         
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()) {
190             AllSimple = false;
191             break;
192           }
193         }
194
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.
198         if (AllSimple) {
199           ByValArgsToTransform.insert(PtrArg);
200           continue;
201         }
202       }
203     }
204
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;
213             break;
214           }
215         }
216         if (RecursiveType)
217           continue;
218       }
219     }
220     
221     // Otherwise, see if we can promote the pointer to its value.
222     if (isSafeToPromoteArgument(PtrArg, PtrArg->hasByValOrInAllocaAttr()))
223       ArgsToPromote.insert(PtrArg);
224   }
225
226   // No promotable pointer arguments.
227   if (ArgsToPromote.empty() && ByValArgsToTransform.empty()) 
228     return nullptr;
229
230   return DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
231 }
232
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();
238
239   unsigned ArgNo = Arg->getArgNo();
240
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()) {
244     CallSite CS(U);
245     assert(CS && "Should only have direct calls!");
246
247     if (!CS.getArgument(ArgNo)->isDereferenceablePointer(DL))
248       return false;
249   }
250   return true;
251 }
252
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.
256 ///
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())
261     return false;
262   return std::equal(Prefix.begin(), Prefix.end(), Longer.begin());
263 }
264
265
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())
272       Low--;
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
275     // prefix exists.
276     //
277     // This load is safe if any prefix of its operands is safe to load.
278     return Low != Set.end() && IsPrefix(*Low, Indices);
279 }
280
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())
292     Low--;
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
300       return;
301
302     // Increment Low, so we can use it as a "insert before" hint
303     ++Low;
304   }
305   // Insert
306   Low = Safe.insert(Low, ToMark);
307   ++Low;
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;
312     ++Low;
313     Safe.erase(Remove);
314   }
315 }
316
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;
325
326   // Quick exit for unused arguments
327   if (Arg->use_empty())
328     return true;
329
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.
332   //
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
337   // valid.
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
341   // original code.
342   //
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.
345   //
346   // This optimization is also safe for InAlloca parameters, because it verifies
347   // that the address isn't captured.
348   GEPIndicesSet SafeToUnconditionallyLoad;
349
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;
353
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));
357
358   // First, iterate the entry block and mark loads of (geps of) arguments as
359   // safe.
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();
364        I != E; ++I)
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();
369         if (V == Arg) {
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();
373                II != IE; ++II)
374             if (ConstantInt *CI = dyn_cast<ConstantInt>(*II))
375               Indices.push_back(CI->getSExtValue());
376             else
377               // We found a non-constant GEP index for this argument? Bail out
378               // right away, can't promote this argument at all.
379               return false;
380
381           // Indices checked out, mark them as safe
382           MarkIndicesSafe(Indices, SafeToUnconditionallyLoad);
383           Indices.clear();
384         }
385       } else if (V == Arg) {
386         // Direct loads are equivalent to a GEP with a single 0 index.
387         MarkIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
388       }
389     }
390
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();
397     Operands.clear();
398     if (LoadInst *LI = dyn_cast<LoadInst>(UR)) {
399       // Don't hack volatile/atomic loads
400       if (!LI->isSimple()) return false;
401       Loads.push_back(LI);
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
407         // them.
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
412         // use?
413         return isSafeToPromoteArgument(Arg, isByValOrInAlloca);
414       }
415
416       // Ensure that all of the indices are constants.
417       for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end();
418         i != e; ++i)
419         if (ConstantInt *C = dyn_cast<ConstantInt>(*i))
420           Operands.push_back(C->getSExtValue());
421         else
422           return false;  // Not a constant operand GEP!
423
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;
429           Loads.push_back(LI);
430         } else {
431           // Other uses than load?
432           return false;
433         }
434     } else {
435       return false;  // Not a load or a GEP.
436     }
437
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))
441       return false;
442
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
445     // to do.
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.
453         return false;
454       }
455       ToPromote.insert(Operands);
456     }
457   }
458
459   if (Loads.empty()) return true;  // No users, this is a dead argument.
460
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.
465
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;
469
470   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
471
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
474     // the load itself.
475     LoadInst *Load = Loads[i];
476     BasicBlock *BB = Load->getParent();
477
478     AliasAnalysis::Location Loc = AA.getLocation(Load);
479     if (AA.canInstructionRangeModify(BB->front(), *Load, Loc))
480       return false;  // Pointer is invalidated!
481
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
484     // loading block.
485     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
486       BasicBlock *P = *PI;
487       for (BasicBlock *TranspBB : inverse_depth_first_ext(P, TranspBlocks))
488         if (AA.canBasicBlockModify(*TranspBB, Loc))
489           return false;
490     }
491   }
492
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
495   // transformation!
496   return true;
497 }
498
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
501 /// safe to do so.
502 CallGraphNode *ArgPromotion::DoPromotion(Function *F,
503                              SmallPtrSetImpl<Argument*> &ArgsToPromote,
504                              SmallPtrSetImpl<Argument*> &ByValArgsToTransform) {
505
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;
510
511   typedef std::set<IndicesVector> ScalarizeTable;
512
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.
516   //
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.
519   //
520   std::map<Argument*, ScalarizeTable> ScalarizedElements;
521
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;
528
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();
534
535   // Add any return attributes.
536   if (PAL.hasAttributes(AttributeSet::ReturnIndex))
537     AttributesVec.push_back(AttributeSet::get(F->getContext(),
538                                               PAL.getRetAttributes()));
539
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;
543        ++I, ++ArgIndex) {
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);
557         AttributesVec.
558           push_back(AttributeSet::get(F->getContext(), Params.size(), B));
559       }
560     } else if (I->use_empty()) {
561       // Dead argument (which are always marked as promotable)
562       ++NumArgumentsDead;
563     } else {
564       // Okay, this is being promoted. This means that the only uses are loads
565       // or GEPs which are only used by loads
566
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();
579              II != IE; ++II)
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)
583           Indices.clear();
584         ArgIndices.insert(Indices);
585         LoadInst *OrigLoad;
586         if (LoadInst *L = dyn_cast<LoadInst>(UI))
587           OrigLoad = L;
588         else
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;
592       }
593
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());
600       }
601
602       if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
603         ++NumArgumentsPromoted;
604       else
605         ++NumAggregatesPromoted;
606     }
607   }
608
609   // Add any function attributes.
610   if (PAL.hasAttributes(AttributeSet::FunctionIndex))
611     AttributesVec.push_back(AttributeSet::get(FTy->getContext(),
612                                               PAL.getFnAttributes()));
613
614   Type *RetTy = FTy->getReturnType();
615
616   // Construct the new function type using the new arguments.
617   FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
618
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);
622
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;
630   }
631
632   DEBUG(dbgs() << "ARG PROMOTION:  Promoting to:" << *NF << "\n"
633         << "From: " << *F);
634   
635   // Recompute the parameter attributes list based on the new arguments for
636   // the function.
637   NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec));
638   AttributesVec.clear();
639
640   F->getParent()->getFunctionList().insert(F, NF);
641   NF->takeName(F);
642
643   // Get the alias analysis information that we need to update to reflect our
644   // changes.
645   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
646
647   // Get the callgraph information that we need to update to reflect our
648   // changes.
649   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
650
651   // Get a new callgraph node for NF.
652   CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
653
654   // Loop over all of the callers of the function, transforming the call sites
655   // to pass in the loaded pointers.
656   //
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();
663
664     // Add any return attributes.
665     if (CallPAL.hasAttributes(AttributeSet::ReturnIndex))
666       AttributesVec.push_back(AttributeSet::get(F->getContext(),
667                                                 CallPAL.getRetAttributes()));
668
669     // Loop over the operands, inserting GEP and loads in the caller as
670     // appropriate.
671     CallSite::arg_iterator AI = CS.arg_begin();
672     ArgIndex = 1;
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
677
678         if (CallPAL.hasAttributes(ArgIndex)) {
679           AttrBuilder B(CallPAL, ArgIndex);
680           AttributesVec.
681             push_back(AttributeSet::get(F->getContext(), Args.size(), B));
682         }
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);
687         Value *Idxs[2] = {
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),
693                                                  Call);
694           // TODO: Tell AA about the new values?
695           Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
696         }
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
701         // for reuse.
702         std::vector<Value*> Ops;
703         for (ScalarizeTable::iterator SI = ArgIndices.begin(),
704                E = ArgIndices.end(); SI != E; ++SI) {
705           Value *V = *AI;
706           LoadInst *OrigLoad = OriginalLoads[std::make_pair(I, *SI)];
707           if (!SI->empty()) {
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);
720             }
721             // And create a GEP to extract those indices.
722             V = GetElementPtrInst::Create(V, Ops, V->getName()+".idx", Call);
723             Ops.clear();
724             AA.copyValue(OrigLoad->getOperand(0), V);
725           }
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.
731           AAMDNodes AAInfo;
732           OrigLoad->getAAMetadata(AAInfo);
733           newLoad->setAAMetadata(AAInfo);
734
735           Args.push_back(newLoad);
736           AA.copyValue(OrigLoad, Args.back());
737         }
738       }
739
740     // Push any varargs arguments on the list.
741     for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
742       Args.push_back(*AI);
743       if (CallPAL.hasAttributes(ArgIndex)) {
744         AttrBuilder B(CallPAL, ArgIndex);
745         AttributesVec.
746           push_back(AttributeSet::get(F->getContext(), Args.size(), B));
747       }
748     }
749
750     // Add any function attributes.
751     if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
752       AttributesVec.push_back(AttributeSet::get(Call->getContext(),
753                                                 CallPAL.getFnAttributes()));
754
755     Instruction *New;
756     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
757       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
758                                Args, "", Call);
759       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
760       cast<InvokeInst>(New)->setAttributes(AttributeSet::get(II->getContext(),
761                                                             AttributesVec));
762     } else {
763       New = CallInst::Create(NF, Args, "", Call);
764       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
765       cast<CallInst>(New)->setAttributes(AttributeSet::get(New->getContext(),
766                                                           AttributesVec));
767       if (cast<CallInst>(Call)->isTailCall())
768         cast<CallInst>(New)->setTailCall();
769     }
770     New->setDebugLoc(Call->getDebugLoc());
771     Args.clear();
772     AttributesVec.clear();
773
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);
777
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);
781
782     if (!Call->use_empty()) {
783       Call->replaceAllUsesWith(New);
784       New->takeName(Call);
785     }
786
787     // Finally, remove the old call from the program, reducing the use-count of
788     // F.
789     Call->eraseFromParent();
790   }
791
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
794   // function empty.
795   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
796
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.
799   //
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
804       // new version.
805       I->replaceAllUsesWith(I2);
806       I2->takeName(I);
807       AA.replaceWithNewValue(I, I2);
808       ++I2;
809       continue;
810     }
811
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();
816
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);
821       Value *Idxs[2] = {
822             ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr };
823
824       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
825         Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
826         Value *Idx = 
827           GetElementPtrInst::Create(TheAlloca, Idxs,
828                                     TheAlloca->getName()+"."+Twine(i), 
829                                     InsertPt);
830         I2->setName(I->getName()+"."+Twine(i));
831         new StoreInst(I2++, Idx, InsertPt);
832       }
833
834       // Anything that used the arg should now use the alloca.
835       I->replaceAllUsesWith(TheAlloca);
836       TheAlloca->takeName(I);
837       AA.replaceWithNewValue(I, TheAlloca);
838
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);
843         if (!Call)
844           continue;
845         Call->setTailCall(false);
846       }
847       continue;
848     }
849
850     if (I->use_empty()) {
851       AA.deleteValue(I);
852       continue;
853     }
854
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];
859
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");
870       } else {
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();
875              II != IE; ++II)
876           Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
877
878         // GEPs with a single 0 index can be merged with direct loads
879         if (Operands.size() == 1 && Operands.front() == 0)
880           Operands.clear();
881
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??");
886         }
887
888         std::string NewName = I->getName();
889         for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
890             NewName += "." + utostr(Operands[i]);
891         }
892         NewName += ".val";
893         TheArg->setName(NewName);
894
895         DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
896               << "' of function '" << NF->getName() << "'\n");
897
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();
905         }
906         AA.deleteValue(GEP);
907         GEP->eraseFromParent();
908       }
909     }
910
911     // Increment I2 past all of the arguments added for this promoted pointer.
912     std::advance(I2, ArgIndices.size());
913   }
914
915   // Tell the alias analysis that the old function is about to disappear.
916   AA.replaceWithNewValue(F, NF);
917
918   
919   NF_CGN->stealCalledFunctionsFrom(CG[F]);
920   
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);
927   else
928     F->setLinkage(Function::ExternalLinkage);
929   
930   return NF_CGN;
931 }
932
933 bool ArgPromotion::doInitialization(CallGraph &CG) {
934   FunctionDIs = makeSubprogramMap(CG.getModule());
935   return CallGraphSCCPass::doInitialization(CG);
936 }