1 //===- ArgumentPromotion.cpp - Promote by-reference arguments -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass promotes "by reference" arguments to be "by value" arguments.  In
10 // practice, this means looking for internal functions that have pointer
11 // arguments.  If it can prove, through the use of alias analysis, that an
12 // argument is *only* loaded, then it can pass the value into the function
13 // instead of the address of the value.  This can cause recursive simplification
14 // of code and lead to the elimination of allocas (especially in C++ template
15 // code like the STL).
16 //
17 // This pass also handles aggregate arguments that are passed into a function,
18 // scalarizing them if the elements of the aggregate are only loaded.  Note that
19 // by default it refuses to scalarize aggregates which would require passing in
20 // more than three operands to the function, because passing thousands of
21 // operands for a large array or structure is unprofitable! This limit can be
22 // configured or disabled, however.
23 //
24 // Note that this transformation could also be done for arguments that are only
25 // stored to (returning the value instead), but does not currently.  This case
26 // would be best handled when and if LLVM begins supporting multiple return
27 // values from functions.
28 //
29 //===----------------------------------------------------------------------===//
30 
31 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
32 #include "llvm/ADT/DepthFirstIterator.h"
33 #include "llvm/ADT/None.h"
34 #include "llvm/ADT/Optional.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/ScopeExit.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Analysis/AliasAnalysis.h"
42 #include "llvm/Analysis/AssumptionCache.h"
43 #include "llvm/Analysis/BasicAliasAnalysis.h"
44 #include "llvm/Analysis/CGSCCPassManager.h"
45 #include "llvm/Analysis/CallGraph.h"
46 #include "llvm/Analysis/CallGraphSCCPass.h"
47 #include "llvm/Analysis/LazyCallGraph.h"
48 #include "llvm/Analysis/Loads.h"
49 #include "llvm/Analysis/MemoryLocation.h"
50 #include "llvm/Analysis/TargetLibraryInfo.h"
51 #include "llvm/Analysis/TargetTransformInfo.h"
52 #include "llvm/IR/Argument.h"
53 #include "llvm/IR/Attributes.h"
54 #include "llvm/IR/BasicBlock.h"
55 #include "llvm/IR/CFG.h"
56 #include "llvm/IR/Constants.h"
57 #include "llvm/IR/DataLayout.h"
58 #include "llvm/IR/DerivedTypes.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/Metadata.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/NoFolder.h"
67 #include "llvm/IR/PassManager.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/InitializePasses.h"
73 #include "llvm/Pass.h"
74 #include "llvm/Support/Casting.h"
75 #include "llvm/Support/Debug.h"
76 #include "llvm/Support/FormatVariadic.h"
77 #include "llvm/Support/raw_ostream.h"
78 #include "llvm/Transforms/IPO.h"
79 #include <algorithm>
80 #include <cassert>
81 #include <cstdint>
82 #include <functional>
83 #include <iterator>
84 #include <map>
85 #include <set>
86 #include <string>
87 #include <utility>
88 #include <vector>
89 
90 using namespace llvm;
91 
92 #define DEBUG_TYPE "argpromotion"
93 
94 STATISTIC(NumArgumentsPromoted, "Number of pointer arguments promoted");
95 STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
96 STATISTIC(NumByValArgsPromoted, "Number of byval arguments promoted");
97 STATISTIC(NumArgumentsDead, "Number of dead pointer args eliminated");
98 
99 /// A vector used to hold the indices of a single GEP instruction
100 using IndicesVector = std::vector<uint64_t>;
101 
102 /// DoPromotion - This method actually performs the promotion of the specified
103 /// arguments, and returns the new function.  At this point, we know that it's
104 /// safe to do so.
105 static Function *
106 doPromotion(Function *F, SmallPtrSetImpl<Argument *> &ArgsToPromote,
107             SmallPtrSetImpl<Argument *> &ByValArgsToTransform,
108             Optional<function_ref<void(CallBase &OldCS, CallBase &NewCS)>>
109                 ReplaceCallSite) {
110   // Start by computing a new prototype for the function, which is the same as
111   // the old function, but has modified arguments.
112   FunctionType *FTy = F->getFunctionType();
113   std::vector<Type *> Params;
114 
115   using ScalarizeTable = std::set<std::pair<Type *, IndicesVector>>;
116 
117   // ScalarizedElements - If we are promoting a pointer that has elements
118   // accessed out of it, keep track of which elements are accessed so that we
119   // can add one argument for each.
120   //
121   // Arguments that are directly loaded will have a zero element value here, to
122   // handle cases where there are both a direct load and GEP accesses.
123   std::map<Argument *, ScalarizeTable> ScalarizedElements;
124 
125   // OriginalLoads - Keep track of a representative load instruction from the
126   // original function so that we can tell the alias analysis implementation
127   // what the new GEP/Load instructions we are inserting look like.
128   // We need to keep the original loads for each argument and the elements
129   // of the argument that are accessed.
130   std::map<std::pair<Argument *, IndicesVector>, LoadInst *> OriginalLoads;
131 
132   // Attribute - Keep track of the parameter attributes for the arguments
133   // that we are *not* promoting. For the ones that we do promote, the parameter
134   // attributes are lost
135   SmallVector<AttributeSet, 8> ArgAttrVec;
136   AttributeList PAL = F->getAttributes();
137 
138   // First, determine the new argument list
139   unsigned ArgNo = 0;
140   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
141        ++I, ++ArgNo) {
142     if (ByValArgsToTransform.count(&*I)) {
143       // Simple byval argument? Just add all the struct element types.
144       Type *AgTy = cast<PointerType>(I->getType())->getElementType();
145       StructType *STy = cast<StructType>(AgTy);
146       Params.insert(Params.end(), STy->element_begin(), STy->element_end());
147       ArgAttrVec.insert(ArgAttrVec.end(), STy->getNumElements(),
148                         AttributeSet());
149       ++NumByValArgsPromoted;
150     } else if (!ArgsToPromote.count(&*I)) {
151       // Unchanged argument
152       Params.push_back(I->getType());
153       ArgAttrVec.push_back(PAL.getParamAttributes(ArgNo));
154     } else if (I->use_empty()) {
155       // Dead argument (which are always marked as promotable)
156       ++NumArgumentsDead;
157     } else {
158       // Okay, this is being promoted. This means that the only uses are loads
159       // or GEPs which are only used by loads
160 
161       // In this table, we will track which indices are loaded from the argument
162       // (where direct loads are tracked as no indices).
163       ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
164       for (User *U : I->users()) {
165         Instruction *UI = cast<Instruction>(U);
166         Type *SrcTy;
167         if (LoadInst *L = dyn_cast<LoadInst>(UI))
168           SrcTy = L->getType();
169         else
170           SrcTy = cast<GetElementPtrInst>(UI)->getSourceElementType();
171         IndicesVector Indices;
172         Indices.reserve(UI->getNumOperands() - 1);
173         // Since loads will only have a single operand, and GEPs only a single
174         // non-index operand, this will record direct loads without any indices,
175         // and gep+loads with the GEP indices.
176         for (User::op_iterator II = UI->op_begin() + 1, IE = UI->op_end();
177              II != IE; ++II)
178           Indices.push_back(cast<ConstantInt>(*II)->getSExtValue());
179         // GEPs with a single 0 index can be merged with direct loads
180         if (Indices.size() == 1 && Indices.front() == 0)
181           Indices.clear();
182         ArgIndices.insert(std::make_pair(SrcTy, Indices));
183         LoadInst *OrigLoad;
184         if (LoadInst *L = dyn_cast<LoadInst>(UI))
185           OrigLoad = L;
186         else
187           // Take any load, we will use it only to update Alias Analysis
188           OrigLoad = cast<LoadInst>(UI->user_back());
189         OriginalLoads[std::make_pair(&*I, Indices)] = OrigLoad;
190       }
191 
192       // Add a parameter to the function for each element passed in.
193       for (const auto &ArgIndex : ArgIndices) {
194         // not allowed to dereference ->begin() if size() is 0
195         Params.push_back(GetElementPtrInst::getIndexedType(
196             cast<PointerType>(I->getType())->getElementType(),
197             ArgIndex.second));
198         ArgAttrVec.push_back(AttributeSet());
199         assert(Params.back());
200       }
201 
202       if (ArgIndices.size() == 1 && ArgIndices.begin()->second.empty())
203         ++NumArgumentsPromoted;
204       else
205         ++NumAggregatesPromoted;
206     }
207   }
208 
209   Type *RetTy = FTy->getReturnType();
210 
211   // Construct the new function type using the new arguments.
212   FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
213 
214   // Create the new function body and insert it into the module.
215   Function *NF = Function::Create(NFTy, F->getLinkage(), F->getAddressSpace(),
216                                   F->getName());
217   NF->copyAttributesFrom(F);
218 
219   // Patch the pointer to LLVM function in debug info descriptor.
220   NF->setSubprogram(F->getSubprogram());
221   F->setSubprogram(nullptr);
222 
223   LLVM_DEBUG(dbgs() << "ARG PROMOTION:  Promoting to:" << *NF << "\n"
224                     << "From: " << *F);
225 
226   // Recompute the parameter attributes list based on the new arguments for
227   // the function.
228   NF->setAttributes(AttributeList::get(F->getContext(), PAL.getFnAttributes(),
229                                        PAL.getRetAttributes(), ArgAttrVec));
230   ArgAttrVec.clear();
231 
232   F->getParent()->getFunctionList().insert(F->getIterator(), NF);
233   NF->takeName(F);
234 
235   // Loop over all of the callers of the function, transforming the call sites
236   // to pass in the loaded pointers.
237   //
238   SmallVector<Value *, 16> Args;
239   while (!F->use_empty()) {
240     CallBase &CB = cast<CallBase>(*F->user_back());
241     assert(CB.getCalledFunction() == F);
242     const AttributeList &CallPAL = CB.getAttributes();
243     IRBuilder<NoFolder> IRB(&CB);
244 
245     // Loop over the operands, inserting GEP and loads in the caller as
246     // appropriate.
247     auto AI = CB.arg_begin();
248     ArgNo = 0;
249     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
250          ++I, ++AI, ++ArgNo)
251       if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
252         Args.push_back(*AI); // Unmodified argument
253         ArgAttrVec.push_back(CallPAL.getParamAttributes(ArgNo));
254       } else if (ByValArgsToTransform.count(&*I)) {
255         // Emit a GEP and load for each element of the struct.
256         Type *AgTy = cast<PointerType>(I->getType())->getElementType();
257         StructType *STy = cast<StructType>(AgTy);
258         Value *Idxs[2] = {
259             ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr};
260         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
261           Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
262           auto *Idx =
263               IRB.CreateGEP(STy, *AI, Idxs, (*AI)->getName() + "." + Twine(i));
264           // TODO: Tell AA about the new values?
265           Args.push_back(IRB.CreateLoad(STy->getElementType(i), Idx,
266                                         Idx->getName() + ".val"));
267           ArgAttrVec.push_back(AttributeSet());
268         }
269       } else if (!I->use_empty()) {
270         // Non-dead argument: insert GEPs and loads as appropriate.
271         ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
272         // Store the Value* version of the indices in here, but declare it now
273         // for reuse.
274         std::vector<Value *> Ops;
275         for (const auto &ArgIndex : ArgIndices) {
276           Value *V = *AI;
277           LoadInst *OrigLoad =
278               OriginalLoads[std::make_pair(&*I, ArgIndex.second)];
279           if (!ArgIndex.second.empty()) {
280             Ops.reserve(ArgIndex.second.size());
281             Type *ElTy = V->getType();
282             for (auto II : ArgIndex.second) {
283               // Use i32 to index structs, and i64 for others (pointers/arrays).
284               // This satisfies GEP constraints.
285               Type *IdxTy =
286                   (ElTy->isStructTy() ? Type::getInt32Ty(F->getContext())
287                                       : Type::getInt64Ty(F->getContext()));
288               Ops.push_back(ConstantInt::get(IdxTy, II));
289               // Keep track of the type we're currently indexing.
290               if (auto *ElPTy = dyn_cast<PointerType>(ElTy))
291                 ElTy = ElPTy->getElementType();
292               else
293                 ElTy = GetElementPtrInst::getTypeAtIndex(ElTy, II);
294             }
295             // And create a GEP to extract those indices.
296             V = IRB.CreateGEP(ArgIndex.first, V, Ops, V->getName() + ".idx");
297             Ops.clear();
298           }
299           // Since we're replacing a load make sure we take the alignment
300           // of the previous load.
301           LoadInst *newLoad =
302               IRB.CreateLoad(OrigLoad->getType(), V, V->getName() + ".val");
303           newLoad->setAlignment(OrigLoad->getAlign());
304           // Transfer the AA info too.
305           AAMDNodes AAInfo;
306           OrigLoad->getAAMetadata(AAInfo);
307           newLoad->setAAMetadata(AAInfo);
308 
309           Args.push_back(newLoad);
310           ArgAttrVec.push_back(AttributeSet());
311         }
312       }
313 
314     // Push any varargs arguments on the list.
315     for (; AI != CB.arg_end(); ++AI, ++ArgNo) {
316       Args.push_back(*AI);
317       ArgAttrVec.push_back(CallPAL.getParamAttributes(ArgNo));
318     }
319 
320     SmallVector<OperandBundleDef, 1> OpBundles;
321     CB.getOperandBundlesAsDefs(OpBundles);
322 
323     CallBase *NewCS = nullptr;
324     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
325       NewCS = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
326                                  Args, OpBundles, "", &CB);
327     } else {
328       auto *NewCall = CallInst::Create(NF, Args, OpBundles, "", &CB);
329       NewCall->setTailCallKind(cast<CallInst>(&CB)->getTailCallKind());
330       NewCS = NewCall;
331     }
332     NewCS->setCallingConv(CB.getCallingConv());
333     NewCS->setAttributes(
334         AttributeList::get(F->getContext(), CallPAL.getFnAttributes(),
335                            CallPAL.getRetAttributes(), ArgAttrVec));
336     NewCS->copyMetadata(CB, {LLVMContext::MD_prof, LLVMContext::MD_dbg});
337     Args.clear();
338     ArgAttrVec.clear();
339 
340     // Update the callgraph to know that the callsite has been transformed.
341     if (ReplaceCallSite)
342       (*ReplaceCallSite)(CB, *NewCS);
343 
344     if (!CB.use_empty()) {
345       CB.replaceAllUsesWith(NewCS);
346       NewCS->takeName(&CB);
347     }
348 
349     // Finally, remove the old call from the program, reducing the use-count of
350     // F.
351     CB.eraseFromParent();
352   }
353 
354   const DataLayout &DL = F->getParent()->getDataLayout();
355 
356   // Since we have now created the new function, splice the body of the old
357   // function right into the new function, leaving the old rotting hulk of the
358   // function empty.
359   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
360 
361   // Loop over the argument list, transferring uses of the old arguments over to
362   // the new arguments, also transferring over the names as well.
363   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
364                               I2 = NF->arg_begin();
365        I != E; ++I) {
366     if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
367       // If this is an unmodified argument, move the name and users over to the
368       // new version.
369       I->replaceAllUsesWith(&*I2);
370       I2->takeName(&*I);
371       ++I2;
372       continue;
373     }
374 
375     if (ByValArgsToTransform.count(&*I)) {
376       // In the callee, we create an alloca, and store each of the new incoming
377       // arguments into the alloca.
378       Instruction *InsertPt = &NF->begin()->front();
379 
380       // Just add all the struct element types.
381       Type *AgTy = cast<PointerType>(I->getType())->getElementType();
382       Value *TheAlloca = new AllocaInst(
383           AgTy, DL.getAllocaAddrSpace(), nullptr,
384           I->getParamAlign().getValueOr(DL.getPrefTypeAlign(AgTy)), "",
385           InsertPt);
386       StructType *STy = cast<StructType>(AgTy);
387       Value *Idxs[2] = {ConstantInt::get(Type::getInt32Ty(F->getContext()), 0),
388                         nullptr};
389 
390       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
391         Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
392         Value *Idx = GetElementPtrInst::Create(
393             AgTy, TheAlloca, Idxs, TheAlloca->getName() + "." + Twine(i),
394             InsertPt);
395         I2->setName(I->getName() + "." + Twine(i));
396         new StoreInst(&*I2++, Idx, InsertPt);
397       }
398 
399       // Anything that used the arg should now use the alloca.
400       I->replaceAllUsesWith(TheAlloca);
401       TheAlloca->takeName(&*I);
402 
403       // If the alloca is used in a call, we must clear the tail flag since
404       // the callee now uses an alloca from the caller.
405       for (User *U : TheAlloca->users()) {
406         CallInst *Call = dyn_cast<CallInst>(U);
407         if (!Call)
408           continue;
409         Call->setTailCall(false);
410       }
411       continue;
412     }
413 
414     // There potentially are metadata uses for things like llvm.dbg.value.
415     // Replace them with undef, after handling the other regular uses.
416     auto RauwUndefMetadata = make_scope_exit(
417         [&]() { I->replaceAllUsesWith(UndefValue::get(I->getType())); });
418 
419     if (I->use_empty())
420       continue;
421 
422     // Otherwise, if we promoted this argument, then all users are load
423     // instructions (or GEPs with only load users), and all loads should be
424     // using the new argument that we added.
425     ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
426 
427     while (!I->use_empty()) {
428       if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) {
429         assert(ArgIndices.begin()->second.empty() &&
430                "Load element should sort to front!");
431         I2->setName(I->getName() + ".val");
432         LI->replaceAllUsesWith(&*I2);
433         LI->eraseFromParent();
434         LLVM_DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
435                           << "' in function '" << F->getName() << "'\n");
436       } else {
437         GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->user_back());
438         IndicesVector Operands;
439         Operands.reserve(GEP->getNumIndices());
440         for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
441              II != IE; ++II)
442           Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
443 
444         // GEPs with a single 0 index can be merged with direct loads
445         if (Operands.size() == 1 && Operands.front() == 0)
446           Operands.clear();
447 
448         Function::arg_iterator TheArg = I2;
449         for (ScalarizeTable::iterator It = ArgIndices.begin();
450              It->second != Operands; ++It, ++TheArg) {
451           assert(It != ArgIndices.end() && "GEP not handled??");
452         }
453 
454         TheArg->setName(formatv("{0}.{1:$[.]}.val", I->getName(),
455                                 make_range(Operands.begin(), Operands.end())));
456 
457         LLVM_DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
458                           << "' of function '" << NF->getName() << "'\n");
459 
460         // All of the uses must be load instructions.  Replace them all with
461         // the argument specified by ArgNo.
462         while (!GEP->use_empty()) {
463           LoadInst *L = cast<LoadInst>(GEP->user_back());
464           L->replaceAllUsesWith(&*TheArg);
465           L->eraseFromParent();
466         }
467         GEP->eraseFromParent();
468       }
469     }
470     // Increment I2 past all of the arguments added for this promoted pointer.
471     std::advance(I2, ArgIndices.size());
472   }
473 
474   return NF;
475 }
476 
477 /// Return true if we can prove that all callees pass in a valid pointer for the
478 /// specified function argument.
479 static bool allCallersPassValidPointerForArgument(Argument *Arg, Type *Ty) {
480   Function *Callee = Arg->getParent();
481   const DataLayout &DL = Callee->getParent()->getDataLayout();
482 
483   unsigned ArgNo = Arg->getArgNo();
484 
485   // Look at all call sites of the function.  At this point we know we only have
486   // direct callees.
487   for (User *U : Callee->users()) {
488     CallBase &CB = cast<CallBase>(*U);
489 
490     if (!isDereferenceablePointer(CB.getArgOperand(ArgNo), Ty, DL))
491       return false;
492   }
493   return true;
494 }
495 
496 /// Returns true if Prefix is a prefix of longer. That means, Longer has a size
497 /// that is greater than or equal to the size of prefix, and each of the
498 /// elements in Prefix is the same as the corresponding elements in Longer.
499 ///
500 /// This means it also returns true when Prefix and Longer are equal!
501 static bool isPrefix(const IndicesVector &Prefix, const IndicesVector &Longer) {
502   if (Prefix.size() > Longer.size())
503     return false;
504   return std::equal(Prefix.begin(), Prefix.end(), Longer.begin());
505 }
506 
507 /// Checks if Indices, or a prefix of Indices, is in Set.
508 static bool prefixIn(const IndicesVector &Indices,
509                      std::set<IndicesVector> &Set) {
510   std::set<IndicesVector>::iterator Low;
511   Low = Set.upper_bound(Indices);
512   if (Low != Set.begin())
513     Low--;
514   // Low is now the last element smaller than or equal to Indices. This means
515   // it points to a prefix of Indices (possibly Indices itself), if such
516   // prefix exists.
517   //
518   // This load is safe if any prefix of its operands is safe to load.
519   return Low != Set.end() && isPrefix(*Low, Indices);
520 }
521 
522 /// Mark the given indices (ToMark) as safe in the given set of indices
523 /// (Safe). Marking safe usually means adding ToMark to Safe. However, if there
524 /// is already a prefix of Indices in Safe, Indices are implicitely marked safe
525 /// already. Furthermore, any indices that Indices is itself a prefix of, are
526 /// removed from Safe (since they are implicitely safe because of Indices now).
527 static void markIndicesSafe(const IndicesVector &ToMark,
528                             std::set<IndicesVector> &Safe) {
529   std::set<IndicesVector>::iterator Low;
530   Low = Safe.upper_bound(ToMark);
531   // Guard against the case where Safe is empty
532   if (Low != Safe.begin())
533     Low--;
534   // Low is now the last element smaller than or equal to Indices. This
535   // means it points to a prefix of Indices (possibly Indices itself), if
536   // such prefix exists.
537   if (Low != Safe.end()) {
538     if (isPrefix(*Low, ToMark))
539       // If there is already a prefix of these indices (or exactly these
540       // indices) marked a safe, don't bother adding these indices
541       return;
542 
543     // Increment Low, so we can use it as a "insert before" hint
544     ++Low;
545   }
546   // Insert
547   Low = Safe.insert(Low, ToMark);
548   ++Low;
549   // If there we're a prefix of longer index list(s), remove those
550   std::set<IndicesVector>::iterator End = Safe.end();
551   while (Low != End && isPrefix(ToMark, *Low)) {
552     std::set<IndicesVector>::iterator Remove = Low;
553     ++Low;
554     Safe.erase(Remove);
555   }
556 }
557 
558 /// isSafeToPromoteArgument - As you might guess from the name of this method,
559 /// it checks to see if it is both safe and useful to promote the argument.
560 /// This method limits promotion of aggregates to only promote up to three
561 /// elements of the aggregate in order to avoid exploding the number of
562 /// arguments passed in.
563 static bool isSafeToPromoteArgument(Argument *Arg, Type *ByValTy, AAResults &AAR,
564                                     unsigned MaxElements) {
565   using GEPIndicesSet = std::set<IndicesVector>;
566 
567   // Quick exit for unused arguments
568   if (Arg->use_empty())
569     return true;
570 
571   // We can only promote this argument if all of the uses are loads, or are GEP
572   // instructions (with constant indices) that are subsequently loaded.
573   //
574   // Promoting the argument causes it to be loaded in the caller
575   // unconditionally. This is only safe if we can prove that either the load
576   // would have happened in the callee anyway (ie, there is a load in the entry
577   // block) or the pointer passed in at every call site is guaranteed to be
578   // valid.
579   // In the former case, invalid loads can happen, but would have happened
580   // anyway, in the latter case, invalid loads won't happen. This prevents us
581   // from introducing an invalid load that wouldn't have happened in the
582   // original code.
583   //
584   // This set will contain all sets of indices that are loaded in the entry
585   // block, and thus are safe to unconditionally load in the caller.
586   GEPIndicesSet SafeToUnconditionallyLoad;
587 
588   // This set contains all the sets of indices that we are planning to promote.
589   // This makes it possible to limit the number of arguments added.
590   GEPIndicesSet ToPromote;
591 
592   // If the pointer is always valid, any load with first index 0 is valid.
593 
594   if (ByValTy)
595     SafeToUnconditionallyLoad.insert(IndicesVector(1, 0));
596 
597   // Whenever a new underlying type for the operand is found, make sure it's
598   // consistent with the GEPs and loads we've already seen and, if necessary,
599   // use it to see if all incoming pointers are valid (which implies the 0-index
600   // is safe).
601   Type *BaseTy = ByValTy;
602   auto UpdateBaseTy = [&](Type *NewBaseTy) {
603     if (BaseTy)
604       return BaseTy == NewBaseTy;
605 
606     BaseTy = NewBaseTy;
607     if (allCallersPassValidPointerForArgument(Arg, BaseTy)) {
608       assert(SafeToUnconditionallyLoad.empty());
609       SafeToUnconditionallyLoad.insert(IndicesVector(1, 0));
610     }
611 
612     return true;
613   };
614 
615   // First, iterate the entry block and mark loads of (geps of) arguments as
616   // safe.
617   BasicBlock &EntryBlock = Arg->getParent()->front();
618   // Declare this here so we can reuse it
619   IndicesVector Indices;
620   for (Instruction &I : EntryBlock)
621     if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
622       Value *V = LI->getPointerOperand();
623       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
624         V = GEP->getPointerOperand();
625         if (V == Arg) {
626           // This load actually loads (part of) Arg? Check the indices then.
627           Indices.reserve(GEP->getNumIndices());
628           for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
629                II != IE; ++II)
630             if (ConstantInt *CI = dyn_cast<ConstantInt>(*II))
631               Indices.push_back(CI->getSExtValue());
632             else
633               // We found a non-constant GEP index for this argument? Bail out
634               // right away, can't promote this argument at all.
635               return false;
636 
637           if (!UpdateBaseTy(GEP->getSourceElementType()))
638             return false;
639 
640           // Indices checked out, mark them as safe
641           markIndicesSafe(Indices, SafeToUnconditionallyLoad);
642           Indices.clear();
643         }
644       } else if (V == Arg) {
645         // Direct loads are equivalent to a GEP with a single 0 index.
646         markIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
647 
648         if (BaseTy && LI->getType() != BaseTy)
649           return false;
650 
651         BaseTy = LI->getType();
652       }
653     }
654 
655   // Now, iterate all uses of the argument to see if there are any uses that are
656   // not (GEP+)loads, or any (GEP+)loads that are not safe to promote.
657   SmallVector<LoadInst *, 16> Loads;
658   IndicesVector Operands;
659   for (Use &U : Arg->uses()) {
660     User *UR = U.getUser();
661     Operands.clear();
662     if (LoadInst *LI = dyn_cast<LoadInst>(UR)) {
663       // Don't hack volatile/atomic loads
664       if (!LI->isSimple())
665         return false;
666       Loads.push_back(LI);
667       // Direct loads are equivalent to a GEP with a zero index and then a load.
668       Operands.push_back(0);
669 
670       if (!UpdateBaseTy(LI->getType()))
671         return false;
672     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UR)) {
673       if (GEP->use_empty()) {
674         // Dead GEP's cause trouble later.  Just remove them if we run into
675         // them.
676         GEP->eraseFromParent();
677         // TODO: This runs the above loop over and over again for dead GEPs
678         // Couldn't we just do increment the UI iterator earlier and erase the
679         // use?
680         return isSafeToPromoteArgument(Arg, ByValTy, AAR, MaxElements);
681       }
682 
683       if (!UpdateBaseTy(GEP->getSourceElementType()))
684         return false;
685 
686       // Ensure that all of the indices are constants.
687       for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end(); i != e;
688            ++i)
689         if (ConstantInt *C = dyn_cast<ConstantInt>(*i))
690           Operands.push_back(C->getSExtValue());
691         else
692           return false; // Not a constant operand GEP!
693 
694       // Ensure that the only users of the GEP are load instructions.
695       for (User *GEPU : GEP->users())
696         if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
697           // Don't hack volatile/atomic loads
698           if (!LI->isSimple())
699             return false;
700           Loads.push_back(LI);
701         } else {
702           // Other uses than load?
703           return false;
704         }
705     } else {
706       return false; // Not a load or a GEP.
707     }
708 
709     // Now, see if it is safe to promote this load / loads of this GEP. Loading
710     // is safe if Operands, or a prefix of Operands, is marked as safe.
711     if (!prefixIn(Operands, SafeToUnconditionallyLoad))
712       return false;
713 
714     // See if we are already promoting a load with these indices. If not, check
715     // to make sure that we aren't promoting too many elements.  If so, nothing
716     // to do.
717     if (ToPromote.find(Operands) == ToPromote.end()) {
718       if (MaxElements > 0 && ToPromote.size() == MaxElements) {
719         LLVM_DEBUG(dbgs() << "argpromotion not promoting argument '"
720                           << Arg->getName()
721                           << "' because it would require adding more "
722                           << "than " << MaxElements
723                           << " arguments to the function.\n");
724         // We limit aggregate promotion to only promoting up to a fixed number
725         // of elements of the aggregate.
726         return false;
727       }
728       ToPromote.insert(std::move(Operands));
729     }
730   }
731 
732   if (Loads.empty())
733     return true; // No users, this is a dead argument.
734 
735   // Okay, now we know that the argument is only used by load instructions and
736   // it is safe to unconditionally perform all of them. Use alias analysis to
737   // check to see if the pointer is guaranteed to not be modified from entry of
738   // the function to each of the load instructions.
739 
740   // Because there could be several/many load instructions, remember which
741   // blocks we know to be transparent to the load.
742   df_iterator_default_set<BasicBlock *, 16> TranspBlocks;
743 
744   for (LoadInst *Load : Loads) {
745     // Check to see if the load is invalidated from the start of the block to
746     // the load itself.
747     BasicBlock *BB = Load->getParent();
748 
749     MemoryLocation Loc = MemoryLocation::get(Load);
750     if (AAR.canInstructionRangeModRef(BB->front(), *Load, Loc, ModRefInfo::Mod))
751       return false; // Pointer is invalidated!
752 
753     // Now check every path from the entry block to the load for transparency.
754     // To do this, we perform a depth first search on the inverse CFG from the
755     // loading block.
756     for (BasicBlock *P : predecessors(BB)) {
757       for (BasicBlock *TranspBB : inverse_depth_first_ext(P, TranspBlocks))
758         if (AAR.canBasicBlockModify(*TranspBB, Loc))
759           return false;
760     }
761   }
762 
763   // If the path from the entry of the function to each load is free of
764   // instructions that potentially invalidate the load, we can make the
765   // transformation!
766   return true;
767 }
768 
769 bool ArgumentPromotionPass::isDenselyPacked(Type *type, const DataLayout &DL) {
770   // There is no size information, so be conservative.
771   if (!type->isSized())
772     return false;
773 
774   // If the alloc size is not equal to the storage size, then there are padding
775   // bytes. For x86_fp80 on x86-64, size: 80 alloc size: 128.
776   if (DL.getTypeSizeInBits(type) != DL.getTypeAllocSizeInBits(type))
777     return false;
778 
779   // FIXME: This isn't the right way to check for padding in vectors with
780   // non-byte-size elements.
781   if (VectorType *seqTy = dyn_cast<VectorType>(type))
782     return isDenselyPacked(seqTy->getElementType(), DL);
783 
784   // For array types, check for padding within members.
785   if (ArrayType *seqTy = dyn_cast<ArrayType>(type))
786     return isDenselyPacked(seqTy->getElementType(), DL);
787 
788   if (!isa<StructType>(type))
789     return true;
790 
791   // Check for padding within and between elements of a struct.
792   StructType *StructTy = cast<StructType>(type);
793   const StructLayout *Layout = DL.getStructLayout(StructTy);
794   uint64_t StartPos = 0;
795   for (unsigned i = 0, E = StructTy->getNumElements(); i < E; ++i) {
796     Type *ElTy = StructTy->getElementType(i);
797     if (!isDenselyPacked(ElTy, DL))
798       return false;
799     if (StartPos != Layout->getElementOffsetInBits(i))
800       return false;
801     StartPos += DL.getTypeAllocSizeInBits(ElTy);
802   }
803 
804   return true;
805 }
806 
807 /// Checks if the padding bytes of an argument could be accessed.
808 static bool canPaddingBeAccessed(Argument *arg) {
809   assert(arg->hasByValAttr());
810 
811   // Track all the pointers to the argument to make sure they are not captured.
812   SmallPtrSet<Value *, 16> PtrValues;
813   PtrValues.insert(arg);
814 
815   // Track all of the stores.
816   SmallVector<StoreInst *, 16> Stores;
817 
818   // Scan through the uses recursively to make sure the pointer is always used
819   // sanely.
820   SmallVector<Value *, 16> WorkList;
821   WorkList.insert(WorkList.end(), arg->user_begin(), arg->user_end());
822   while (!WorkList.empty()) {
823     Value *V = WorkList.back();
824     WorkList.pop_back();
825     if (isa<GetElementPtrInst>(V) || isa<PHINode>(V)) {
826       if (PtrValues.insert(V).second)
827         WorkList.insert(WorkList.end(), V->user_begin(), V->user_end());
828     } else if (StoreInst *Store = dyn_cast<StoreInst>(V)) {
829       Stores.push_back(Store);
830     } else if (!isa<LoadInst>(V)) {
831       return true;
832     }
833   }
834 
835   // Check to make sure the pointers aren't captured
836   for (StoreInst *Store : Stores)
837     if (PtrValues.count(Store->getValueOperand()))
838       return true;
839 
840   return false;
841 }
842 
843 bool ArgumentPromotionPass::areFunctionArgsABICompatible(
844     const Function &F, const TargetTransformInfo &TTI,
845     SmallPtrSetImpl<Argument *> &ArgsToPromote,
846     SmallPtrSetImpl<Argument *> &ByValArgsToTransform) {
847   for (const Use &U : F.uses()) {
848     CallBase *CB = dyn_cast<CallBase>(U.getUser());
849     if (!CB)
850       return false;
851     const Function *Caller = CB->getCaller();
852     const Function *Callee = CB->getCalledFunction();
853     if (!TTI.areFunctionArgsABICompatible(Caller, Callee, ArgsToPromote) ||
854         !TTI.areFunctionArgsABICompatible(Caller, Callee, ByValArgsToTransform))
855       return false;
856   }
857   return true;
858 }
859 
860 /// PromoteArguments - This method checks the specified function to see if there
861 /// are any promotable arguments and if it is safe to promote the function (for
862 /// example, all callers are direct).  If safe to promote some arguments, it
863 /// calls the DoPromotion method.
864 static Function *
865 promoteArguments(Function *F, function_ref<AAResults &(Function &F)> AARGetter,
866                  unsigned MaxElements,
867                  Optional<function_ref<void(CallBase &OldCS, CallBase &NewCS)>>
868                      ReplaceCallSite,
869                  const TargetTransformInfo &TTI) {
870   // Don't perform argument promotion for naked functions; otherwise we can end
871   // up removing parameters that are seemingly 'not used' as they are referred
872   // to in the assembly.
873   if(F->hasFnAttribute(Attribute::Naked))
874     return nullptr;
875 
876   // Make sure that it is local to this module.
877   if (!F->hasLocalLinkage())
878     return nullptr;
879 
880   // Don't promote arguments for variadic functions. Adding, removing, or
881   // changing non-pack parameters can change the classification of pack
882   // parameters. Frontends encode that classification at the call site in the
883   // IR, while in the callee the classification is determined dynamically based
884   // on the number of registers consumed so far.
885   if (F->isVarArg())
886     return nullptr;
887 
888   // Don't transform functions that receive inallocas, as the transformation may
889   // not be safe depending on calling convention.
890   if (F->getAttributes().hasAttrSomewhere(Attribute::InAlloca))
891     return nullptr;
892 
893   // First check: see if there are any pointer arguments!  If not, quick exit.
894   SmallVector<Argument *, 16> PointerArgs;
895   for (Argument &I : F->args())
896     if (I.getType()->isPointerTy())
897       PointerArgs.push_back(&I);
898   if (PointerArgs.empty())
899     return nullptr;
900 
901   // Second check: make sure that all callers are direct callers.  We can't
902   // transform functions that have indirect callers.  Also see if the function
903   // is self-recursive and check that target features are compatible.
904   bool isSelfRecursive = false;
905   for (Use &U : F->uses()) {
906     CallBase *CB = dyn_cast<CallBase>(U.getUser());
907     // Must be a direct call.
908     if (CB == nullptr || !CB->isCallee(&U))
909       return nullptr;
910 
911     // Can't change signature of musttail callee
912     if (CB->isMustTailCall())
913       return nullptr;
914 
915     if (CB->getParent()->getParent() == F)
916       isSelfRecursive = true;
917   }
918 
919   // Can't change signature of musttail caller
920   // FIXME: Support promoting whole chain of musttail functions
921   for (BasicBlock &BB : *F)
922     if (BB.getTerminatingMustTailCall())
923       return nullptr;
924 
925   const DataLayout &DL = F->getParent()->getDataLayout();
926 
927   AAResults &AAR = AARGetter(*F);
928 
929   // Check to see which arguments are promotable.  If an argument is promotable,
930   // add it to ArgsToPromote.
931   SmallPtrSet<Argument *, 8> ArgsToPromote;
932   SmallPtrSet<Argument *, 8> ByValArgsToTransform;
933   for (Argument *PtrArg : PointerArgs) {
934     Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
935 
936     // Replace sret attribute with noalias. This reduces register pressure by
937     // avoiding a register copy.
938     if (PtrArg->hasStructRetAttr()) {
939       unsigned ArgNo = PtrArg->getArgNo();
940       F->removeParamAttr(ArgNo, Attribute::StructRet);
941       F->addParamAttr(ArgNo, Attribute::NoAlias);
942       for (Use &U : F->uses()) {
943         CallBase &CB = cast<CallBase>(*U.getUser());
944         CB.removeParamAttr(ArgNo, Attribute::StructRet);
945         CB.addParamAttr(ArgNo, Attribute::NoAlias);
946       }
947     }
948 
949     // If this is a byval argument, and if the aggregate type is small, just
950     // pass the elements, which is always safe, if the passed value is densely
951     // packed or if we can prove the padding bytes are never accessed.
952     bool isSafeToPromote = PtrArg->hasByValAttr() &&
953                            (ArgumentPromotionPass::isDenselyPacked(AgTy, DL) ||
954                             !canPaddingBeAccessed(PtrArg));
955     if (isSafeToPromote) {
956       if (StructType *STy = dyn_cast<StructType>(AgTy)) {
957         if (MaxElements > 0 && STy->getNumElements() > MaxElements) {
958           LLVM_DEBUG(dbgs() << "argpromotion disable promoting argument '"
959                             << PtrArg->getName()
960                             << "' because it would require adding more"
961                             << " than " << MaxElements
962                             << " arguments to the function.\n");
963           continue;
964         }
965 
966         // If all the elements are single-value types, we can promote it.
967         bool AllSimple = true;
968         for (const auto *EltTy : STy->elements()) {
969           if (!EltTy->isSingleValueType()) {
970             AllSimple = false;
971             break;
972           }
973         }
974 
975         // Safe to transform, don't even bother trying to "promote" it.
976         // Passing the elements as a scalar will allow sroa to hack on
977         // the new alloca we introduce.
978         if (AllSimple) {
979           ByValArgsToTransform.insert(PtrArg);
980           continue;
981         }
982       }
983     }
984 
985     // If the argument is a recursive type and we're in a recursive
986     // function, we could end up infinitely peeling the function argument.
987     if (isSelfRecursive) {
988       if (StructType *STy = dyn_cast<StructType>(AgTy)) {
989         bool RecursiveType = false;
990         for (const auto *EltTy : STy->elements()) {
991           if (EltTy == PtrArg->getType()) {
992             RecursiveType = true;
993             break;
994           }
995         }
996         if (RecursiveType)
997           continue;
998       }
999     }
1000 
1001     // Otherwise, see if we can promote the pointer to its value.
1002     Type *ByValTy =
1003         PtrArg->hasByValAttr() ? PtrArg->getParamByValType() : nullptr;
1004     if (isSafeToPromoteArgument(PtrArg, ByValTy, AAR, MaxElements))
1005       ArgsToPromote.insert(PtrArg);
1006   }
1007 
1008   // No promotable pointer arguments.
1009   if (ArgsToPromote.empty() && ByValArgsToTransform.empty())
1010     return nullptr;
1011 
1012   if (!ArgumentPromotionPass::areFunctionArgsABICompatible(
1013           *F, TTI, ArgsToPromote, ByValArgsToTransform))
1014     return nullptr;
1015 
1016   return doPromotion(F, ArgsToPromote, ByValArgsToTransform, ReplaceCallSite);
1017 }
1018 
1019 PreservedAnalyses ArgumentPromotionPass::run(LazyCallGraph::SCC &C,
1020                                              CGSCCAnalysisManager &AM,
1021                                              LazyCallGraph &CG,
1022                                              CGSCCUpdateResult &UR) {
1023   bool Changed = false, LocalChange;
1024 
1025   // Iterate until we stop promoting from this SCC.
1026   do {
1027     LocalChange = false;
1028 
1029     for (LazyCallGraph::Node &N : C) {
1030       Function &OldF = N.getFunction();
1031 
1032       FunctionAnalysisManager &FAM =
1033           AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
1034       // FIXME: This lambda must only be used with this function. We should
1035       // skip the lambda and just get the AA results directly.
1036       auto AARGetter = [&](Function &F) -> AAResults & {
1037         assert(&F == &OldF && "Called with an unexpected function!");
1038         return FAM.getResult<AAManager>(F);
1039       };
1040 
1041       const TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(OldF);
1042       Function *NewF =
1043           promoteArguments(&OldF, AARGetter, MaxElements, None, TTI);
1044       if (!NewF)
1045         continue;
1046       LocalChange = true;
1047 
1048       // Directly substitute the functions in the call graph. Note that this
1049       // requires the old function to be completely dead and completely
1050       // replaced by the new function. It does no call graph updates, it merely
1051       // swaps out the particular function mapped to a particular node in the
1052       // graph.
1053       C.getOuterRefSCC().replaceNodeFunction(N, *NewF);
1054       OldF.eraseFromParent();
1055     }
1056 
1057     Changed |= LocalChange;
1058   } while (LocalChange);
1059 
1060   if (!Changed)
1061     return PreservedAnalyses::all();
1062 
1063   return PreservedAnalyses::none();
1064 }
1065 
1066 namespace {
1067 
1068 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
1069 struct ArgPromotion : public CallGraphSCCPass {
1070   // Pass identification, replacement for typeid
1071   static char ID;
1072 
1073   explicit ArgPromotion(unsigned MaxElements = 3)
1074       : CallGraphSCCPass(ID), MaxElements(MaxElements) {
1075     initializeArgPromotionPass(*PassRegistry::getPassRegistry());
1076   }
1077 
1078   void getAnalysisUsage(AnalysisUsage &AU) const override {
1079     AU.addRequired<AssumptionCacheTracker>();
1080     AU.addRequired<TargetLibraryInfoWrapperPass>();
1081     AU.addRequired<TargetTransformInfoWrapperPass>();
1082     getAAResultsAnalysisUsage(AU);
1083     CallGraphSCCPass::getAnalysisUsage(AU);
1084   }
1085 
1086   bool runOnSCC(CallGraphSCC &SCC) override;
1087 
1088 private:
1089   using llvm::Pass::doInitialization;
1090 
1091   bool doInitialization(CallGraph &CG) override;
1092 
1093   /// The maximum number of elements to expand, or 0 for unlimited.
1094   unsigned MaxElements;
1095 };
1096 
1097 } // end anonymous namespace
1098 
1099 char ArgPromotion::ID = 0;
1100 
1101 INITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion",
1102                       "Promote 'by reference' arguments to scalars", false,
1103                       false)
1104 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1105 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1106 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1107 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1108 INITIALIZE_PASS_END(ArgPromotion, "argpromotion",
1109                     "Promote 'by reference' arguments to scalars", false, false)
1110 
1111 Pass *llvm::createArgumentPromotionPass(unsigned MaxElements) {
1112   return new ArgPromotion(MaxElements);
1113 }
1114 
1115 bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
1116   if (skipSCC(SCC))
1117     return false;
1118 
1119   // Get the callgraph information that we need to update to reflect our
1120   // changes.
1121   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1122 
1123   LegacyAARGetter AARGetter(*this);
1124 
1125   bool Changed = false, LocalChange;
1126 
1127   // Iterate until we stop promoting from this SCC.
1128   do {
1129     LocalChange = false;
1130     // Attempt to promote arguments from all functions in this SCC.
1131     for (CallGraphNode *OldNode : SCC) {
1132       Function *OldF = OldNode->getFunction();
1133       if (!OldF)
1134         continue;
1135 
1136       auto ReplaceCallSite = [&](CallBase &OldCS, CallBase &NewCS) {
1137         Function *Caller = OldCS.getParent()->getParent();
1138         CallGraphNode *NewCalleeNode =
1139             CG.getOrInsertFunction(NewCS.getCalledFunction());
1140         CallGraphNode *CallerNode = CG[Caller];
1141         CallerNode->replaceCallEdge(cast<CallBase>(OldCS),
1142                                     cast<CallBase>(NewCS), NewCalleeNode);
1143       };
1144 
1145       const TargetTransformInfo &TTI =
1146           getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*OldF);
1147       if (Function *NewF = promoteArguments(OldF, AARGetter, MaxElements,
1148                                             {ReplaceCallSite}, TTI)) {
1149         LocalChange = true;
1150 
1151         // Update the call graph for the newly promoted function.
1152         CallGraphNode *NewNode = CG.getOrInsertFunction(NewF);
1153         NewNode->stealCalledFunctionsFrom(OldNode);
1154         if (OldNode->getNumReferences() == 0)
1155           delete CG.removeFunctionFromModule(OldNode);
1156         else
1157           OldF->setLinkage(Function::ExternalLinkage);
1158 
1159         // And updat ethe SCC we're iterating as well.
1160         SCC.ReplaceNode(OldNode, NewNode);
1161       }
1162     }
1163     // Remember that we changed something.
1164     Changed |= LocalChange;
1165   } while (LocalChange);
1166 
1167   return Changed;
1168 }
1169 
1170 bool ArgPromotion::doInitialization(CallGraph &CG) {
1171   return CallGraphSCCPass::doInitialization(CG);
1172 }
1173