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