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