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/AssumptionCache.h"
42 #include "llvm/Analysis/BasicAliasAnalysis.h"
43 #include "llvm/Analysis/CGSCCPassManager.h"
44 #include "llvm/Analysis/CallGraph.h"
45 #include "llvm/Analysis/CallGraphSCCPass.h"
46 #include "llvm/Analysis/LazyCallGraph.h"
47 #include "llvm/Analysis/Loads.h"
48 #include "llvm/Analysis/MemoryLocation.h"
49 #include "llvm/Analysis/ValueTracking.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 <utility>
87 #include <vector>
88 
89 using namespace llvm;
90 
91 #define DEBUG_TYPE "argpromotion"
92 
93 STATISTIC(NumArgumentsPromoted, "Number of pointer arguments promoted");
94 STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
95 STATISTIC(NumByValArgsPromoted, "Number of byval arguments promoted");
96 STATISTIC(NumArgumentsDead, "Number of dead pointer args eliminated");
97 
98 /// A vector used to hold the indices of a single GEP instruction
99 using IndicesVector = std::vector<uint64_t>;
100 
101 /// DoPromotion - This method actually performs the promotion of the specified
102 /// arguments, and returns the new function.  At this point, we know that it's
103 /// safe to do so.
104 static Function *
105 doPromotion(Function *F, SmallPtrSetImpl<Argument *> &ArgsToPromote,
106             SmallPtrSetImpl<Argument *> &ByValArgsToTransform,
107             Optional<function_ref<void(CallBase &OldCS, CallBase &NewCS)>>
108                 ReplaceCallSite) {
109   // Start by computing a new prototype for the function, which is the same as
110   // the old function, but has modified arguments.
111   FunctionType *FTy = F->getFunctionType();
112   std::vector<Type *> Params;
113 
114   using ScalarizeTable = std::set<std::pair<Type *, IndicesVector>>;
115 
116   // ScalarizedElements - If we are promoting a pointer that has elements
117   // accessed out of it, keep track of which elements are accessed so that we
118   // can add one argument for each.
119   //
120   // Arguments that are directly loaded will have a zero element value here, to
121   // handle cases where there are both a direct load and GEP accesses.
122   std::map<Argument *, ScalarizeTable> ScalarizedElements;
123 
124   // OriginalLoads - Keep track of a representative load instruction from the
125   // original function so that we can tell the alias analysis implementation
126   // what the new GEP/Load instructions we are inserting look like.
127   // We need to keep the original loads for each argument and the elements
128   // of the argument that are accessed.
129   std::map<std::pair<Argument *, IndicesVector>, LoadInst *> OriginalLoads;
130 
131   // Attribute - Keep track of the parameter attributes for the arguments
132   // that we are *not* promoting. For the ones that we do promote, the parameter
133   // attributes are lost
134   SmallVector<AttributeSet, 8> ArgAttrVec;
135   AttributeList PAL = F->getAttributes();
136 
137   // First, determine the new argument list
138   unsigned ArgNo = 0;
139   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
140        ++I, ++ArgNo) {
141     if (ByValArgsToTransform.count(&*I)) {
142       // Simple byval argument? Just add all the struct element types.
143       Type *AgTy = I->getParamByValType();
144       StructType *STy = cast<StructType>(AgTy);
145       llvm::append_range(Params, STy->elements());
146       ArgAttrVec.insert(ArgAttrVec.end(), STy->getNumElements(),
147                         AttributeSet());
148       ++NumByValArgsPromoted;
149     } else if (!ArgsToPromote.count(&*I)) {
150       // Unchanged argument
151       Params.push_back(I->getType());
152       ArgAttrVec.push_back(PAL.getParamAttrs(ArgNo));
153     } else if (I->use_empty()) {
154       // Dead argument (which are always marked as promotable)
155       ++NumArgumentsDead;
156     } else {
157       // Okay, this is being promoted. This means that the only uses are loads
158       // or GEPs which are only used by loads
159 
160       // In this table, we will track which indices are loaded from the argument
161       // (where direct loads are tracked as no indices).
162       ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
163       for (User *U : make_early_inc_range(I->users())) {
164         Instruction *UI = cast<Instruction>(U);
165         Type *SrcTy;
166         if (LoadInst *L = dyn_cast<LoadInst>(UI))
167           SrcTy = L->getType();
168         else
169           SrcTy = cast<GetElementPtrInst>(UI)->getSourceElementType();
170         // Skip dead GEPs and remove them.
171         if (isa<GetElementPtrInst>(UI) && UI->use_empty()) {
172           UI->eraseFromParent();
173           continue;
174         }
175 
176         IndicesVector Indices;
177         Indices.reserve(UI->getNumOperands() - 1);
178         // Since loads will only have a single operand, and GEPs only a single
179         // non-index operand, this will record direct loads without any indices,
180         // and gep+loads with the GEP indices.
181         for (const Use &I : llvm::drop_begin(UI->operands()))
182           Indices.push_back(cast<ConstantInt>(I)->getSExtValue());
183         // GEPs with a single 0 index can be merged with direct loads
184         if (Indices.size() == 1 && Indices.front() == 0)
185           Indices.clear();
186         ArgIndices.insert(std::make_pair(SrcTy, Indices));
187         LoadInst *OrigLoad;
188         if (LoadInst *L = dyn_cast<LoadInst>(UI))
189           OrigLoad = L;
190         else
191           // Take any load, we will use it only to update Alias Analysis
192           OrigLoad = cast<LoadInst>(UI->user_back());
193         OriginalLoads[std::make_pair(&*I, Indices)] = OrigLoad;
194       }
195 
196       // Add a parameter to the function for each element passed in.
197       for (const auto &ArgIndex : ArgIndices) {
198         // not allowed to dereference ->begin() if size() is 0
199         Params.push_back(GetElementPtrInst::getIndexedType(
200             I->getType()->getPointerElementType(), ArgIndex.second));
201         ArgAttrVec.push_back(AttributeSet());
202         assert(Params.back());
203       }
204 
205       if (ArgIndices.size() == 1 && ArgIndices.begin()->second.empty())
206         ++NumArgumentsPromoted;
207       else
208         ++NumAggregatesPromoted;
209     }
210   }
211 
212   Type *RetTy = FTy->getReturnType();
213 
214   // Construct the new function type using the new arguments.
215   FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
216 
217   // Create the new function body and insert it into the module.
218   Function *NF = Function::Create(NFTy, F->getLinkage(), F->getAddressSpace(),
219                                   F->getName());
220   NF->copyAttributesFrom(F);
221   NF->copyMetadata(F, 0);
222 
223   // The new function will have the !dbg metadata copied from the original
224   // function. The original function may not be deleted, and dbg metadata need
225   // to be unique so we need to drop it.
226   F->setSubprogram(nullptr);
227 
228   LLVM_DEBUG(dbgs() << "ARG PROMOTION:  Promoting to:" << *NF << "\n"
229                     << "From: " << *F);
230 
231   // Recompute the parameter attributes list based on the new arguments for
232   // the function.
233   NF->setAttributes(AttributeList::get(F->getContext(), PAL.getFnAttrs(),
234                                        PAL.getRetAttrs(), ArgAttrVec));
235   ArgAttrVec.clear();
236 
237   F->getParent()->getFunctionList().insert(F->getIterator(), NF);
238   NF->takeName(F);
239 
240   // Loop over all of the callers of the function, transforming the call sites
241   // to pass in the loaded pointers.
242   //
243   SmallVector<Value *, 16> Args;
244   const DataLayout &DL = F->getParent()->getDataLayout();
245   while (!F->use_empty()) {
246     CallBase &CB = cast<CallBase>(*F->user_back());
247     assert(CB.getCalledFunction() == F);
248     const AttributeList &CallPAL = CB.getAttributes();
249     IRBuilder<NoFolder> IRB(&CB);
250 
251     // Loop over the operands, inserting GEP and loads in the caller as
252     // appropriate.
253     auto AI = CB.arg_begin();
254     ArgNo = 0;
255     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
256          ++I, ++AI, ++ArgNo)
257       if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
258         Args.push_back(*AI); // Unmodified argument
259         ArgAttrVec.push_back(CallPAL.getParamAttrs(ArgNo));
260       } else if (ByValArgsToTransform.count(&*I)) {
261         // Emit a GEP and load for each element of the struct.
262         Type *AgTy = I->getParamByValType();
263         StructType *STy = cast<StructType>(AgTy);
264         Value *Idxs[2] = {
265             ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr};
266         const StructLayout *SL = DL.getStructLayout(STy);
267         Align StructAlign = *I->getParamAlign();
268         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
269           Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
270           auto *Idx =
271               IRB.CreateGEP(STy, *AI, Idxs, (*AI)->getName() + "." + Twine(i));
272           // TODO: Tell AA about the new values?
273           Align Alignment =
274               commonAlignment(StructAlign, SL->getElementOffset(i));
275           Args.push_back(IRB.CreateAlignedLoad(
276               STy->getElementType(i), Idx, Alignment, Idx->getName() + ".val"));
277           ArgAttrVec.push_back(AttributeSet());
278         }
279       } else if (!I->use_empty()) {
280         // Non-dead argument: insert GEPs and loads as appropriate.
281         ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
282         // Store the Value* version of the indices in here, but declare it now
283         // for reuse.
284         std::vector<Value *> Ops;
285         for (const auto &ArgIndex : ArgIndices) {
286           Value *V = *AI;
287           LoadInst *OrigLoad =
288               OriginalLoads[std::make_pair(&*I, ArgIndex.second)];
289           if (!ArgIndex.second.empty()) {
290             Ops.reserve(ArgIndex.second.size());
291             Type *ElTy = V->getType();
292             for (auto II : ArgIndex.second) {
293               // Use i32 to index structs, and i64 for others (pointers/arrays).
294               // This satisfies GEP constraints.
295               Type *IdxTy =
296                   (ElTy->isStructTy() ? Type::getInt32Ty(F->getContext())
297                                       : Type::getInt64Ty(F->getContext()));
298               Ops.push_back(ConstantInt::get(IdxTy, II));
299               // Keep track of the type we're currently indexing.
300               if (auto *ElPTy = dyn_cast<PointerType>(ElTy))
301                 ElTy = ElPTy->getPointerElementType();
302               else
303                 ElTy = GetElementPtrInst::getTypeAtIndex(ElTy, II);
304             }
305             // And create a GEP to extract those indices.
306             V = IRB.CreateGEP(ArgIndex.first, V, Ops, V->getName() + ".idx");
307             Ops.clear();
308           }
309           // Since we're replacing a load make sure we take the alignment
310           // of the previous load.
311           LoadInst *newLoad =
312               IRB.CreateLoad(OrigLoad->getType(), V, V->getName() + ".val");
313           newLoad->setAlignment(OrigLoad->getAlign());
314           // Transfer the AA info too.
315           newLoad->setAAMetadata(OrigLoad->getAAMetadata());
316 
317           Args.push_back(newLoad);
318           ArgAttrVec.push_back(AttributeSet());
319         }
320       }
321 
322     // Push any varargs arguments on the list.
323     for (; AI != CB.arg_end(); ++AI, ++ArgNo) {
324       Args.push_back(*AI);
325       ArgAttrVec.push_back(CallPAL.getParamAttrs(ArgNo));
326     }
327 
328     SmallVector<OperandBundleDef, 1> OpBundles;
329     CB.getOperandBundlesAsDefs(OpBundles);
330 
331     CallBase *NewCS = nullptr;
332     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
333       NewCS = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
334                                  Args, OpBundles, "", &CB);
335     } else {
336       auto *NewCall = CallInst::Create(NF, Args, OpBundles, "", &CB);
337       NewCall->setTailCallKind(cast<CallInst>(&CB)->getTailCallKind());
338       NewCS = NewCall;
339     }
340     NewCS->setCallingConv(CB.getCallingConv());
341     NewCS->setAttributes(AttributeList::get(F->getContext(),
342                                             CallPAL.getFnAttrs(),
343                                             CallPAL.getRetAttrs(), ArgAttrVec));
344     NewCS->copyMetadata(CB, {LLVMContext::MD_prof, LLVMContext::MD_dbg});
345     Args.clear();
346     ArgAttrVec.clear();
347 
348     // Update the callgraph to know that the callsite has been transformed.
349     if (ReplaceCallSite)
350       (*ReplaceCallSite)(CB, *NewCS);
351 
352     if (!CB.use_empty()) {
353       CB.replaceAllUsesWith(NewCS);
354       NewCS->takeName(&CB);
355     }
356 
357     // Finally, remove the old call from the program, reducing the use-count of
358     // F.
359     CB.eraseFromParent();
360   }
361 
362   // Since we have now created the new function, splice the body of the old
363   // function right into the new function, leaving the old rotting hulk of the
364   // function empty.
365   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
366 
367   // Loop over the argument list, transferring uses of the old arguments over to
368   // the new arguments, also transferring over the names as well.
369   Function::arg_iterator I2 = NF->arg_begin();
370   for (Argument &Arg : F->args()) {
371     if (!ArgsToPromote.count(&Arg) && !ByValArgsToTransform.count(&Arg)) {
372       // If this is an unmodified argument, move the name and users over to the
373       // new version.
374       Arg.replaceAllUsesWith(&*I2);
375       I2->takeName(&Arg);
376       ++I2;
377       continue;
378     }
379 
380     if (ByValArgsToTransform.count(&Arg)) {
381       // In the callee, we create an alloca, and store each of the new incoming
382       // arguments into the alloca.
383       Instruction *InsertPt = &NF->begin()->front();
384 
385       // Just add all the struct element types.
386       Type *AgTy = Arg.getParamByValType();
387       Align StructAlign = *Arg.getParamAlign();
388       Value *TheAlloca = new AllocaInst(AgTy, DL.getAllocaAddrSpace(), nullptr,
389                                         StructAlign, "", InsertPt);
390       StructType *STy = cast<StructType>(AgTy);
391       Value *Idxs[2] = {ConstantInt::get(Type::getInt32Ty(F->getContext()), 0),
392                         nullptr};
393       const StructLayout *SL = DL.getStructLayout(STy);
394 
395       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
396         Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
397         Value *Idx = GetElementPtrInst::Create(
398             AgTy, TheAlloca, Idxs, TheAlloca->getName() + "." + Twine(i),
399             InsertPt);
400         I2->setName(Arg.getName() + "." + Twine(i));
401         Align Alignment = commonAlignment(StructAlign, SL->getElementOffset(i));
402         new StoreInst(&*I2++, Idx, false, Alignment, InsertPt);
403       }
404 
405       // Anything that used the arg should now use the alloca.
406       Arg.replaceAllUsesWith(TheAlloca);
407       TheAlloca->takeName(&Arg);
408       continue;
409     }
410 
411     // There potentially are metadata uses for things like llvm.dbg.value.
412     // Replace them with undef, after handling the other regular uses.
413     auto RauwUndefMetadata = make_scope_exit(
414         [&]() { Arg.replaceAllUsesWith(UndefValue::get(Arg.getType())); });
415 
416     if (Arg.use_empty())
417       continue;
418 
419     // Otherwise, if we promoted this argument, then all users are load
420     // instructions (or GEPs with only load users), and all loads should be
421     // using the new argument that we added.
422     ScalarizeTable &ArgIndices = ScalarizedElements[&Arg];
423 
424     while (!Arg.use_empty()) {
425       if (LoadInst *LI = dyn_cast<LoadInst>(Arg.user_back())) {
426         assert(ArgIndices.begin()->second.empty() &&
427                "Load element should sort to front!");
428         I2->setName(Arg.getName() + ".val");
429         LI->replaceAllUsesWith(&*I2);
430         LI->eraseFromParent();
431         LLVM_DEBUG(dbgs() << "*** Promoted load of argument '" << Arg.getName()
432                           << "' in function '" << F->getName() << "'\n");
433       } else {
434         GetElementPtrInst *GEP = cast<GetElementPtrInst>(Arg.user_back());
435         assert(!GEP->use_empty() &&
436                "GEPs without uses should be cleaned up already");
437         IndicesVector Operands;
438         Operands.reserve(GEP->getNumIndices());
439         for (const Use &Idx : GEP->indices())
440           Operands.push_back(cast<ConstantInt>(Idx)->getSExtValue());
441 
442         // GEPs with a single 0 index can be merged with direct loads
443         if (Operands.size() == 1 && Operands.front() == 0)
444           Operands.clear();
445 
446         Function::arg_iterator TheArg = I2;
447         for (ScalarizeTable::iterator It = ArgIndices.begin();
448              It->second != Operands; ++It, ++TheArg) {
449           assert(It != ArgIndices.end() && "GEP not handled??");
450         }
451 
452         TheArg->setName(formatv("{0}.{1:$[.]}.val", Arg.getName(),
453                                 make_range(Operands.begin(), Operands.end())));
454 
455         LLVM_DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
456                           << "' of function '" << NF->getName() << "'\n");
457 
458         // All of the uses must be load instructions.  Replace them all with
459         // the argument specified by ArgNo.
460         while (!GEP->use_empty()) {
461           LoadInst *L = cast<LoadInst>(GEP->user_back());
462           L->replaceAllUsesWith(&*TheArg);
463           L->eraseFromParent();
464         }
465         GEP->eraseFromParent();
466       }
467     }
468     // Increment I2 past all of the arguments added for this promoted pointer.
469     std::advance(I2, ArgIndices.size());
470   }
471 
472   return NF;
473 }
474 
475 /// Return true if we can prove that all callees pass in a valid pointer for the
476 /// specified function argument.
477 static bool allCallersPassValidPointerForArgument(Argument *Arg, Type *Ty) {
478   Function *Callee = Arg->getParent();
479   const DataLayout &DL = Callee->getParent()->getDataLayout();
480   Align NeededAlign(1); // TODO: This is incorrect!
481   APInt Bytes(64, DL.getTypeStoreSize(Ty));
482 
483   // Check if the argument itself is marked dereferenceable and aligned.
484   if (isDereferenceableAndAlignedPointer(Arg, NeededAlign, Bytes, DL))
485     return true;
486 
487   // Look at all call sites of the function.  At this point we know we only have
488   // direct callees.
489   return all_of(Callee->users(), [&](User *U) {
490     CallBase &CB = cast<CallBase>(*U);
491     return isDereferenceableAndAlignedPointer(
492         CB.getArgOperand(Arg->getArgNo()), NeededAlign, Bytes, DL);
493   });
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 functions that are guaranteed to execution on function
616   // entry and mark loads of (geps of) arguments as 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 (Use &Idx : GEP->indices())
629             if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
630               Indices.push_back(CI->getSExtValue());
631             else
632               // We found a non-constant GEP index for this argument? Bail out
633               // right away, can't promote this argument at all.
634               return false;
635 
636           if (!UpdateBaseTy(GEP->getSourceElementType()))
637             return false;
638 
639           // Indices checked out, mark them as safe
640           markIndicesSafe(Indices, SafeToUnconditionallyLoad);
641           Indices.clear();
642         }
643       } else if (V == Arg) {
644         // Direct loads are equivalent to a GEP with a single 0 index.
645         markIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
646 
647         if (BaseTy && LI->getType() != BaseTy)
648           return false;
649 
650         BaseTy = LI->getType();
651       }
652     }
653 
654     if (!isGuaranteedToTransferExecutionToSuccessor(&I))
655       break;
656   }
657 
658   // Now, iterate all uses of the argument to see if there are any uses that are
659   // not (GEP+)loads, or any (GEP+)loads that are not safe to promote.
660   SmallVector<LoadInst *, 16> Loads;
661   IndicesVector Operands;
662   for (Use &U : Arg->uses()) {
663     User *UR = U.getUser();
664     Operands.clear();
665     if (LoadInst *LI = dyn_cast<LoadInst>(UR)) {
666       // Don't hack volatile/atomic loads
667       if (!LI->isSimple())
668         return false;
669       Loads.push_back(LI);
670       // Direct loads are equivalent to a GEP with a zero index and then a load.
671       Operands.push_back(0);
672 
673       if (!UpdateBaseTy(LI->getType()))
674         return false;
675     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UR)) {
676       if (GEP->use_empty()) {
677         // Dead GEP's cause trouble later.  Just remove them if we run into
678         // them.
679         continue;
680       }
681 
682       if (!UpdateBaseTy(GEP->getSourceElementType()))
683         return false;
684 
685       // Ensure that all of the indices are constants.
686       for (Use &Idx : GEP->indices())
687         if (ConstantInt *C = dyn_cast<ConstantInt>(Idx))
688           Operands.push_back(C->getSExtValue());
689         else
690           return false; // Not a constant operand GEP!
691 
692       // Ensure that the only users of the GEP are load instructions.
693       for (User *GEPU : GEP->users())
694         if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
695           // Don't hack volatile/atomic loads
696           if (!LI->isSimple())
697             return false;
698           Loads.push_back(LI);
699         } else {
700           // Other uses than load?
701           return false;
702         }
703     } else {
704       return false; // Not a load or a GEP.
705     }
706 
707     // Now, see if it is safe to promote this load / loads of this GEP. Loading
708     // is safe if Operands, or a prefix of Operands, is marked as safe.
709     if (!prefixIn(Operands, SafeToUnconditionallyLoad))
710       return false;
711 
712     // See if we are already promoting a load with these indices. If not, check
713     // to make sure that we aren't promoting too many elements.  If so, nothing
714     // to do.
715     if (ToPromote.find(Operands) == ToPromote.end()) {
716       if (MaxElements > 0 && ToPromote.size() == MaxElements) {
717         LLVM_DEBUG(dbgs() << "argpromotion not promoting argument '"
718                           << Arg->getName()
719                           << "' because it would require adding more "
720                           << "than " << MaxElements
721                           << " arguments to the function.\n");
722         // We limit aggregate promotion to only promoting up to a fixed number
723         // of elements of the aggregate.
724         return false;
725       }
726       ToPromote.insert(std::move(Operands));
727     }
728   }
729 
730   if (Loads.empty())
731     return true; // No users, this is a dead argument.
732 
733   // Okay, now we know that the argument is only used by load instructions and
734   // it is safe to unconditionally perform all of them. Use alias analysis to
735   // check to see if the pointer is guaranteed to not be modified from entry of
736   // the function to each of the load instructions.
737 
738   // Because there could be several/many load instructions, remember which
739   // blocks we know to be transparent to the load.
740   df_iterator_default_set<BasicBlock *, 16> TranspBlocks;
741 
742   for (LoadInst *Load : Loads) {
743     // Check to see if the load is invalidated from the start of the block to
744     // the load itself.
745     BasicBlock *BB = Load->getParent();
746 
747     MemoryLocation Loc = MemoryLocation::get(Load);
748     if (AAR.canInstructionRangeModRef(BB->front(), *Load, Loc, ModRefInfo::Mod))
749       return false; // Pointer is invalidated!
750 
751     // Now check every path from the entry block to the load for transparency.
752     // To do this, we perform a depth first search on the inverse CFG from the
753     // loading block.
754     for (BasicBlock *P : predecessors(BB)) {
755       for (BasicBlock *TranspBB : inverse_depth_first_ext(P, TranspBlocks))
756         if (AAR.canBasicBlockModify(*TranspBB, Loc))
757           return false;
758     }
759   }
760 
761   // If the path from the entry of the function to each load is free of
762   // instructions that potentially invalidate the load, we can make the
763   // transformation!
764   return true;
765 }
766 
767 bool ArgumentPromotionPass::isDenselyPacked(Type *type, const DataLayout &DL) {
768   // There is no size information, so be conservative.
769   if (!type->isSized())
770     return false;
771 
772   // If the alloc size is not equal to the storage size, then there are padding
773   // bytes. For x86_fp80 on x86-64, size: 80 alloc size: 128.
774   if (DL.getTypeSizeInBits(type) != DL.getTypeAllocSizeInBits(type))
775     return false;
776 
777   // FIXME: This isn't the right way to check for padding in vectors with
778   // non-byte-size elements.
779   if (VectorType *seqTy = dyn_cast<VectorType>(type))
780     return isDenselyPacked(seqTy->getElementType(), DL);
781 
782   // For array types, check for padding within members.
783   if (ArrayType *seqTy = dyn_cast<ArrayType>(type))
784     return isDenselyPacked(seqTy->getElementType(), DL);
785 
786   if (!isa<StructType>(type))
787     return true;
788 
789   // Check for padding within and between elements of a struct.
790   StructType *StructTy = cast<StructType>(type);
791   const StructLayout *Layout = DL.getStructLayout(StructTy);
792   uint64_t StartPos = 0;
793   for (unsigned i = 0, E = StructTy->getNumElements(); i < E; ++i) {
794     Type *ElTy = StructTy->getElementType(i);
795     if (!isDenselyPacked(ElTy, DL))
796       return false;
797     if (StartPos != Layout->getElementOffsetInBits(i))
798       return false;
799     StartPos += DL.getTypeAllocSizeInBits(ElTy);
800   }
801 
802   return true;
803 }
804 
805 /// Checks if the padding bytes of an argument could be accessed.
806 static bool canPaddingBeAccessed(Argument *arg) {
807   assert(arg->hasByValAttr());
808 
809   // Track all the pointers to the argument to make sure they are not captured.
810   SmallPtrSet<Value *, 16> PtrValues;
811   PtrValues.insert(arg);
812 
813   // Track all of the stores.
814   SmallVector<StoreInst *, 16> Stores;
815 
816   // Scan through the uses recursively to make sure the pointer is always used
817   // sanely.
818   SmallVector<Value *, 16> WorkList(arg->users());
819   while (!WorkList.empty()) {
820     Value *V = WorkList.pop_back_val();
821     if (isa<GetElementPtrInst>(V) || isa<PHINode>(V)) {
822       if (PtrValues.insert(V).second)
823         llvm::append_range(WorkList, V->users());
824     } else if (StoreInst *Store = dyn_cast<StoreInst>(V)) {
825       Stores.push_back(Store);
826     } else if (!isa<LoadInst>(V)) {
827       return true;
828     }
829   }
830 
831   // Check to make sure the pointers aren't captured
832   for (StoreInst *Store : Stores)
833     if (PtrValues.count(Store->getValueOperand()))
834       return true;
835 
836   return false;
837 }
838 
839 /// Check if callers and the callee \p F agree how promoted arguments would be
840 /// passed. The ones that they do not agree on are eliminated from the sets but
841 /// the return value has to be observed as well.
842 static bool areFunctionArgsABICompatible(
843     const Function &F, const TargetTransformInfo &TTI,
844     SmallPtrSetImpl<Argument *> &ArgsToPromote,
845     SmallPtrSetImpl<Argument *> &ByValArgsToTransform) {
846   // TODO: Check individual arguments so we can promote a subset?
847   SmallVector<Type *, 32> Types;
848   for (Argument *Arg : ArgsToPromote)
849     Types.push_back(Arg->getType()->getPointerElementType());
850   for (Argument *Arg : ByValArgsToTransform)
851     Types.push_back(Arg->getParamByValType());
852 
853   for (const Use &U : F.uses()) {
854     CallBase *CB = dyn_cast<CallBase>(U.getUser());
855     if (!CB)
856       return false;
857     const Function *Caller = CB->getCaller();
858     const Function *Callee = CB->getCalledFunction();
859     if (!TTI.areTypesABICompatible(Caller, Callee, Types))
860       return false;
861   }
862   return true;
863 }
864 
865 /// PromoteArguments - This method checks the specified function to see if there
866 /// are any promotable arguments and if it is safe to promote the function (for
867 /// example, all callers are direct).  If safe to promote some arguments, it
868 /// calls the DoPromotion method.
869 static Function *
870 promoteArguments(Function *F, function_ref<AAResults &(Function &F)> AARGetter,
871                  unsigned MaxElements,
872                  Optional<function_ref<void(CallBase &OldCS, CallBase &NewCS)>>
873                      ReplaceCallSite,
874                  const TargetTransformInfo &TTI) {
875   // Don't perform argument promotion for naked functions; otherwise we can end
876   // up removing parameters that are seemingly 'not used' as they are referred
877   // to in the assembly.
878   if(F->hasFnAttribute(Attribute::Naked))
879     return nullptr;
880 
881   // Make sure that it is local to this module.
882   if (!F->hasLocalLinkage())
883     return nullptr;
884 
885   // Don't promote arguments for variadic functions. Adding, removing, or
886   // changing non-pack parameters can change the classification of pack
887   // parameters. Frontends encode that classification at the call site in the
888   // IR, while in the callee the classification is determined dynamically based
889   // on the number of registers consumed so far.
890   if (F->isVarArg())
891     return nullptr;
892 
893   // Don't transform functions that receive inallocas, as the transformation may
894   // not be safe depending on calling convention.
895   if (F->getAttributes().hasAttrSomewhere(Attribute::InAlloca))
896     return nullptr;
897 
898   // First check: see if there are any pointer arguments!  If not, quick exit.
899   SmallVector<Argument *, 16> PointerArgs;
900   for (Argument &I : F->args())
901     if (I.getType()->isPointerTy())
902       PointerArgs.push_back(&I);
903   if (PointerArgs.empty())
904     return nullptr;
905 
906   // Second check: make sure that all callers are direct callers.  We can't
907   // transform functions that have indirect callers.  Also see if the function
908   // is self-recursive and check that target features are compatible.
909   bool isSelfRecursive = false;
910   for (Use &U : F->uses()) {
911     CallBase *CB = dyn_cast<CallBase>(U.getUser());
912     // Must be a direct call.
913     if (CB == nullptr || !CB->isCallee(&U))
914       return nullptr;
915 
916     // Can't change signature of musttail callee
917     if (CB->isMustTailCall())
918       return nullptr;
919 
920     if (CB->getParent()->getParent() == F)
921       isSelfRecursive = true;
922   }
923 
924   // Can't change signature of musttail caller
925   // FIXME: Support promoting whole chain of musttail functions
926   for (BasicBlock &BB : *F)
927     if (BB.getTerminatingMustTailCall())
928       return nullptr;
929 
930   const DataLayout &DL = F->getParent()->getDataLayout();
931 
932   AAResults &AAR = AARGetter(*F);
933 
934   // Check to see which arguments are promotable.  If an argument is promotable,
935   // add it to ArgsToPromote.
936   SmallPtrSet<Argument *, 8> ArgsToPromote;
937   SmallPtrSet<Argument *, 8> ByValArgsToTransform;
938   for (Argument *PtrArg : PointerArgs) {
939     Type *AgTy = PtrArg->getType()->getPointerElementType();
940 
941     // Replace sret attribute with noalias. This reduces register pressure by
942     // avoiding a register copy.
943     if (PtrArg->hasStructRetAttr()) {
944       unsigned ArgNo = PtrArg->getArgNo();
945       F->removeParamAttr(ArgNo, Attribute::StructRet);
946       F->addParamAttr(ArgNo, Attribute::NoAlias);
947       for (Use &U : F->uses()) {
948         CallBase &CB = cast<CallBase>(*U.getUser());
949         CB.removeParamAttr(ArgNo, Attribute::StructRet);
950         CB.addParamAttr(ArgNo, Attribute::NoAlias);
951       }
952     }
953 
954     // If this is a byval argument, and if the aggregate type is small, just
955     // pass the elements, which is always safe, if the passed value is densely
956     // packed or if we can prove the padding bytes are never accessed.
957     //
958     // Only handle arguments with specified alignment; if it's unspecified, the
959     // actual alignment of the argument is target-specific.
960     bool isSafeToPromote = PtrArg->hasByValAttr() && PtrArg->getParamAlign() &&
961                            (ArgumentPromotionPass::isDenselyPacked(AgTy, DL) ||
962                             !canPaddingBeAccessed(PtrArg));
963     if (isSafeToPromote) {
964       if (StructType *STy = dyn_cast<StructType>(AgTy)) {
965         if (MaxElements > 0 && STy->getNumElements() > MaxElements) {
966           LLVM_DEBUG(dbgs() << "argpromotion disable promoting argument '"
967                             << PtrArg->getName()
968                             << "' because it would require adding more"
969                             << " than " << MaxElements
970                             << " arguments to the function.\n");
971           continue;
972         }
973 
974         // If all the elements are single-value types, we can promote it.
975         bool AllSimple = true;
976         for (const auto *EltTy : STy->elements()) {
977           if (!EltTy->isSingleValueType()) {
978             AllSimple = false;
979             break;
980           }
981         }
982 
983         // Safe to transform, don't even bother trying to "promote" it.
984         // Passing the elements as a scalar will allow sroa to hack on
985         // the new alloca we introduce.
986         if (AllSimple) {
987           ByValArgsToTransform.insert(PtrArg);
988           continue;
989         }
990       }
991     }
992 
993     // If the argument is a recursive type and we're in a recursive
994     // function, we could end up infinitely peeling the function argument.
995     if (isSelfRecursive) {
996       if (StructType *STy = dyn_cast<StructType>(AgTy)) {
997         bool RecursiveType =
998             llvm::is_contained(STy->elements(), PtrArg->getType());
999         if (RecursiveType)
1000           continue;
1001       }
1002     }
1003 
1004     // Otherwise, see if we can promote the pointer to its value.
1005     Type *ByValTy =
1006         PtrArg->hasByValAttr() ? PtrArg->getParamByValType() : nullptr;
1007     if (isSafeToPromoteArgument(PtrArg, ByValTy, AAR, MaxElements))
1008       ArgsToPromote.insert(PtrArg);
1009   }
1010 
1011   // No promotable pointer arguments.
1012   if (ArgsToPromote.empty() && ByValArgsToTransform.empty())
1013     return nullptr;
1014 
1015   if (!areFunctionArgsABICompatible(
1016           *F, TTI, ArgsToPromote, ByValArgsToTransform))
1017     return nullptr;
1018 
1019   return doPromotion(F, ArgsToPromote, ByValArgsToTransform, ReplaceCallSite);
1020 }
1021 
1022 PreservedAnalyses ArgumentPromotionPass::run(LazyCallGraph::SCC &C,
1023                                              CGSCCAnalysisManager &AM,
1024                                              LazyCallGraph &CG,
1025                                              CGSCCUpdateResult &UR) {
1026   bool Changed = false, LocalChange;
1027 
1028   // Iterate until we stop promoting from this SCC.
1029   do {
1030     LocalChange = false;
1031 
1032     FunctionAnalysisManager &FAM =
1033         AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
1034 
1035     for (LazyCallGraph::Node &N : C) {
1036       Function &OldF = N.getFunction();
1037 
1038       // FIXME: This lambda must only be used with this function. We should
1039       // skip the lambda and just get the AA results directly.
1040       auto AARGetter = [&](Function &F) -> AAResults & {
1041         assert(&F == &OldF && "Called with an unexpected function!");
1042         return FAM.getResult<AAManager>(F);
1043       };
1044 
1045       const TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(OldF);
1046       Function *NewF =
1047           promoteArguments(&OldF, AARGetter, MaxElements, None, TTI);
1048       if (!NewF)
1049         continue;
1050       LocalChange = true;
1051 
1052       // Directly substitute the functions in the call graph. Note that this
1053       // requires the old function to be completely dead and completely
1054       // replaced by the new function. It does no call graph updates, it merely
1055       // swaps out the particular function mapped to a particular node in the
1056       // graph.
1057       C.getOuterRefSCC().replaceNodeFunction(N, *NewF);
1058       FAM.clear(OldF, OldF.getName());
1059       OldF.eraseFromParent();
1060 
1061       PreservedAnalyses FuncPA;
1062       FuncPA.preserveSet<CFGAnalyses>();
1063       for (auto *U : NewF->users()) {
1064         auto *UserF = cast<CallBase>(U)->getFunction();
1065         FAM.invalidate(*UserF, FuncPA);
1066       }
1067     }
1068 
1069     Changed |= LocalChange;
1070   } while (LocalChange);
1071 
1072   if (!Changed)
1073     return PreservedAnalyses::all();
1074 
1075   PreservedAnalyses PA;
1076   // We've cleared out analyses for deleted functions.
1077   PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1078   // We've manually invalidated analyses for functions we've modified.
1079   PA.preserveSet<AllAnalysesOn<Function>>();
1080   return PA;
1081 }
1082 
1083 namespace {
1084 
1085 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
1086 struct ArgPromotion : public CallGraphSCCPass {
1087   // Pass identification, replacement for typeid
1088   static char ID;
1089 
1090   explicit ArgPromotion(unsigned MaxElements = 3)
1091       : CallGraphSCCPass(ID), MaxElements(MaxElements) {
1092     initializeArgPromotionPass(*PassRegistry::getPassRegistry());
1093   }
1094 
1095   void getAnalysisUsage(AnalysisUsage &AU) const override {
1096     AU.addRequired<AssumptionCacheTracker>();
1097     AU.addRequired<TargetLibraryInfoWrapperPass>();
1098     AU.addRequired<TargetTransformInfoWrapperPass>();
1099     getAAResultsAnalysisUsage(AU);
1100     CallGraphSCCPass::getAnalysisUsage(AU);
1101   }
1102 
1103   bool runOnSCC(CallGraphSCC &SCC) override;
1104 
1105 private:
1106   using llvm::Pass::doInitialization;
1107 
1108   bool doInitialization(CallGraph &CG) override;
1109 
1110   /// The maximum number of elements to expand, or 0 for unlimited.
1111   unsigned MaxElements;
1112 };
1113 
1114 } // end anonymous namespace
1115 
1116 char ArgPromotion::ID = 0;
1117 
1118 INITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion",
1119                       "Promote 'by reference' arguments to scalars", false,
1120                       false)
1121 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1122 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1123 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1124 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1125 INITIALIZE_PASS_END(ArgPromotion, "argpromotion",
1126                     "Promote 'by reference' arguments to scalars", false, false)
1127 
1128 Pass *llvm::createArgumentPromotionPass(unsigned MaxElements) {
1129   return new ArgPromotion(MaxElements);
1130 }
1131 
1132 bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
1133   if (skipSCC(SCC))
1134     return false;
1135 
1136   // Get the callgraph information that we need to update to reflect our
1137   // changes.
1138   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1139 
1140   LegacyAARGetter AARGetter(*this);
1141 
1142   bool Changed = false, LocalChange;
1143 
1144   // Iterate until we stop promoting from this SCC.
1145   do {
1146     LocalChange = false;
1147     // Attempt to promote arguments from all functions in this SCC.
1148     for (CallGraphNode *OldNode : SCC) {
1149       Function *OldF = OldNode->getFunction();
1150       if (!OldF)
1151         continue;
1152 
1153       auto ReplaceCallSite = [&](CallBase &OldCS, CallBase &NewCS) {
1154         Function *Caller = OldCS.getParent()->getParent();
1155         CallGraphNode *NewCalleeNode =
1156             CG.getOrInsertFunction(NewCS.getCalledFunction());
1157         CallGraphNode *CallerNode = CG[Caller];
1158         CallerNode->replaceCallEdge(cast<CallBase>(OldCS),
1159                                     cast<CallBase>(NewCS), NewCalleeNode);
1160       };
1161 
1162       const TargetTransformInfo &TTI =
1163           getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*OldF);
1164       if (Function *NewF = promoteArguments(OldF, AARGetter, MaxElements,
1165                                             {ReplaceCallSite}, TTI)) {
1166         LocalChange = true;
1167 
1168         // Update the call graph for the newly promoted function.
1169         CallGraphNode *NewNode = CG.getOrInsertFunction(NewF);
1170         NewNode->stealCalledFunctionsFrom(OldNode);
1171         if (OldNode->getNumReferences() == 0)
1172           delete CG.removeFunctionFromModule(OldNode);
1173         else
1174           OldF->setLinkage(Function::ExternalLinkage);
1175 
1176         // And updat ethe SCC we're iterating as well.
1177         SCC.ReplaceNode(OldNode, NewNode);
1178       }
1179     }
1180     // Remember that we changed something.
1181     Changed |= LocalChange;
1182   } while (LocalChange);
1183 
1184   return Changed;
1185 }
1186 
1187 bool ArgPromotion::doInitialization(CallGraph &CG) {
1188   return CallGraphSCCPass::doInitialization(CG);
1189 }
1190