1 //===- DeadArgumentElimination.cpp - Eliminate dead 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 deletes dead arguments from internal functions.  Dead argument
10 // elimination removes arguments which are directly dead, as well as arguments
11 // only passed into function calls as dead arguments of other functions.  This
12 // pass also deletes dead return values in a similar way.
13 //
14 // This pass is often useful as a cleanup pass to run after aggressive
15 // interprocedural passes, which add possibly-dead arguments or return values.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/IR/Argument.h"
23 #include "llvm/IR/Attributes.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/InstrTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/PassManager.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/IR/Use.h"
37 #include "llvm/IR/User.h"
38 #include "llvm/IR/Value.h"
39 #include "llvm/InitializePasses.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Transforms/IPO.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include <cassert>
47 #include <cstdint>
48 #include <utility>
49 #include <vector>
50 
51 using namespace llvm;
52 
53 #define DEBUG_TYPE "deadargelim"
54 
55 STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
56 STATISTIC(NumRetValsEliminated  , "Number of unused return values removed");
57 STATISTIC(NumArgumentsReplacedWithUndef,
58           "Number of unread args replaced with undef");
59 
60 namespace {
61 
62   /// DAE - The dead argument elimination pass.
63   class DAE : public ModulePass {
64   protected:
65     // DAH uses this to specify a different ID.
66     explicit DAE(char &ID) : ModulePass(ID) {}
67 
68   public:
69     static char ID; // Pass identification, replacement for typeid
70 
71     DAE() : ModulePass(ID) {
72       initializeDAEPass(*PassRegistry::getPassRegistry());
73     }
74 
75     bool runOnModule(Module &M) override {
76       if (skipModule(M))
77         return false;
78       DeadArgumentEliminationPass DAEP(ShouldHackArguments());
79       ModuleAnalysisManager DummyMAM;
80       PreservedAnalyses PA = DAEP.run(M, DummyMAM);
81       return !PA.areAllPreserved();
82     }
83 
84     virtual bool ShouldHackArguments() const { return false; }
85   };
86 
87 } // end anonymous namespace
88 
89 char DAE::ID = 0;
90 
91 INITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false)
92 
93 namespace {
94 
95   /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
96   /// deletes arguments to functions which are external.  This is only for use
97   /// by bugpoint.
98   struct DAH : public DAE {
99     static char ID;
100 
101     DAH() : DAE(ID) {}
102 
103     bool ShouldHackArguments() const override { return true; }
104   };
105 
106 } // end anonymous namespace
107 
108 char DAH::ID = 0;
109 
110 INITIALIZE_PASS(DAH, "deadarghaX0r",
111                 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)",
112                 false, false)
113 
114 /// createDeadArgEliminationPass - This pass removes arguments from functions
115 /// which are not used by the body of the function.
116 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
117 
118 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
119 
120 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if
121 /// llvm.vastart is never called, the varargs list is dead for the function.
122 bool DeadArgumentEliminationPass::DeleteDeadVarargs(Function &Fn) {
123   assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
124   if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false;
125 
126   // Ensure that the function is only directly called.
127   if (Fn.hasAddressTaken())
128     return false;
129 
130   // Don't touch naked functions. The assembly might be using an argument, or
131   // otherwise rely on the frame layout in a way that this analysis will not
132   // see.
133   if (Fn.hasFnAttribute(Attribute::Naked)) {
134     return false;
135   }
136 
137   // Okay, we know we can transform this function if safe.  Scan its body
138   // looking for calls marked musttail or calls to llvm.vastart.
139   for (BasicBlock &BB : Fn) {
140     for (Instruction &I : BB) {
141       CallInst *CI = dyn_cast<CallInst>(&I);
142       if (!CI)
143         continue;
144       if (CI->isMustTailCall())
145         return false;
146       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
147         if (II->getIntrinsicID() == Intrinsic::vastart)
148           return false;
149       }
150     }
151   }
152 
153   // If we get here, there are no calls to llvm.vastart in the function body,
154   // remove the "..." and adjust all the calls.
155 
156   // Start by computing a new prototype for the function, which is the same as
157   // the old function, but doesn't have isVarArg set.
158   FunctionType *FTy = Fn.getFunctionType();
159 
160   std::vector<Type *> Params(FTy->param_begin(), FTy->param_end());
161   FunctionType *NFTy = FunctionType::get(FTy->getReturnType(),
162                                                 Params, false);
163   unsigned NumArgs = Params.size();
164 
165   // Create the new function body and insert it into the module...
166   Function *NF = Function::Create(NFTy, Fn.getLinkage(), Fn.getAddressSpace());
167   NF->copyAttributesFrom(&Fn);
168   NF->setComdat(Fn.getComdat());
169   Fn.getParent()->getFunctionList().insert(Fn.getIterator(), NF);
170   NF->takeName(&Fn);
171 
172   // Loop over all of the callers of the function, transforming the call sites
173   // to pass in a smaller number of arguments into the new function.
174   //
175   std::vector<Value *> Args;
176   for (Value::user_iterator I = Fn.user_begin(), E = Fn.user_end(); I != E; ) {
177     CallBase *CB = dyn_cast<CallBase>(*I++);
178     if (!CB)
179       continue;
180 
181     // Pass all the same arguments.
182     Args.assign(CB->arg_begin(), CB->arg_begin() + NumArgs);
183 
184     // Drop any attributes that were on the vararg arguments.
185     AttributeList PAL = CB->getAttributes();
186     if (!PAL.isEmpty()) {
187       SmallVector<AttributeSet, 8> ArgAttrs;
188       for (unsigned ArgNo = 0; ArgNo < NumArgs; ++ArgNo)
189         ArgAttrs.push_back(PAL.getParamAttributes(ArgNo));
190       PAL = AttributeList::get(Fn.getContext(), PAL.getFnAttributes(),
191                                PAL.getRetAttributes(), ArgAttrs);
192     }
193 
194     SmallVector<OperandBundleDef, 1> OpBundles;
195     CB->getOperandBundlesAsDefs(OpBundles);
196 
197     CallBase *NewCB = nullptr;
198     if (InvokeInst *II = dyn_cast<InvokeInst>(CB)) {
199       NewCB = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
200                                  Args, OpBundles, "", CB);
201     } else {
202       NewCB = CallInst::Create(NF, Args, OpBundles, "", CB);
203       cast<CallInst>(NewCB)->setTailCallKind(
204           cast<CallInst>(CB)->getTailCallKind());
205     }
206     NewCB->setCallingConv(CB->getCallingConv());
207     NewCB->setAttributes(PAL);
208     NewCB->setDebugLoc(CB->getDebugLoc());
209     uint64_t W;
210     if (CB->extractProfTotalWeight(W))
211       NewCB->setProfWeight(W);
212 
213     Args.clear();
214 
215     if (!CB->use_empty())
216       CB->replaceAllUsesWith(NewCB);
217 
218     NewCB->takeName(CB);
219 
220     // Finally, remove the old call from the program, reducing the use-count of
221     // F.
222     CB->eraseFromParent();
223   }
224 
225   // Since we have now created the new function, splice the body of the old
226   // function right into the new function, leaving the old rotting hulk of the
227   // function empty.
228   NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
229 
230   // Loop over the argument list, transferring uses of the old arguments over to
231   // the new arguments, also transferring over the names as well.  While we're at
232   // it, remove the dead arguments from the DeadArguments list.
233   for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
234        I2 = NF->arg_begin(); I != E; ++I, ++I2) {
235     // Move the name and users over to the new version.
236     I->replaceAllUsesWith(&*I2);
237     I2->takeName(&*I);
238   }
239 
240   // Clone metadatas from the old function, including debug info descriptor.
241   SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
242   Fn.getAllMetadata(MDs);
243   for (auto MD : MDs)
244     NF->addMetadata(MD.first, *MD.second);
245 
246   // Fix up any BlockAddresses that refer to the function.
247   Fn.replaceAllUsesWith(ConstantExpr::getBitCast(NF, Fn.getType()));
248   // Delete the bitcast that we just created, so that NF does not
249   // appear to be address-taken.
250   NF->removeDeadConstantUsers();
251   // Finally, nuke the old function.
252   Fn.eraseFromParent();
253   return true;
254 }
255 
256 /// RemoveDeadArgumentsFromCallers - Checks if the given function has any
257 /// arguments that are unused, and changes the caller parameters to be undefined
258 /// instead.
259 bool DeadArgumentEliminationPass::RemoveDeadArgumentsFromCallers(Function &Fn) {
260   // We cannot change the arguments if this TU does not define the function or
261   // if the linker may choose a function body from another TU, even if the
262   // nominal linkage indicates that other copies of the function have the same
263   // semantics. In the below example, the dead load from %p may not have been
264   // eliminated from the linker-chosen copy of f, so replacing %p with undef
265   // in callers may introduce undefined behavior.
266   //
267   // define linkonce_odr void @f(i32* %p) {
268   //   %v = load i32 %p
269   //   ret void
270   // }
271   if (!Fn.hasExactDefinition())
272     return false;
273 
274   // Functions with local linkage should already have been handled, except the
275   // fragile (variadic) ones which we can improve here.
276   if (Fn.hasLocalLinkage() && !Fn.getFunctionType()->isVarArg())
277     return false;
278 
279   // Don't touch naked functions. The assembly might be using an argument, or
280   // otherwise rely on the frame layout in a way that this analysis will not
281   // see.
282   if (Fn.hasFnAttribute(Attribute::Naked))
283     return false;
284 
285   if (Fn.use_empty())
286     return false;
287 
288   SmallVector<unsigned, 8> UnusedArgs;
289   bool Changed = false;
290 
291   for (Argument &Arg : Fn.args()) {
292     if (!Arg.hasSwiftErrorAttr() && Arg.use_empty() &&
293         !Arg.hasPassPointeeByValueAttr()) {
294       if (Arg.isUsedByMetadata()) {
295         Arg.replaceAllUsesWith(UndefValue::get(Arg.getType()));
296         Changed = true;
297       }
298       UnusedArgs.push_back(Arg.getArgNo());
299     }
300   }
301 
302   if (UnusedArgs.empty())
303     return false;
304 
305   for (Use &U : Fn.uses()) {
306     CallBase *CB = dyn_cast<CallBase>(U.getUser());
307     if (!CB || !CB->isCallee(&U))
308       continue;
309 
310     // Now go through all unused args and replace them with "undef".
311     for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) {
312       unsigned ArgNo = UnusedArgs[I];
313 
314       Value *Arg = CB->getArgOperand(ArgNo);
315       CB->setArgOperand(ArgNo, UndefValue::get(Arg->getType()));
316       ++NumArgumentsReplacedWithUndef;
317       Changed = true;
318     }
319   }
320 
321   return Changed;
322 }
323 
324 /// Convenience function that returns the number of return values. It returns 0
325 /// for void functions and 1 for functions not returning a struct. It returns
326 /// the number of struct elements for functions returning a struct.
327 static unsigned NumRetVals(const Function *F) {
328   Type *RetTy = F->getReturnType();
329   if (RetTy->isVoidTy())
330     return 0;
331   else if (StructType *STy = dyn_cast<StructType>(RetTy))
332     return STy->getNumElements();
333   else if (ArrayType *ATy = dyn_cast<ArrayType>(RetTy))
334     return ATy->getNumElements();
335   else
336     return 1;
337 }
338 
339 /// Returns the sub-type a function will return at a given Idx. Should
340 /// correspond to the result type of an ExtractValue instruction executed with
341 /// just that one Idx (i.e. only top-level structure is considered).
342 static Type *getRetComponentType(const Function *F, unsigned Idx) {
343   Type *RetTy = F->getReturnType();
344   assert(!RetTy->isVoidTy() && "void type has no subtype");
345 
346   if (StructType *STy = dyn_cast<StructType>(RetTy))
347     return STy->getElementType(Idx);
348   else if (ArrayType *ATy = dyn_cast<ArrayType>(RetTy))
349     return ATy->getElementType();
350   else
351     return RetTy;
352 }
353 
354 /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
355 /// live, it adds Use to the MaybeLiveUses argument. Returns the determined
356 /// liveness of Use.
357 DeadArgumentEliminationPass::Liveness
358 DeadArgumentEliminationPass::MarkIfNotLive(RetOrArg Use,
359                                            UseVector &MaybeLiveUses) {
360   // We're live if our use or its Function is already marked as live.
361   if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
362     return Live;
363 
364   // We're maybe live otherwise, but remember that we must become live if
365   // Use becomes live.
366   MaybeLiveUses.push_back(Use);
367   return MaybeLive;
368 }
369 
370 /// SurveyUse - This looks at a single use of an argument or return value
371 /// and determines if it should be alive or not. Adds this use to MaybeLiveUses
372 /// if it causes the used value to become MaybeLive.
373 ///
374 /// RetValNum is the return value number to use when this use is used in a
375 /// return instruction. This is used in the recursion, you should always leave
376 /// it at 0.
377 DeadArgumentEliminationPass::Liveness
378 DeadArgumentEliminationPass::SurveyUse(const Use *U, UseVector &MaybeLiveUses,
379                                        unsigned RetValNum) {
380     const User *V = U->getUser();
381     if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
382       // The value is returned from a function. It's only live when the
383       // function's return value is live. We use RetValNum here, for the case
384       // that U is really a use of an insertvalue instruction that uses the
385       // original Use.
386       const Function *F = RI->getParent()->getParent();
387       if (RetValNum != -1U) {
388         RetOrArg Use = CreateRet(F, RetValNum);
389         // We might be live, depending on the liveness of Use.
390         return MarkIfNotLive(Use, MaybeLiveUses);
391       } else {
392         DeadArgumentEliminationPass::Liveness Result = MaybeLive;
393         for (unsigned Ri = 0; Ri < NumRetVals(F); ++Ri) {
394           RetOrArg Use = CreateRet(F, Ri);
395           // We might be live, depending on the liveness of Use. If any
396           // sub-value is live, then the entire value is considered live. This
397           // is a conservative choice, and better tracking is possible.
398           DeadArgumentEliminationPass::Liveness SubResult =
399               MarkIfNotLive(Use, MaybeLiveUses);
400           if (Result != Live)
401             Result = SubResult;
402         }
403         return Result;
404       }
405     }
406     if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
407       if (U->getOperandNo() != InsertValueInst::getAggregateOperandIndex()
408           && IV->hasIndices())
409         // The use we are examining is inserted into an aggregate. Our liveness
410         // depends on all uses of that aggregate, but if it is used as a return
411         // value, only index at which we were inserted counts.
412         RetValNum = *IV->idx_begin();
413 
414       // Note that if we are used as the aggregate operand to the insertvalue,
415       // we don't change RetValNum, but do survey all our uses.
416 
417       Liveness Result = MaybeLive;
418       for (const Use &UU : IV->uses()) {
419         Result = SurveyUse(&UU, MaybeLiveUses, RetValNum);
420         if (Result == Live)
421           break;
422       }
423       return Result;
424     }
425 
426     if (const auto *CB = dyn_cast<CallBase>(V)) {
427       const Function *F = CB->getCalledFunction();
428       if (F) {
429         // Used in a direct call.
430 
431         // The function argument is live if it is used as a bundle operand.
432         if (CB->isBundleOperand(U))
433           return Live;
434 
435         // Find the argument number. We know for sure that this use is an
436         // argument, since if it was the function argument this would be an
437         // indirect call and the we know can't be looking at a value of the
438         // label type (for the invoke instruction).
439         unsigned ArgNo = CB->getArgOperandNo(U);
440 
441         if (ArgNo >= F->getFunctionType()->getNumParams())
442           // The value is passed in through a vararg! Must be live.
443           return Live;
444 
445         assert(CB->getArgOperand(ArgNo) == CB->getOperand(U->getOperandNo()) &&
446                "Argument is not where we expected it");
447 
448         // Value passed to a normal call. It's only live when the corresponding
449         // argument to the called function turns out live.
450         RetOrArg Use = CreateArg(F, ArgNo);
451         return MarkIfNotLive(Use, MaybeLiveUses);
452       }
453     }
454     // Used in any other way? Value must be live.
455     return Live;
456 }
457 
458 /// SurveyUses - This looks at all the uses of the given value
459 /// Returns the Liveness deduced from the uses of this value.
460 ///
461 /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
462 /// the result is Live, MaybeLiveUses might be modified but its content should
463 /// be ignored (since it might not be complete).
464 DeadArgumentEliminationPass::Liveness
465 DeadArgumentEliminationPass::SurveyUses(const Value *V,
466                                         UseVector &MaybeLiveUses) {
467   // Assume it's dead (which will only hold if there are no uses at all..).
468   Liveness Result = MaybeLive;
469   // Check each use.
470   for (const Use &U : V->uses()) {
471     Result = SurveyUse(&U, MaybeLiveUses);
472     if (Result == Live)
473       break;
474   }
475   return Result;
476 }
477 
478 // SurveyFunction - This performs the initial survey of the specified function,
479 // checking out whether or not it uses any of its incoming arguments or whether
480 // any callers use the return value.  This fills in the LiveValues set and Uses
481 // map.
482 //
483 // We consider arguments of non-internal functions to be intrinsically alive as
484 // well as arguments to functions which have their "address taken".
485 void DeadArgumentEliminationPass::SurveyFunction(const Function &F) {
486   // Functions with inalloca parameters are expecting args in a particular
487   // register and memory layout.
488   if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca)) {
489     MarkLive(F);
490     return;
491   }
492 
493   // Don't touch naked functions. The assembly might be using an argument, or
494   // otherwise rely on the frame layout in a way that this analysis will not
495   // see.
496   if (F.hasFnAttribute(Attribute::Naked)) {
497     MarkLive(F);
498     return;
499   }
500 
501   unsigned RetCount = NumRetVals(&F);
502 
503   // Assume all return values are dead
504   using RetVals = SmallVector<Liveness, 5>;
505 
506   RetVals RetValLiveness(RetCount, MaybeLive);
507 
508   using RetUses = SmallVector<UseVector, 5>;
509 
510   // These vectors map each return value to the uses that make it MaybeLive, so
511   // we can add those to the Uses map if the return value really turns out to be
512   // MaybeLive. Initialized to a list of RetCount empty lists.
513   RetUses MaybeLiveRetUses(RetCount);
514 
515   bool HasMustTailCalls = false;
516 
517   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
518     if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
519       if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
520           != F.getFunctionType()->getReturnType()) {
521         // We don't support old style multiple return values.
522         MarkLive(F);
523         return;
524       }
525     }
526 
527     // If we have any returns of `musttail` results - the signature can't
528     // change
529     if (BB->getTerminatingMustTailCall() != nullptr)
530       HasMustTailCalls = true;
531   }
532 
533   if (HasMustTailCalls) {
534     LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - " << F.getName()
535                       << " has musttail calls\n");
536   }
537 
538   if (!F.hasLocalLinkage() && (!ShouldHackArguments || F.isIntrinsic())) {
539     MarkLive(F);
540     return;
541   }
542 
543   LLVM_DEBUG(
544       dbgs() << "DeadArgumentEliminationPass - Inspecting callers for fn: "
545              << F.getName() << "\n");
546   // Keep track of the number of live retvals, so we can skip checks once all
547   // of them turn out to be live.
548   unsigned NumLiveRetVals = 0;
549 
550   bool HasMustTailCallers = false;
551 
552   // Loop all uses of the function.
553   for (const Use &U : F.uses()) {
554     // If the function is PASSED IN as an argument, its address has been
555     // taken.
556     const auto *CB = dyn_cast<CallBase>(U.getUser());
557     if (!CB || !CB->isCallee(&U)) {
558       MarkLive(F);
559       return;
560     }
561 
562     // The number of arguments for `musttail` call must match the number of
563     // arguments of the caller
564     if (CB->isMustTailCall())
565       HasMustTailCallers = true;
566 
567     // If we end up here, we are looking at a direct call to our function.
568 
569     // Now, check how our return value(s) is/are used in this caller. Don't
570     // bother checking return values if all of them are live already.
571     if (NumLiveRetVals == RetCount)
572       continue;
573 
574     // Check all uses of the return value.
575     for (const Use &U : CB->uses()) {
576       if (ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(U.getUser())) {
577         // This use uses a part of our return value, survey the uses of
578         // that part and store the results for this index only.
579         unsigned Idx = *Ext->idx_begin();
580         if (RetValLiveness[Idx] != Live) {
581           RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
582           if (RetValLiveness[Idx] == Live)
583             NumLiveRetVals++;
584         }
585       } else {
586         // Used by something else than extractvalue. Survey, but assume that the
587         // result applies to all sub-values.
588         UseVector MaybeLiveAggregateUses;
589         if (SurveyUse(&U, MaybeLiveAggregateUses) == Live) {
590           NumLiveRetVals = RetCount;
591           RetValLiveness.assign(RetCount, Live);
592           break;
593         } else {
594           for (unsigned Ri = 0; Ri != RetCount; ++Ri) {
595             if (RetValLiveness[Ri] != Live)
596               MaybeLiveRetUses[Ri].append(MaybeLiveAggregateUses.begin(),
597                                           MaybeLiveAggregateUses.end());
598           }
599         }
600       }
601     }
602   }
603 
604   if (HasMustTailCallers) {
605     LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - " << F.getName()
606                       << " has musttail callers\n");
607   }
608 
609   // Now we've inspected all callers, record the liveness of our return values.
610   for (unsigned Ri = 0; Ri != RetCount; ++Ri)
611     MarkValue(CreateRet(&F, Ri), RetValLiveness[Ri], MaybeLiveRetUses[Ri]);
612 
613   LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Inspecting args for fn: "
614                     << F.getName() << "\n");
615 
616   // Now, check all of our arguments.
617   unsigned ArgI = 0;
618   UseVector MaybeLiveArgUses;
619   for (Function::const_arg_iterator AI = F.arg_begin(), E = F.arg_end();
620        AI != E; ++AI, ++ArgI) {
621     Liveness Result;
622     if (F.getFunctionType()->isVarArg() || HasMustTailCallers ||
623         HasMustTailCalls) {
624       // Variadic functions will already have a va_arg function expanded inside
625       // them, making them potentially very sensitive to ABI changes resulting
626       // from removing arguments entirely, so don't. For example AArch64 handles
627       // register and stack HFAs very differently, and this is reflected in the
628       // IR which has already been generated.
629       //
630       // `musttail` calls to this function restrict argument removal attempts.
631       // The signature of the caller must match the signature of the function.
632       //
633       // `musttail` calls in this function prevents us from changing its
634       // signature
635       Result = Live;
636     } else {
637       // See what the effect of this use is (recording any uses that cause
638       // MaybeLive in MaybeLiveArgUses).
639       Result = SurveyUses(&*AI, MaybeLiveArgUses);
640     }
641 
642     // Mark the result.
643     MarkValue(CreateArg(&F, ArgI), Result, MaybeLiveArgUses);
644     // Clear the vector again for the next iteration.
645     MaybeLiveArgUses.clear();
646   }
647 }
648 
649 /// MarkValue - This function marks the liveness of RA depending on L. If L is
650 /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
651 /// such that RA will be marked live if any use in MaybeLiveUses gets marked
652 /// live later on.
653 void DeadArgumentEliminationPass::MarkValue(const RetOrArg &RA, Liveness L,
654                                             const UseVector &MaybeLiveUses) {
655   switch (L) {
656     case Live:
657       MarkLive(RA);
658       break;
659     case MaybeLive:
660       // Note any uses of this value, so this return value can be
661       // marked live whenever one of the uses becomes live.
662       for (const auto &MaybeLiveUse : MaybeLiveUses)
663         Uses.insert(std::make_pair(MaybeLiveUse, RA));
664       break;
665   }
666 }
667 
668 /// MarkLive - Mark the given Function as alive, meaning that it cannot be
669 /// changed in any way. Additionally,
670 /// mark any values that are used as this function's parameters or by its return
671 /// values (according to Uses) live as well.
672 void DeadArgumentEliminationPass::MarkLive(const Function &F) {
673   LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Intrinsically live fn: "
674                     << F.getName() << "\n");
675   // Mark the function as live.
676   LiveFunctions.insert(&F);
677   // Mark all arguments as live.
678   for (unsigned ArgI = 0, E = F.arg_size(); ArgI != E; ++ArgI)
679     PropagateLiveness(CreateArg(&F, ArgI));
680   // Mark all return values as live.
681   for (unsigned Ri = 0, E = NumRetVals(&F); Ri != E; ++Ri)
682     PropagateLiveness(CreateRet(&F, Ri));
683 }
684 
685 /// MarkLive - Mark the given return value or argument as live. Additionally,
686 /// mark any values that are used by this value (according to Uses) live as
687 /// well.
688 void DeadArgumentEliminationPass::MarkLive(const RetOrArg &RA) {
689   if (LiveFunctions.count(RA.F))
690     return; // Function was already marked Live.
691 
692   if (!LiveValues.insert(RA).second)
693     return; // We were already marked Live.
694 
695   LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Marking "
696                     << RA.getDescription() << " live\n");
697   PropagateLiveness(RA);
698 }
699 
700 /// PropagateLiveness - Given that RA is a live value, propagate it's liveness
701 /// to any other values it uses (according to Uses).
702 void DeadArgumentEliminationPass::PropagateLiveness(const RetOrArg &RA) {
703   // We don't use upper_bound (or equal_range) here, because our recursive call
704   // to ourselves is likely to cause the upper_bound (which is the first value
705   // not belonging to RA) to become erased and the iterator invalidated.
706   UseMap::iterator Begin = Uses.lower_bound(RA);
707   UseMap::iterator E = Uses.end();
708   UseMap::iterator I;
709   for (I = Begin; I != E && I->first == RA; ++I)
710     MarkLive(I->second);
711 
712   // Erase RA from the Uses map (from the lower bound to wherever we ended up
713   // after the loop).
714   Uses.erase(Begin, I);
715 }
716 
717 // RemoveDeadStuffFromFunction - Remove any arguments and return values from F
718 // that are not in LiveValues. Transform the function and all of the callees of
719 // the function to not have these arguments and return values.
720 //
721 bool DeadArgumentEliminationPass::RemoveDeadStuffFromFunction(Function *F) {
722   // Don't modify fully live functions
723   if (LiveFunctions.count(F))
724     return false;
725 
726   // Start by computing a new prototype for the function, which is the same as
727   // the old function, but has fewer arguments and a different return type.
728   FunctionType *FTy = F->getFunctionType();
729   std::vector<Type*> Params;
730 
731   // Keep track of if we have a live 'returned' argument
732   bool HasLiveReturnedArg = false;
733 
734   // Set up to build a new list of parameter attributes.
735   SmallVector<AttributeSet, 8> ArgAttrVec;
736   const AttributeList &PAL = F->getAttributes();
737 
738   // Remember which arguments are still alive.
739   SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
740   // Construct the new parameter list from non-dead arguments. Also construct
741   // a new set of parameter attributes to correspond. Skip the first parameter
742   // attribute, since that belongs to the return value.
743   unsigned ArgI = 0;
744   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
745        ++I, ++ArgI) {
746     RetOrArg Arg = CreateArg(F, ArgI);
747     if (LiveValues.erase(Arg)) {
748       Params.push_back(I->getType());
749       ArgAlive[ArgI] = true;
750       ArgAttrVec.push_back(PAL.getParamAttributes(ArgI));
751       HasLiveReturnedArg |= PAL.hasParamAttribute(ArgI, Attribute::Returned);
752     } else {
753       ++NumArgumentsEliminated;
754       LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Removing argument "
755                         << ArgI << " (" << I->getName() << ") from "
756                         << F->getName() << "\n");
757     }
758   }
759 
760   // Find out the new return value.
761   Type *RetTy = FTy->getReturnType();
762   Type *NRetTy = nullptr;
763   unsigned RetCount = NumRetVals(F);
764 
765   // -1 means unused, other numbers are the new index
766   SmallVector<int, 5> NewRetIdxs(RetCount, -1);
767   std::vector<Type*> RetTypes;
768 
769   // If there is a function with a live 'returned' argument but a dead return
770   // value, then there are two possible actions:
771   // 1) Eliminate the return value and take off the 'returned' attribute on the
772   //    argument.
773   // 2) Retain the 'returned' attribute and treat the return value (but not the
774   //    entire function) as live so that it is not eliminated.
775   //
776   // It's not clear in the general case which option is more profitable because,
777   // even in the absence of explicit uses of the return value, code generation
778   // is free to use the 'returned' attribute to do things like eliding
779   // save/restores of registers across calls. Whether or not this happens is
780   // target and ABI-specific as well as depending on the amount of register
781   // pressure, so there's no good way for an IR-level pass to figure this out.
782   //
783   // Fortunately, the only places where 'returned' is currently generated by
784   // the FE are places where 'returned' is basically free and almost always a
785   // performance win, so the second option can just be used always for now.
786   //
787   // This should be revisited if 'returned' is ever applied more liberally.
788   if (RetTy->isVoidTy() || HasLiveReturnedArg) {
789     NRetTy = RetTy;
790   } else {
791     // Look at each of the original return values individually.
792     for (unsigned Ri = 0; Ri != RetCount; ++Ri) {
793       RetOrArg Ret = CreateRet(F, Ri);
794       if (LiveValues.erase(Ret)) {
795         RetTypes.push_back(getRetComponentType(F, Ri));
796         NewRetIdxs[Ri] = RetTypes.size() - 1;
797       } else {
798         ++NumRetValsEliminated;
799         LLVM_DEBUG(
800             dbgs() << "DeadArgumentEliminationPass - Removing return value "
801                    << Ri << " from " << F->getName() << "\n");
802       }
803     }
804     if (RetTypes.size() > 1) {
805       // More than one return type? Reduce it down to size.
806       if (StructType *STy = dyn_cast<StructType>(RetTy)) {
807         // Make the new struct packed if we used to return a packed struct
808         // already.
809         NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked());
810       } else {
811         assert(isa<ArrayType>(RetTy) && "unexpected multi-value return");
812         NRetTy = ArrayType::get(RetTypes[0], RetTypes.size());
813       }
814     } else if (RetTypes.size() == 1)
815       // One return type? Just a simple value then, but only if we didn't use to
816       // return a struct with that simple value before.
817       NRetTy = RetTypes.front();
818     else if (RetTypes.empty())
819       // No return types? Make it void, but only if we didn't use to return {}.
820       NRetTy = Type::getVoidTy(F->getContext());
821   }
822 
823   assert(NRetTy && "No new return type found?");
824 
825   // The existing function return attributes.
826   AttrBuilder RAttrs(PAL.getRetAttributes());
827 
828   // Remove any incompatible attributes, but only if we removed all return
829   // values. Otherwise, ensure that we don't have any conflicting attributes
830   // here. Currently, this should not be possible, but special handling might be
831   // required when new return value attributes are added.
832   if (NRetTy->isVoidTy())
833     RAttrs.remove(AttributeFuncs::typeIncompatible(NRetTy));
834   else
835     assert(!RAttrs.overlaps(AttributeFuncs::typeIncompatible(NRetTy)) &&
836            "Return attributes no longer compatible?");
837 
838   AttributeSet RetAttrs = AttributeSet::get(F->getContext(), RAttrs);
839 
840   // Strip allocsize attributes. They might refer to the deleted arguments.
841   AttributeSet FnAttrs = PAL.getFnAttributes().removeAttribute(
842       F->getContext(), Attribute::AllocSize);
843 
844   // Reconstruct the AttributesList based on the vector we constructed.
845   assert(ArgAttrVec.size() == Params.size());
846   AttributeList NewPAL =
847       AttributeList::get(F->getContext(), FnAttrs, RetAttrs, ArgAttrVec);
848 
849   // Create the new function type based on the recomputed parameters.
850   FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
851 
852   // No change?
853   if (NFTy == FTy)
854     return false;
855 
856   // Create the new function body and insert it into the module...
857   Function *NF = Function::Create(NFTy, F->getLinkage(), F->getAddressSpace());
858   NF->copyAttributesFrom(F);
859   NF->setComdat(F->getComdat());
860   NF->setAttributes(NewPAL);
861   // Insert the new function before the old function, so we won't be processing
862   // it again.
863   F->getParent()->getFunctionList().insert(F->getIterator(), NF);
864   NF->takeName(F);
865 
866   // Loop over all of the callers of the function, transforming the call sites
867   // to pass in a smaller number of arguments into the new function.
868   std::vector<Value*> Args;
869   while (!F->use_empty()) {
870     CallBase &CB = cast<CallBase>(*F->user_back());
871 
872     ArgAttrVec.clear();
873     const AttributeList &CallPAL = CB.getAttributes();
874 
875     // Adjust the call return attributes in case the function was changed to
876     // return void.
877     AttrBuilder RAttrs(CallPAL.getRetAttributes());
878     RAttrs.remove(AttributeFuncs::typeIncompatible(NRetTy));
879     AttributeSet RetAttrs = AttributeSet::get(F->getContext(), RAttrs);
880 
881     // Declare these outside of the loops, so we can reuse them for the second
882     // loop, which loops the varargs.
883     auto I = CB.arg_begin();
884     unsigned Pi = 0;
885     // Loop over those operands, corresponding to the normal arguments to the
886     // original function, and add those that are still alive.
887     for (unsigned E = FTy->getNumParams(); Pi != E; ++I, ++Pi)
888       if (ArgAlive[Pi]) {
889         Args.push_back(*I);
890         // Get original parameter attributes, but skip return attributes.
891         AttributeSet Attrs = CallPAL.getParamAttributes(Pi);
892         if (NRetTy != RetTy && Attrs.hasAttribute(Attribute::Returned)) {
893           // If the return type has changed, then get rid of 'returned' on the
894           // call site. The alternative is to make all 'returned' attributes on
895           // call sites keep the return value alive just like 'returned'
896           // attributes on function declaration but it's less clearly a win and
897           // this is not an expected case anyway
898           ArgAttrVec.push_back(AttributeSet::get(
899               F->getContext(),
900               AttrBuilder(Attrs).removeAttribute(Attribute::Returned)));
901         } else {
902           // Otherwise, use the original attributes.
903           ArgAttrVec.push_back(Attrs);
904         }
905       }
906 
907     // Push any varargs arguments on the list. Don't forget their attributes.
908     for (auto E = CB.arg_end(); I != E; ++I, ++Pi) {
909       Args.push_back(*I);
910       ArgAttrVec.push_back(CallPAL.getParamAttributes(Pi));
911     }
912 
913     // Reconstruct the AttributesList based on the vector we constructed.
914     assert(ArgAttrVec.size() == Args.size());
915 
916     // Again, be sure to remove any allocsize attributes, since their indices
917     // may now be incorrect.
918     AttributeSet FnAttrs = CallPAL.getFnAttributes().removeAttribute(
919         F->getContext(), Attribute::AllocSize);
920 
921     AttributeList NewCallPAL = AttributeList::get(
922         F->getContext(), FnAttrs, RetAttrs, ArgAttrVec);
923 
924     SmallVector<OperandBundleDef, 1> OpBundles;
925     CB.getOperandBundlesAsDefs(OpBundles);
926 
927     CallBase *NewCB = nullptr;
928     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
929       NewCB = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
930                                  Args, OpBundles, "", CB.getParent());
931     } else {
932       NewCB = CallInst::Create(NFTy, NF, Args, OpBundles, "", &CB);
933       cast<CallInst>(NewCB)->setTailCallKind(
934           cast<CallInst>(&CB)->getTailCallKind());
935     }
936     NewCB->setCallingConv(CB.getCallingConv());
937     NewCB->setAttributes(NewCallPAL);
938     NewCB->setDebugLoc(CB.getDebugLoc());
939     uint64_t W;
940     if (CB.extractProfTotalWeight(W))
941       NewCB->setProfWeight(W);
942     Args.clear();
943     ArgAttrVec.clear();
944 
945     if (!CB.use_empty() || CB.isUsedByMetadata()) {
946       if (NewCB->getType() == CB.getType()) {
947         // Return type not changed? Just replace users then.
948         CB.replaceAllUsesWith(NewCB);
949         NewCB->takeName(&CB);
950       } else if (NewCB->getType()->isVoidTy()) {
951         // If the return value is dead, replace any uses of it with undef
952         // (any non-debug value uses will get removed later on).
953         if (!CB.getType()->isX86_MMXTy())
954           CB.replaceAllUsesWith(UndefValue::get(CB.getType()));
955       } else {
956         assert((RetTy->isStructTy() || RetTy->isArrayTy()) &&
957                "Return type changed, but not into a void. The old return type"
958                " must have been a struct or an array!");
959         Instruction *InsertPt = &CB;
960         if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
961           BasicBlock *NewEdge =
962               SplitEdge(NewCB->getParent(), II->getNormalDest());
963           InsertPt = &*NewEdge->getFirstInsertionPt();
964         }
965 
966         // We used to return a struct or array. Instead of doing smart stuff
967         // with all the uses, we will just rebuild it using extract/insertvalue
968         // chaining and let instcombine clean that up.
969         //
970         // Start out building up our return value from undef
971         Value *RetVal = UndefValue::get(RetTy);
972         for (unsigned Ri = 0; Ri != RetCount; ++Ri)
973           if (NewRetIdxs[Ri] != -1) {
974             Value *V;
975             if (RetTypes.size() > 1)
976               // We are still returning a struct, so extract the value from our
977               // return value
978               V = ExtractValueInst::Create(NewCB, NewRetIdxs[Ri], "newret",
979                                            InsertPt);
980             else
981               // We are now returning a single element, so just insert that
982               V = NewCB;
983             // Insert the value at the old position
984             RetVal = InsertValueInst::Create(RetVal, V, Ri, "oldret", InsertPt);
985           }
986         // Now, replace all uses of the old call instruction with the return
987         // struct we built
988         CB.replaceAllUsesWith(RetVal);
989         NewCB->takeName(&CB);
990       }
991     }
992 
993     // Finally, remove the old call from the program, reducing the use-count of
994     // F.
995     CB.eraseFromParent();
996   }
997 
998   // Since we have now created the new function, splice the body of the old
999   // function right into the new function, leaving the old rotting hulk of the
1000   // function empty.
1001   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
1002 
1003   // Loop over the argument list, transferring uses of the old arguments over to
1004   // the new arguments, also transferring over the names as well.
1005   ArgI = 0;
1006   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
1007                               I2 = NF->arg_begin();
1008        I != E; ++I, ++ArgI)
1009     if (ArgAlive[ArgI]) {
1010       // If this is a live argument, move the name and users over to the new
1011       // version.
1012       I->replaceAllUsesWith(&*I2);
1013       I2->takeName(&*I);
1014       ++I2;
1015     } else {
1016       // If this argument is dead, replace any uses of it with undef
1017       // (any non-debug value uses will get removed later on).
1018       if (!I->getType()->isX86_MMXTy())
1019         I->replaceAllUsesWith(UndefValue::get(I->getType()));
1020     }
1021 
1022   // If we change the return value of the function we must rewrite any return
1023   // instructions.  Check this now.
1024   if (F->getReturnType() != NF->getReturnType())
1025     for (BasicBlock &BB : *NF)
1026       if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
1027         Value *RetVal = nullptr;
1028 
1029         if (!NFTy->getReturnType()->isVoidTy()) {
1030           assert(RetTy->isStructTy() || RetTy->isArrayTy());
1031           // The original return value was a struct or array, insert
1032           // extractvalue/insertvalue chains to extract only the values we need
1033           // to return and insert them into our new result.
1034           // This does generate messy code, but we'll let it to instcombine to
1035           // clean that up.
1036           Value *OldRet = RI->getOperand(0);
1037           // Start out building up our return value from undef
1038           RetVal = UndefValue::get(NRetTy);
1039           for (unsigned RetI = 0; RetI != RetCount; ++RetI)
1040             if (NewRetIdxs[RetI] != -1) {
1041               ExtractValueInst *EV =
1042                   ExtractValueInst::Create(OldRet, RetI, "oldret", RI);
1043               if (RetTypes.size() > 1) {
1044                 // We're still returning a struct, so reinsert the value into
1045                 // our new return value at the new index
1046 
1047                 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[RetI],
1048                                                  "newret", RI);
1049               } else {
1050                 // We are now only returning a simple value, so just return the
1051                 // extracted value.
1052                 RetVal = EV;
1053               }
1054             }
1055         }
1056         // Replace the return instruction with one returning the new return
1057         // value (possibly 0 if we became void).
1058         ReturnInst::Create(F->getContext(), RetVal, RI);
1059         BB.getInstList().erase(RI);
1060       }
1061 
1062   // Clone metadatas from the old function, including debug info descriptor.
1063   SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
1064   F->getAllMetadata(MDs);
1065   for (auto MD : MDs)
1066     NF->addMetadata(MD.first, *MD.second);
1067 
1068   // Now that the old function is dead, delete it.
1069   F->eraseFromParent();
1070 
1071   return true;
1072 }
1073 
1074 PreservedAnalyses DeadArgumentEliminationPass::run(Module &M,
1075                                                    ModuleAnalysisManager &) {
1076   bool Changed = false;
1077 
1078   // First pass: Do a simple check to see if any functions can have their "..."
1079   // removed.  We can do this if they never call va_start.  This loop cannot be
1080   // fused with the next loop, because deleting a function invalidates
1081   // information computed while surveying other functions.
1082   LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Deleting dead varargs\n");
1083   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
1084     Function &F = *I++;
1085     if (F.getFunctionType()->isVarArg())
1086       Changed |= DeleteDeadVarargs(F);
1087   }
1088 
1089   // Second phase:loop through the module, determining which arguments are live.
1090   // We assume all arguments are dead unless proven otherwise (allowing us to
1091   // determine that dead arguments passed into recursive functions are dead).
1092   //
1093   LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Determining liveness\n");
1094   for (auto &F : M)
1095     SurveyFunction(F);
1096 
1097   // Now, remove all dead arguments and return values from each function in
1098   // turn.
1099   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
1100     // Increment now, because the function will probably get removed (ie.
1101     // replaced by a new one).
1102     Function *F = &*I++;
1103     Changed |= RemoveDeadStuffFromFunction(F);
1104   }
1105 
1106   // Finally, look for any unused parameters in functions with non-local
1107   // linkage and replace the passed in parameters with undef.
1108   for (auto &F : M)
1109     Changed |= RemoveDeadArgumentsFromCallers(F);
1110 
1111   if (!Changed)
1112     return PreservedAnalyses::all();
1113   return PreservedAnalyses::none();
1114 }
1115