DeadArgumentElimination.cpp revision 280031
1193323Sed//===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This pass deletes dead arguments from internal functions.  Dead argument
11193323Sed// elimination removes arguments which are directly dead, as well as arguments
12193323Sed// only passed into function calls as dead arguments of other functions.  This
13193323Sed// pass also deletes dead return values in a similar way.
14193323Sed//
15193323Sed// This pass is often useful as a cleanup pass to run after aggressive
16193323Sed// interprocedural passes, which add possibly-dead arguments or return values.
17193323Sed//
18193323Sed//===----------------------------------------------------------------------===//
19193323Sed
20193323Sed#include "llvm/Transforms/IPO.h"
21249423Sdim#include "llvm/ADT/DenseMap.h"
22249423Sdim#include "llvm/ADT/SmallVector.h"
23249423Sdim#include "llvm/ADT/Statistic.h"
24249423Sdim#include "llvm/ADT/StringExtras.h"
25276479Sdim#include "llvm/IR/CallSite.h"
26249423Sdim#include "llvm/IR/CallingConv.h"
27249423Sdim#include "llvm/IR/Constant.h"
28276479Sdim#include "llvm/IR/DIBuilder.h"
29276479Sdim#include "llvm/IR/DebugInfo.h"
30249423Sdim#include "llvm/IR/DerivedTypes.h"
31249423Sdim#include "llvm/IR/Instructions.h"
32249423Sdim#include "llvm/IR/IntrinsicInst.h"
33249423Sdim#include "llvm/IR/LLVMContext.h"
34249423Sdim#include "llvm/IR/Module.h"
35193323Sed#include "llvm/Pass.h"
36193323Sed#include "llvm/Support/Debug.h"
37198090Srdivacky#include "llvm/Support/raw_ostream.h"
38193323Sed#include <map>
39193323Sed#include <set>
40276479Sdim#include <tuple>
41193323Sedusing namespace llvm;
42193323Sed
43276479Sdim#define DEBUG_TYPE "deadargelim"
44276479Sdim
45193323SedSTATISTIC(NumArgumentsEliminated, "Number of unread args removed");
46193323SedSTATISTIC(NumRetValsEliminated  , "Number of unused return values removed");
47218893SdimSTATISTIC(NumArgumentsReplacedWithUndef,
48218893Sdim          "Number of unread args replaced with undef");
49193323Sednamespace {
50193323Sed  /// DAE - The dead argument elimination pass.
51193323Sed  ///
52198892Srdivacky  class DAE : public ModulePass {
53193323Sed  public:
54193323Sed
55193323Sed    /// Struct that represents (part of) either a return value or a function
56193323Sed    /// argument.  Used so that arguments and return values can be used
57221345Sdim    /// interchangeably.
58193323Sed    struct RetOrArg {
59206083Srdivacky      RetOrArg(const Function *F, unsigned Idx, bool IsArg) : F(F), Idx(Idx),
60193323Sed               IsArg(IsArg) {}
61193323Sed      const Function *F;
62193323Sed      unsigned Idx;
63193323Sed      bool IsArg;
64193323Sed
65193323Sed      /// Make RetOrArg comparable, so we can put it into a map.
66193323Sed      bool operator<(const RetOrArg &O) const {
67276479Sdim        return std::tie(F, Idx, IsArg) < std::tie(O.F, O.Idx, O.IsArg);
68193323Sed      }
69193323Sed
70193323Sed      /// Make RetOrArg comparable, so we can easily iterate the multimap.
71193323Sed      bool operator==(const RetOrArg &O) const {
72193323Sed        return F == O.F && Idx == O.Idx && IsArg == O.IsArg;
73193323Sed      }
74193323Sed
75193323Sed      std::string getDescription() const {
76206083Srdivacky        return std::string((IsArg ? "Argument #" : "Return value #"))
77234353Sdim               + utostr(Idx) + " of function " + F->getName().str();
78193323Sed      }
79193323Sed    };
80193323Sed
81193323Sed    /// Liveness enum - During our initial pass over the program, we determine
82193323Sed    /// that things are either alive or maybe alive. We don't mark anything
83193323Sed    /// explicitly dead (even if we know they are), since anything not alive
84193323Sed    /// with no registered uses (in Uses) will never be marked alive and will
85193323Sed    /// thus become dead in the end.
86193323Sed    enum Liveness { Live, MaybeLive };
87193323Sed
88193323Sed    /// Convenience wrapper
89193323Sed    RetOrArg CreateRet(const Function *F, unsigned Idx) {
90193323Sed      return RetOrArg(F, Idx, false);
91193323Sed    }
92193323Sed    /// Convenience wrapper
93193323Sed    RetOrArg CreateArg(const Function *F, unsigned Idx) {
94193323Sed      return RetOrArg(F, Idx, true);
95193323Sed    }
96193323Sed
97193323Sed    typedef std::multimap<RetOrArg, RetOrArg> UseMap;
98193323Sed    /// This maps a return value or argument to any MaybeLive return values or
99193323Sed    /// arguments it uses. This allows the MaybeLive values to be marked live
100193323Sed    /// when any of its users is marked live.
101193323Sed    /// For example (indices are left out for clarity):
102193323Sed    ///  - Uses[ret F] = ret G
103193323Sed    ///    This means that F calls G, and F returns the value returned by G.
104193323Sed    ///  - Uses[arg F] = ret G
105193323Sed    ///    This means that some function calls G and passes its result as an
106193323Sed    ///    argument to F.
107193323Sed    ///  - Uses[ret F] = arg F
108193323Sed    ///    This means that F returns one of its own arguments.
109193323Sed    ///  - Uses[arg F] = arg G
110193323Sed    ///    This means that G calls F and passes one of its own (G's) arguments
111193323Sed    ///    directly to F.
112193323Sed    UseMap Uses;
113193323Sed
114193323Sed    typedef std::set<RetOrArg> LiveSet;
115193323Sed    typedef std::set<const Function*> LiveFuncSet;
116193323Sed
117193323Sed    /// This set contains all values that have been determined to be live.
118193323Sed    LiveSet LiveValues;
119193323Sed    /// This set contains all values that are cannot be changed in any way.
120193323Sed    LiveFuncSet LiveFunctions;
121193323Sed
122193323Sed    typedef SmallVector<RetOrArg, 5> UseVector;
123193323Sed
124243830Sdim    // Map each LLVM function to corresponding metadata with debug info. If
125243830Sdim    // the function is replaced with another one, we should patch the pointer
126243830Sdim    // to LLVM function in metadata.
127243830Sdim    // As the code generation for module is finished (and DIBuilder is
128243830Sdim    // finalized) we assume that subprogram descriptors won't be changed, and
129243830Sdim    // they are stored in map for short duration anyway.
130276479Sdim    DenseMap<const Function *, DISubprogram> FunctionDIs;
131243830Sdim
132210299Sed  protected:
133210299Sed    // DAH uses this to specify a different ID.
134212904Sdim    explicit DAE(char &ID) : ModulePass(ID) {}
135210299Sed
136193323Sed  public:
137193323Sed    static char ID; // Pass identification, replacement for typeid
138218893Sdim    DAE() : ModulePass(ID) {
139218893Sdim      initializeDAEPass(*PassRegistry::getPassRegistry());
140218893Sdim    }
141210299Sed
142276479Sdim    bool runOnModule(Module &M) override;
143193323Sed
144193323Sed    virtual bool ShouldHackArguments() const { return false; }
145193323Sed
146193323Sed  private:
147193323Sed    Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
148276479Sdim    Liveness SurveyUse(const Use *U, UseVector &MaybeLiveUses,
149193323Sed                       unsigned RetValNum = 0);
150206083Srdivacky    Liveness SurveyUses(const Value *V, UseVector &MaybeLiveUses);
151193323Sed
152206083Srdivacky    void SurveyFunction(const Function &F);
153193323Sed    void MarkValue(const RetOrArg &RA, Liveness L,
154193323Sed                   const UseVector &MaybeLiveUses);
155193323Sed    void MarkLive(const RetOrArg &RA);
156193323Sed    void MarkLive(const Function &F);
157193323Sed    void PropagateLiveness(const RetOrArg &RA);
158193323Sed    bool RemoveDeadStuffFromFunction(Function *F);
159193323Sed    bool DeleteDeadVarargs(Function &Fn);
160218893Sdim    bool RemoveDeadArgumentsFromCallers(Function &Fn);
161193323Sed  };
162193323Sed}
163193323Sed
164193323Sed
165193323Sedchar DAE::ID = 0;
166218893SdimINITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false)
167193323Sed
168193323Sednamespace {
169193323Sed  /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
170193323Sed  /// deletes arguments to functions which are external.  This is only for use
171193323Sed  /// by bugpoint.
172193323Sed  struct DAH : public DAE {
173193323Sed    static char ID;
174212904Sdim    DAH() : DAE(ID) {}
175210299Sed
176276479Sdim    bool ShouldHackArguments() const override { return true; }
177193323Sed  };
178193323Sed}
179193323Sed
180193323Sedchar DAH::ID = 0;
181212904SdimINITIALIZE_PASS(DAH, "deadarghaX0r",
182212904Sdim                "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)",
183218893Sdim                false, false)
184193323Sed
185193323Sed/// createDeadArgEliminationPass - This pass removes arguments from functions
186193323Sed/// which are not used by the body of the function.
187193323Sed///
188193323SedModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
189193323SedModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
190193323Sed
191193323Sed/// DeleteDeadVarargs - If this is an function that takes a ... list, and if
192193323Sed/// llvm.vastart is never called, the varargs list is dead for the function.
193193323Sedbool DAE::DeleteDeadVarargs(Function &Fn) {
194193323Sed  assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
195193323Sed  if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false;
196193323Sed
197193323Sed  // Ensure that the function is only directly called.
198194178Sed  if (Fn.hasAddressTaken())
199194178Sed    return false;
200193323Sed
201193323Sed  // Okay, we know we can transform this function if safe.  Scan its body
202280031Sdim  // looking for calls marked musttail or calls to llvm.vastart.
203193323Sed  for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
204193323Sed    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
205280031Sdim      CallInst *CI = dyn_cast<CallInst>(I);
206280031Sdim      if (!CI)
207280031Sdim        continue;
208280031Sdim      if (CI->isMustTailCall())
209280031Sdim        return false;
210280031Sdim      if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
211193323Sed        if (II->getIntrinsicID() == Intrinsic::vastart)
212193323Sed          return false;
213193323Sed      }
214193323Sed    }
215193323Sed  }
216193323Sed
217193323Sed  // If we get here, there are no calls to llvm.vastart in the function body,
218193323Sed  // remove the "..." and adjust all the calls.
219193323Sed
220193323Sed  // Start by computing a new prototype for the function, which is the same as
221193323Sed  // the old function, but doesn't have isVarArg set.
222226633Sdim  FunctionType *FTy = Fn.getFunctionType();
223206083Srdivacky
224224145Sdim  std::vector<Type*> Params(FTy->param_begin(), FTy->param_end());
225198090Srdivacky  FunctionType *NFTy = FunctionType::get(FTy->getReturnType(),
226198090Srdivacky                                                Params, false);
227193323Sed  unsigned NumArgs = Params.size();
228193323Sed
229193323Sed  // Create the new function body and insert it into the module...
230193323Sed  Function *NF = Function::Create(NFTy, Fn.getLinkage());
231193323Sed  NF->copyAttributesFrom(&Fn);
232193323Sed  Fn.getParent()->getFunctionList().insert(&Fn, NF);
233193323Sed  NF->takeName(&Fn);
234193323Sed
235193323Sed  // Loop over all of the callers of the function, transforming the call sites
236193323Sed  // to pass in a smaller number of arguments into the new function.
237193323Sed  //
238193323Sed  std::vector<Value*> Args;
239276479Sdim  for (Value::user_iterator I = Fn.user_begin(), E = Fn.user_end(); I != E; ) {
240261991Sdim    CallSite CS(*I++);
241261991Sdim    if (!CS)
242261991Sdim      continue;
243193323Sed    Instruction *Call = CS.getInstruction();
244193323Sed
245193323Sed    // Pass all the same arguments.
246212904Sdim    Args.assign(CS.arg_begin(), CS.arg_begin() + NumArgs);
247193323Sed
248193323Sed    // Drop any attributes that were on the vararg arguments.
249249423Sdim    AttributeSet PAL = CS.getAttributes();
250249423Sdim    if (!PAL.isEmpty() && PAL.getSlotIndex(PAL.getNumSlots() - 1) > NumArgs) {
251249423Sdim      SmallVector<AttributeSet, 8> AttributesVec;
252249423Sdim      for (unsigned i = 0; PAL.getSlotIndex(i) <= NumArgs; ++i)
253249423Sdim        AttributesVec.push_back(PAL.getSlotAttributes(i));
254249423Sdim      if (PAL.hasAttributes(AttributeSet::FunctionIndex))
255249423Sdim        AttributesVec.push_back(AttributeSet::get(Fn.getContext(),
256249423Sdim                                                  PAL.getFnAttributes()));
257249423Sdim      PAL = AttributeSet::get(Fn.getContext(), AttributesVec);
258193323Sed    }
259193323Sed
260193323Sed    Instruction *New;
261193323Sed    if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
262193323Sed      New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
263224145Sdim                               Args, "", Call);
264193323Sed      cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
265193323Sed      cast<InvokeInst>(New)->setAttributes(PAL);
266193323Sed    } else {
267224145Sdim      New = CallInst::Create(NF, Args, "", Call);
268193323Sed      cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
269193323Sed      cast<CallInst>(New)->setAttributes(PAL);
270193323Sed      if (cast<CallInst>(Call)->isTailCall())
271193323Sed        cast<CallInst>(New)->setTailCall();
272193323Sed    }
273212904Sdim    New->setDebugLoc(Call->getDebugLoc());
274207618Srdivacky
275193323Sed    Args.clear();
276193323Sed
277193323Sed    if (!Call->use_empty())
278193323Sed      Call->replaceAllUsesWith(New);
279193323Sed
280193323Sed    New->takeName(Call);
281193323Sed
282193323Sed    // Finally, remove the old call from the program, reducing the use-count of
283193323Sed    // F.
284193323Sed    Call->eraseFromParent();
285193323Sed  }
286193323Sed
287193323Sed  // Since we have now created the new function, splice the body of the old
288193323Sed  // function right into the new function, leaving the old rotting hulk of the
289193323Sed  // function empty.
290193323Sed  NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
291193323Sed
292221345Sdim  // Loop over the argument list, transferring uses of the old arguments over to
293221345Sdim  // the new arguments, also transferring over the names as well.  While we're at
294193323Sed  // it, remove the dead arguments from the DeadArguments list.
295193323Sed  //
296193323Sed  for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
297193323Sed       I2 = NF->arg_begin(); I != E; ++I, ++I2) {
298193323Sed    // Move the name and users over to the new version.
299193323Sed    I->replaceAllUsesWith(I2);
300193323Sed    I2->takeName(I);
301193323Sed  }
302193323Sed
303243830Sdim  // Patch the pointer to LLVM function in debug info descriptor.
304276479Sdim  auto DI = FunctionDIs.find(&Fn);
305280031Sdim  if (DI != FunctionDIs.end()) {
306280031Sdim    DISubprogram SP = DI->second;
307280031Sdim    SP.replaceFunction(NF);
308280031Sdim    // Ensure the map is updated so it can be reused on non-varargs argument
309280031Sdim    // eliminations of the same function.
310280031Sdim    FunctionDIs.erase(DI);
311280031Sdim    FunctionDIs[NF] = SP;
312280031Sdim  }
313243830Sdim
314261991Sdim  // Fix up any BlockAddresses that refer to the function.
315261991Sdim  Fn.replaceAllUsesWith(ConstantExpr::getBitCast(NF, Fn.getType()));
316261991Sdim  // Delete the bitcast that we just created, so that NF does not
317261991Sdim  // appear to be address-taken.
318261991Sdim  NF->removeDeadConstantUsers();
319193323Sed  // Finally, nuke the old function.
320193323Sed  Fn.eraseFromParent();
321193323Sed  return true;
322193323Sed}
323193323Sed
324218893Sdim/// RemoveDeadArgumentsFromCallers - Checks if the given function has any
325218893Sdim/// arguments that are unused, and changes the caller parameters to be undefined
326218893Sdim/// instead.
327218893Sdimbool DAE::RemoveDeadArgumentsFromCallers(Function &Fn)
328218893Sdim{
329221345Sdim  if (Fn.isDeclaration() || Fn.mayBeOverridden())
330218893Sdim    return false;
331218893Sdim
332261991Sdim  // Functions with local linkage should already have been handled, except the
333261991Sdim  // fragile (variadic) ones which we can improve here.
334261991Sdim  if (Fn.hasLocalLinkage() && !Fn.getFunctionType()->isVarArg())
335218893Sdim    return false;
336218893Sdim
337261991Sdim  // If a function seen at compile time is not necessarily the one linked to
338261991Sdim  // the binary being built, it is illegal to change the actual arguments
339261991Sdim  // passed to it. These functions can be captured by isWeakForLinker().
340261991Sdim  // *NOTE* that mayBeOverridden() is insufficient for this purpose as it
341261991Sdim  // doesn't include linkage types like AvailableExternallyLinkage and
342261991Sdim  // LinkOnceODRLinkage. Take link_odr* as an example, it indicates a set of
343261991Sdim  // *EQUIVALENT* globals that can be merged at link-time. However, the
344261991Sdim  // semantic of *EQUIVALENT*-functions includes parameters. Changing
345261991Sdim  // parameters breaks this assumption.
346261991Sdim  //
347261991Sdim  if (Fn.isWeakForLinker())
348261991Sdim    return false;
349261991Sdim
350218893Sdim  if (Fn.use_empty())
351218893Sdim    return false;
352218893Sdim
353249423Sdim  SmallVector<unsigned, 8> UnusedArgs;
354218893Sdim  for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
355218893Sdim       I != E; ++I) {
356218893Sdim    Argument *Arg = I;
357218893Sdim
358276479Sdim    if (Arg->use_empty() && !Arg->hasByValOrInAllocaAttr())
359218893Sdim      UnusedArgs.push_back(Arg->getArgNo());
360218893Sdim  }
361218893Sdim
362218893Sdim  if (UnusedArgs.empty())
363218893Sdim    return false;
364218893Sdim
365218893Sdim  bool Changed = false;
366218893Sdim
367276479Sdim  for (Use &U : Fn.uses()) {
368276479Sdim    CallSite CS(U.getUser());
369276479Sdim    if (!CS || !CS.isCallee(&U))
370218893Sdim      continue;
371218893Sdim
372218893Sdim    // Now go through all unused args and replace them with "undef".
373218893Sdim    for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) {
374218893Sdim      unsigned ArgNo = UnusedArgs[I];
375218893Sdim
376218893Sdim      Value *Arg = CS.getArgument(ArgNo);
377218893Sdim      CS.setArgument(ArgNo, UndefValue::get(Arg->getType()));
378218893Sdim      ++NumArgumentsReplacedWithUndef;
379218893Sdim      Changed = true;
380218893Sdim    }
381218893Sdim  }
382218893Sdim
383218893Sdim  return Changed;
384218893Sdim}
385218893Sdim
386193323Sed/// Convenience function that returns the number of return values. It returns 0
387193323Sed/// for void functions and 1 for functions not returning a struct. It returns
388193323Sed/// the number of struct elements for functions returning a struct.
389193323Sedstatic unsigned NumRetVals(const Function *F) {
390206083Srdivacky  if (F->getReturnType()->isVoidTy())
391193323Sed    return 0;
392226633Sdim  else if (StructType *STy = dyn_cast<StructType>(F->getReturnType()))
393193323Sed    return STy->getNumElements();
394193323Sed  else
395193323Sed    return 1;
396193323Sed}
397193323Sed
398193323Sed/// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
399193323Sed/// live, it adds Use to the MaybeLiveUses argument. Returns the determined
400193323Sed/// liveness of Use.
401193323SedDAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
402193323Sed  // We're live if our use or its Function is already marked as live.
403193323Sed  if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
404193323Sed    return Live;
405193323Sed
406193323Sed  // We're maybe live otherwise, but remember that we must become live if
407193323Sed  // Use becomes live.
408193323Sed  MaybeLiveUses.push_back(Use);
409193323Sed  return MaybeLive;
410193323Sed}
411193323Sed
412193323Sed
413193323Sed/// SurveyUse - This looks at a single use of an argument or return value
414193323Sed/// and determines if it should be alive or not. Adds this use to MaybeLiveUses
415206083Srdivacky/// if it causes the used value to become MaybeLive.
416193323Sed///
417193323Sed/// RetValNum is the return value number to use when this use is used in a
418193323Sed/// return instruction. This is used in the recursion, you should always leave
419193323Sed/// it at 0.
420276479SdimDAE::Liveness DAE::SurveyUse(const Use *U,
421206083Srdivacky                             UseVector &MaybeLiveUses, unsigned RetValNum) {
422276479Sdim    const User *V = U->getUser();
423206083Srdivacky    if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
424193323Sed      // The value is returned from a function. It's only live when the
425193323Sed      // function's return value is live. We use RetValNum here, for the case
426193323Sed      // that U is really a use of an insertvalue instruction that uses the
427221345Sdim      // original Use.
428193323Sed      RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
429193323Sed      // We might be live, depending on the liveness of Use.
430193323Sed      return MarkIfNotLive(Use, MaybeLiveUses);
431193323Sed    }
432206083Srdivacky    if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
433276479Sdim      if (U->getOperandNo() != InsertValueInst::getAggregateOperandIndex()
434193323Sed          && IV->hasIndices())
435193323Sed        // The use we are examining is inserted into an aggregate. Our liveness
436193323Sed        // depends on all uses of that aggregate, but if it is used as a return
437193323Sed        // value, only index at which we were inserted counts.
438193323Sed        RetValNum = *IV->idx_begin();
439193323Sed
440193323Sed      // Note that if we are used as the aggregate operand to the insertvalue,
441193323Sed      // we don't change RetValNum, but do survey all our uses.
442193323Sed
443193323Sed      Liveness Result = MaybeLive;
444276479Sdim      for (const Use &UU : IV->uses()) {
445276479Sdim        Result = SurveyUse(&UU, MaybeLiveUses, RetValNum);
446193323Sed        if (Result == Live)
447193323Sed          break;
448193323Sed      }
449193323Sed      return Result;
450193323Sed    }
451206083Srdivacky
452206083Srdivacky    if (ImmutableCallSite CS = V) {
453206083Srdivacky      const Function *F = CS.getCalledFunction();
454193323Sed      if (F) {
455193323Sed        // Used in a direct call.
456206083Srdivacky
457193323Sed        // Find the argument number. We know for sure that this use is an
458193323Sed        // argument, since if it was the function argument this would be an
459193323Sed        // indirect call and the we know can't be looking at a value of the
460193323Sed        // label type (for the invoke instruction).
461206083Srdivacky        unsigned ArgNo = CS.getArgumentNo(U);
462193323Sed
463193323Sed        if (ArgNo >= F->getFunctionType()->getNumParams())
464193323Sed          // The value is passed in through a vararg! Must be live.
465193323Sed          return Live;
466193323Sed
467206083Srdivacky        assert(CS.getArgument(ArgNo)
468276479Sdim               == CS->getOperand(U->getOperandNo())
469193323Sed               && "Argument is not where we expected it");
470193323Sed
471193323Sed        // Value passed to a normal call. It's only live when the corresponding
472193323Sed        // argument to the called function turns out live.
473193323Sed        RetOrArg Use = CreateArg(F, ArgNo);
474193323Sed        return MarkIfNotLive(Use, MaybeLiveUses);
475193323Sed      }
476193323Sed    }
477193323Sed    // Used in any other way? Value must be live.
478193323Sed    return Live;
479193323Sed}
480193323Sed
481193323Sed/// SurveyUses - This looks at all the uses of the given value
482193323Sed/// Returns the Liveness deduced from the uses of this value.
483193323Sed///
484193323Sed/// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
485193323Sed/// the result is Live, MaybeLiveUses might be modified but its content should
486193323Sed/// be ignored (since it might not be complete).
487206083SrdivackyDAE::Liveness DAE::SurveyUses(const Value *V, UseVector &MaybeLiveUses) {
488193323Sed  // Assume it's dead (which will only hold if there are no uses at all..).
489193323Sed  Liveness Result = MaybeLive;
490193323Sed  // Check each use.
491276479Sdim  for (const Use &U : V->uses()) {
492276479Sdim    Result = SurveyUse(&U, MaybeLiveUses);
493193323Sed    if (Result == Live)
494193323Sed      break;
495193323Sed  }
496193323Sed  return Result;
497193323Sed}
498193323Sed
499193323Sed// SurveyFunction - This performs the initial survey of the specified function,
500193323Sed// checking out whether or not it uses any of its incoming arguments or whether
501193323Sed// any callers use the return value.  This fills in the LiveValues set and Uses
502193323Sed// map.
503193323Sed//
504193323Sed// We consider arguments of non-internal functions to be intrinsically alive as
505193323Sed// well as arguments to functions which have their "address taken".
506193323Sed//
507206083Srdivackyvoid DAE::SurveyFunction(const Function &F) {
508276479Sdim  // Functions with inalloca parameters are expecting args in a particular
509276479Sdim  // register and memory layout.
510276479Sdim  if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca)) {
511276479Sdim    MarkLive(F);
512276479Sdim    return;
513276479Sdim  }
514276479Sdim
515193323Sed  unsigned RetCount = NumRetVals(&F);
516193323Sed  // Assume all return values are dead
517193323Sed  typedef SmallVector<Liveness, 5> RetVals;
518193323Sed  RetVals RetValLiveness(RetCount, MaybeLive);
519193323Sed
520193323Sed  typedef SmallVector<UseVector, 5> RetUses;
521193323Sed  // These vectors map each return value to the uses that make it MaybeLive, so
522193323Sed  // we can add those to the Uses map if the return value really turns out to be
523193323Sed  // MaybeLive. Initialized to a list of RetCount empty lists.
524193323Sed  RetUses MaybeLiveRetUses(RetCount);
525193323Sed
526206083Srdivacky  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
527206083Srdivacky    if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
528193323Sed      if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
529193323Sed          != F.getFunctionType()->getReturnType()) {
530193323Sed        // We don't support old style multiple return values.
531193323Sed        MarkLive(F);
532193323Sed        return;
533193323Sed      }
534193323Sed
535193323Sed  if (!F.hasLocalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
536193323Sed    MarkLive(F);
537193323Sed    return;
538193323Sed  }
539193323Sed
540202375Srdivacky  DEBUG(dbgs() << "DAE - Inspecting callers for fn: " << F.getName() << "\n");
541193323Sed  // Keep track of the number of live retvals, so we can skip checks once all
542193323Sed  // of them turn out to be live.
543193323Sed  unsigned NumLiveRetVals = 0;
544226633Sdim  Type *STy = dyn_cast<StructType>(F.getReturnType());
545193323Sed  // Loop all uses of the function.
546276479Sdim  for (const Use &U : F.uses()) {
547193323Sed    // If the function is PASSED IN as an argument, its address has been
548193323Sed    // taken.
549276479Sdim    ImmutableCallSite CS(U.getUser());
550276479Sdim    if (!CS || !CS.isCallee(&U)) {
551193323Sed      MarkLive(F);
552193323Sed      return;
553193323Sed    }
554193323Sed
555193323Sed    // If this use is anything other than a call site, the function is alive.
556206083Srdivacky    const Instruction *TheCall = CS.getInstruction();
557193323Sed    if (!TheCall) {   // Not a direct call site?
558193323Sed      MarkLive(F);
559193323Sed      return;
560193323Sed    }
561193323Sed
562193323Sed    // If we end up here, we are looking at a direct call to our function.
563193323Sed
564193323Sed    // Now, check how our return value(s) is/are used in this caller. Don't
565193323Sed    // bother checking return values if all of them are live already.
566193323Sed    if (NumLiveRetVals != RetCount) {
567193323Sed      if (STy) {
568193323Sed        // Check all uses of the return value.
569276479Sdim        for (const User *U : TheCall->users()) {
570276479Sdim          const ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(U);
571193323Sed          if (Ext && Ext->hasIndices()) {
572193323Sed            // This use uses a part of our return value, survey the uses of
573193323Sed            // that part and store the results for this index only.
574193323Sed            unsigned Idx = *Ext->idx_begin();
575193323Sed            if (RetValLiveness[Idx] != Live) {
576193323Sed              RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
577193323Sed              if (RetValLiveness[Idx] == Live)
578193323Sed                NumLiveRetVals++;
579193323Sed            }
580193323Sed          } else {
581193323Sed            // Used by something else than extractvalue. Mark all return
582193323Sed            // values as live.
583193323Sed            for (unsigned i = 0; i != RetCount; ++i )
584193323Sed              RetValLiveness[i] = Live;
585193323Sed            NumLiveRetVals = RetCount;
586193323Sed            break;
587193323Sed          }
588193323Sed        }
589193323Sed      } else {
590193323Sed        // Single return value
591193323Sed        RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]);
592193323Sed        if (RetValLiveness[0] == Live)
593193323Sed          NumLiveRetVals = RetCount;
594193323Sed      }
595193323Sed    }
596193323Sed  }
597193323Sed
598193323Sed  // Now we've inspected all callers, record the liveness of our return values.
599193323Sed  for (unsigned i = 0; i != RetCount; ++i)
600193323Sed    MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
601193323Sed
602202375Srdivacky  DEBUG(dbgs() << "DAE - Inspecting args for fn: " << F.getName() << "\n");
603193323Sed
604193323Sed  // Now, check all of our arguments.
605193323Sed  unsigned i = 0;
606193323Sed  UseVector MaybeLiveArgUses;
607206083Srdivacky  for (Function::const_arg_iterator AI = F.arg_begin(),
608193323Sed       E = F.arg_end(); AI != E; ++AI, ++i) {
609261991Sdim    Liveness Result;
610261991Sdim    if (F.getFunctionType()->isVarArg()) {
611261991Sdim      // Variadic functions will already have a va_arg function expanded inside
612261991Sdim      // them, making them potentially very sensitive to ABI changes resulting
613261991Sdim      // from removing arguments entirely, so don't. For example AArch64 handles
614261991Sdim      // register and stack HFAs very differently, and this is reflected in the
615261991Sdim      // IR which has already been generated.
616261991Sdim      Result = Live;
617261991Sdim    } else {
618261991Sdim      // See what the effect of this use is (recording any uses that cause
619261991Sdim      // MaybeLive in MaybeLiveArgUses).
620261991Sdim      Result = SurveyUses(AI, MaybeLiveArgUses);
621261991Sdim    }
622261991Sdim
623193323Sed    // Mark the result.
624193323Sed    MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
625193323Sed    // Clear the vector again for the next iteration.
626193323Sed    MaybeLiveArgUses.clear();
627193323Sed  }
628193323Sed}
629193323Sed
630193323Sed/// MarkValue - This function marks the liveness of RA depending on L. If L is
631193323Sed/// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
632193323Sed/// such that RA will be marked live if any use in MaybeLiveUses gets marked
633193323Sed/// live later on.
634193323Sedvoid DAE::MarkValue(const RetOrArg &RA, Liveness L,
635193323Sed                    const UseVector &MaybeLiveUses) {
636193323Sed  switch (L) {
637193323Sed    case Live: MarkLive(RA); break;
638193323Sed    case MaybeLive:
639193323Sed    {
640193323Sed      // Note any uses of this value, so this return value can be
641193323Sed      // marked live whenever one of the uses becomes live.
642193323Sed      for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
643193323Sed           UE = MaybeLiveUses.end(); UI != UE; ++UI)
644193323Sed        Uses.insert(std::make_pair(*UI, RA));
645193323Sed      break;
646193323Sed    }
647193323Sed  }
648193323Sed}
649193323Sed
650193323Sed/// MarkLive - Mark the given Function as alive, meaning that it cannot be
651193323Sed/// changed in any way. Additionally,
652193323Sed/// mark any values that are used as this function's parameters or by its return
653193323Sed/// values (according to Uses) live as well.
654193323Sedvoid DAE::MarkLive(const Function &F) {
655202375Srdivacky  DEBUG(dbgs() << "DAE - Intrinsically live fn: " << F.getName() << "\n");
656208599Srdivacky  // Mark the function as live.
657208599Srdivacky  LiveFunctions.insert(&F);
658208599Srdivacky  // Mark all arguments as live.
659208599Srdivacky  for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
660208599Srdivacky    PropagateLiveness(CreateArg(&F, i));
661208599Srdivacky  // Mark all return values as live.
662208599Srdivacky  for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
663208599Srdivacky    PropagateLiveness(CreateRet(&F, i));
664193323Sed}
665193323Sed
666193323Sed/// MarkLive - Mark the given return value or argument as live. Additionally,
667193323Sed/// mark any values that are used by this value (according to Uses) live as
668193323Sed/// well.
669193323Sedvoid DAE::MarkLive(const RetOrArg &RA) {
670193323Sed  if (LiveFunctions.count(RA.F))
671193323Sed    return; // Function was already marked Live.
672193323Sed
673193323Sed  if (!LiveValues.insert(RA).second)
674193323Sed    return; // We were already marked Live.
675193323Sed
676202375Srdivacky  DEBUG(dbgs() << "DAE - Marking " << RA.getDescription() << " live\n");
677193323Sed  PropagateLiveness(RA);
678193323Sed}
679193323Sed
680193323Sed/// PropagateLiveness - Given that RA is a live value, propagate it's liveness
681193323Sed/// to any other values it uses (according to Uses).
682193323Sedvoid DAE::PropagateLiveness(const RetOrArg &RA) {
683193323Sed  // We don't use upper_bound (or equal_range) here, because our recursive call
684193323Sed  // to ourselves is likely to cause the upper_bound (which is the first value
685193323Sed  // not belonging to RA) to become erased and the iterator invalidated.
686193323Sed  UseMap::iterator Begin = Uses.lower_bound(RA);
687193323Sed  UseMap::iterator E = Uses.end();
688193323Sed  UseMap::iterator I;
689193323Sed  for (I = Begin; I != E && I->first == RA; ++I)
690193323Sed    MarkLive(I->second);
691193323Sed
692193323Sed  // Erase RA from the Uses map (from the lower bound to wherever we ended up
693193323Sed  // after the loop).
694193323Sed  Uses.erase(Begin, I);
695193323Sed}
696193323Sed
697193323Sed// RemoveDeadStuffFromFunction - Remove any arguments and return values from F
698193323Sed// that are not in LiveValues. Transform the function and all of the callees of
699193323Sed// the function to not have these arguments and return values.
700193323Sed//
701193323Sedbool DAE::RemoveDeadStuffFromFunction(Function *F) {
702193323Sed  // Don't modify fully live functions
703193323Sed  if (LiveFunctions.count(F))
704193323Sed    return false;
705193323Sed
706193323Sed  // Start by computing a new prototype for the function, which is the same as
707193323Sed  // the old function, but has fewer arguments and a different return type.
708226633Sdim  FunctionType *FTy = F->getFunctionType();
709224145Sdim  std::vector<Type*> Params;
710193323Sed
711261991Sdim  // Keep track of if we have a live 'returned' argument
712261991Sdim  bool HasLiveReturnedArg = false;
713261991Sdim
714193323Sed  // Set up to build a new list of parameter attributes.
715249423Sdim  SmallVector<AttributeSet, 8> AttributesVec;
716249423Sdim  const AttributeSet &PAL = F->getAttributes();
717193323Sed
718261991Sdim  // Remember which arguments are still alive.
719261991Sdim  SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
720261991Sdim  // Construct the new parameter list from non-dead arguments. Also construct
721261991Sdim  // a new set of parameter attributes to correspond. Skip the first parameter
722261991Sdim  // attribute, since that belongs to the return value.
723261991Sdim  unsigned i = 0;
724261991Sdim  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
725261991Sdim       I != E; ++I, ++i) {
726261991Sdim    RetOrArg Arg = CreateArg(F, i);
727261991Sdim    if (LiveValues.erase(Arg)) {
728261991Sdim      Params.push_back(I->getType());
729261991Sdim      ArgAlive[i] = true;
730261991Sdim
731261991Sdim      // Get the original parameter attributes (skipping the first one, that is
732261991Sdim      // for the return value.
733261991Sdim      if (PAL.hasAttributes(i + 1)) {
734261991Sdim        AttrBuilder B(PAL, i + 1);
735261991Sdim        if (B.contains(Attribute::Returned))
736261991Sdim          HasLiveReturnedArg = true;
737261991Sdim        AttributesVec.
738261991Sdim          push_back(AttributeSet::get(F->getContext(), Params.size(), B));
739261991Sdim      }
740261991Sdim    } else {
741261991Sdim      ++NumArgumentsEliminated;
742261991Sdim      DEBUG(dbgs() << "DAE - Removing argument " << i << " (" << I->getName()
743261991Sdim            << ") from " << F->getName() << "\n");
744261991Sdim    }
745261991Sdim  }
746261991Sdim
747193323Sed  // Find out the new return value.
748224145Sdim  Type *RetTy = FTy->getReturnType();
749276479Sdim  Type *NRetTy = nullptr;
750193323Sed  unsigned RetCount = NumRetVals(F);
751206083Srdivacky
752193323Sed  // -1 means unused, other numbers are the new index
753193323Sed  SmallVector<int, 5> NewRetIdxs(RetCount, -1);
754224145Sdim  std::vector<Type*> RetTypes;
755261991Sdim
756261991Sdim  // If there is a function with a live 'returned' argument but a dead return
757261991Sdim  // value, then there are two possible actions:
758261991Sdim  // 1) Eliminate the return value and take off the 'returned' attribute on the
759261991Sdim  //    argument.
760261991Sdim  // 2) Retain the 'returned' attribute and treat the return value (but not the
761261991Sdim  //    entire function) as live so that it is not eliminated.
762261991Sdim  //
763261991Sdim  // It's not clear in the general case which option is more profitable because,
764261991Sdim  // even in the absence of explicit uses of the return value, code generation
765261991Sdim  // is free to use the 'returned' attribute to do things like eliding
766261991Sdim  // save/restores of registers across calls. Whether or not this happens is
767261991Sdim  // target and ABI-specific as well as depending on the amount of register
768261991Sdim  // pressure, so there's no good way for an IR-level pass to figure this out.
769261991Sdim  //
770261991Sdim  // Fortunately, the only places where 'returned' is currently generated by
771261991Sdim  // the FE are places where 'returned' is basically free and almost always a
772261991Sdim  // performance win, so the second option can just be used always for now.
773261991Sdim  //
774261991Sdim  // This should be revisited if 'returned' is ever applied more liberally.
775261991Sdim  if (RetTy->isVoidTy() || HasLiveReturnedArg) {
776206083Srdivacky    NRetTy = RetTy;
777193323Sed  } else {
778226633Sdim    StructType *STy = dyn_cast<StructType>(RetTy);
779193323Sed    if (STy)
780193323Sed      // Look at each of the original return values individually.
781193323Sed      for (unsigned i = 0; i != RetCount; ++i) {
782193323Sed        RetOrArg Ret = CreateRet(F, i);
783193323Sed        if (LiveValues.erase(Ret)) {
784193323Sed          RetTypes.push_back(STy->getElementType(i));
785193323Sed          NewRetIdxs[i] = RetTypes.size() - 1;
786193323Sed        } else {
787193323Sed          ++NumRetValsEliminated;
788202375Srdivacky          DEBUG(dbgs() << "DAE - Removing return value " << i << " from "
789198090Srdivacky                << F->getName() << "\n");
790193323Sed        }
791193323Sed      }
792193323Sed    else
793193323Sed      // We used to return a single value.
794193323Sed      if (LiveValues.erase(CreateRet(F, 0))) {
795193323Sed        RetTypes.push_back(RetTy);
796193323Sed        NewRetIdxs[0] = 0;
797193323Sed      } else {
798202375Srdivacky        DEBUG(dbgs() << "DAE - Removing return value from " << F->getName()
799198090Srdivacky              << "\n");
800193323Sed        ++NumRetValsEliminated;
801193323Sed      }
802193323Sed    if (RetTypes.size() > 1)
803193323Sed      // More than one return type? Return a struct with them. Also, if we used
804193323Sed      // to return a struct and didn't change the number of return values,
805193323Sed      // return a struct again. This prevents changing {something} into
806193323Sed      // something and {} into void.
807193323Sed      // Make the new struct packed if we used to return a packed struct
808193323Sed      // already.
809198090Srdivacky      NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked());
810193323Sed    else if (RetTypes.size() == 1)
811193323Sed      // One return type? Just a simple value then, but only if we didn't use to
812193323Sed      // return a struct with that simple value before.
813193323Sed      NRetTy = RetTypes.front();
814193323Sed    else if (RetTypes.size() == 0)
815193323Sed      // No return types? Make it void, but only if we didn't use to return {}.
816198090Srdivacky      NRetTy = Type::getVoidTy(F->getContext());
817193323Sed  }
818193323Sed
819193323Sed  assert(NRetTy && "No new return type found?");
820193323Sed
821249423Sdim  // The existing function return attributes.
822249423Sdim  AttributeSet RAttrs = PAL.getRetAttributes();
823249423Sdim
824193323Sed  // Remove any incompatible attributes, but only if we removed all return
825193323Sed  // values. Otherwise, ensure that we don't have any conflicting attributes
826193323Sed  // here. Currently, this should not be possible, but special handling might be
827193323Sed  // required when new return value attributes are added.
828206083Srdivacky  if (NRetTy->isVoidTy())
829243830Sdim    RAttrs =
830249423Sdim      AttributeSet::get(NRetTy->getContext(), AttributeSet::ReturnIndex,
831249423Sdim                        AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
832249423Sdim         removeAttributes(AttributeFuncs::
833249423Sdim                          typeIncompatible(NRetTy, AttributeSet::ReturnIndex),
834249423Sdim                          AttributeSet::ReturnIndex));
835193323Sed  else
836249423Sdim    assert(!AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
837249423Sdim             hasAttributes(AttributeFuncs::
838249423Sdim                           typeIncompatible(NRetTy, AttributeSet::ReturnIndex),
839249423Sdim                           AttributeSet::ReturnIndex) &&
840243830Sdim           "Return attributes no longer compatible?");
841193323Sed
842249423Sdim  if (RAttrs.hasAttributes(AttributeSet::ReturnIndex))
843249423Sdim    AttributesVec.push_back(AttributeSet::get(NRetTy->getContext(), RAttrs));
844193323Sed
845249423Sdim  if (PAL.hasAttributes(AttributeSet::FunctionIndex))
846249423Sdim    AttributesVec.push_back(AttributeSet::get(F->getContext(),
847249423Sdim                                              PAL.getFnAttributes()));
848193323Sed
849193323Sed  // Reconstruct the AttributesList based on the vector we constructed.
850249423Sdim  AttributeSet NewPAL = AttributeSet::get(F->getContext(), AttributesVec);
851193323Sed
852193323Sed  // Create the new function type based on the recomputed parameters.
853206083Srdivacky  FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
854193323Sed
855193323Sed  // No change?
856193323Sed  if (NFTy == FTy)
857193323Sed    return false;
858193323Sed
859193323Sed  // Create the new function body and insert it into the module...
860193323Sed  Function *NF = Function::Create(NFTy, F->getLinkage());
861193323Sed  NF->copyAttributesFrom(F);
862193323Sed  NF->setAttributes(NewPAL);
863193323Sed  // Insert the new function before the old function, so we won't be processing
864193323Sed  // it again.
865193323Sed  F->getParent()->getFunctionList().insert(F, NF);
866193323Sed  NF->takeName(F);
867193323Sed
868193323Sed  // Loop over all of the callers of the function, transforming the call sites
869193323Sed  // to pass in a smaller number of arguments into the new function.
870193323Sed  //
871193323Sed  std::vector<Value*> Args;
872193323Sed  while (!F->use_empty()) {
873276479Sdim    CallSite CS(F->user_back());
874193323Sed    Instruction *Call = CS.getInstruction();
875193323Sed
876193323Sed    AttributesVec.clear();
877249423Sdim    const AttributeSet &CallPAL = CS.getAttributes();
878193323Sed
879193323Sed    // The call return attributes.
880249423Sdim    AttributeSet RAttrs = CallPAL.getRetAttributes();
881249423Sdim
882193323Sed    // Adjust in case the function was changed to return void.
883243830Sdim    RAttrs =
884249423Sdim      AttributeSet::get(NF->getContext(), AttributeSet::ReturnIndex,
885249423Sdim                        AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
886249423Sdim        removeAttributes(AttributeFuncs::
887249423Sdim                         typeIncompatible(NF->getReturnType(),
888249423Sdim                                          AttributeSet::ReturnIndex),
889249423Sdim                         AttributeSet::ReturnIndex));
890249423Sdim    if (RAttrs.hasAttributes(AttributeSet::ReturnIndex))
891249423Sdim      AttributesVec.push_back(AttributeSet::get(NF->getContext(), RAttrs));
892193323Sed
893193323Sed    // Declare these outside of the loops, so we can reuse them for the second
894193323Sed    // loop, which loops the varargs.
895193323Sed    CallSite::arg_iterator I = CS.arg_begin();
896193323Sed    unsigned i = 0;
897193323Sed    // Loop over those operands, corresponding to the normal arguments to the
898193323Sed    // original function, and add those that are still alive.
899193323Sed    for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
900193323Sed      if (ArgAlive[i]) {
901193323Sed        Args.push_back(*I);
902193323Sed        // Get original parameter attributes, but skip return attributes.
903249423Sdim        if (CallPAL.hasAttributes(i + 1)) {
904249423Sdim          AttrBuilder B(CallPAL, i + 1);
905261991Sdim          // If the return type has changed, then get rid of 'returned' on the
906261991Sdim          // call site. The alternative is to make all 'returned' attributes on
907261991Sdim          // call sites keep the return value alive just like 'returned'
908261991Sdim          // attributes on function declaration but it's less clearly a win
909261991Sdim          // and this is not an expected case anyway
910261991Sdim          if (NRetTy != RetTy && B.contains(Attribute::Returned))
911261991Sdim            B.removeAttribute(Attribute::Returned);
912249423Sdim          AttributesVec.
913249423Sdim            push_back(AttributeSet::get(F->getContext(), Args.size(), B));
914249423Sdim        }
915193323Sed      }
916193323Sed
917193323Sed    // Push any varargs arguments on the list. Don't forget their attributes.
918193323Sed    for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
919193323Sed      Args.push_back(*I);
920249423Sdim      if (CallPAL.hasAttributes(i + 1)) {
921249423Sdim        AttrBuilder B(CallPAL, i + 1);
922249423Sdim        AttributesVec.
923249423Sdim          push_back(AttributeSet::get(F->getContext(), Args.size(), B));
924249423Sdim      }
925193323Sed    }
926193323Sed
927249423Sdim    if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
928249423Sdim      AttributesVec.push_back(AttributeSet::get(Call->getContext(),
929249423Sdim                                                CallPAL.getFnAttributes()));
930193323Sed
931193323Sed    // Reconstruct the AttributesList based on the vector we constructed.
932249423Sdim    AttributeSet NewCallPAL = AttributeSet::get(F->getContext(), AttributesVec);
933193323Sed
934193323Sed    Instruction *New;
935193323Sed    if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
936193323Sed      New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
937224145Sdim                               Args, "", Call);
938193323Sed      cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
939193323Sed      cast<InvokeInst>(New)->setAttributes(NewCallPAL);
940193323Sed    } else {
941224145Sdim      New = CallInst::Create(NF, Args, "", Call);
942193323Sed      cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
943193323Sed      cast<CallInst>(New)->setAttributes(NewCallPAL);
944193323Sed      if (cast<CallInst>(Call)->isTailCall())
945193323Sed        cast<CallInst>(New)->setTailCall();
946193323Sed    }
947212904Sdim    New->setDebugLoc(Call->getDebugLoc());
948207618Srdivacky
949193323Sed    Args.clear();
950193323Sed
951193323Sed    if (!Call->use_empty()) {
952193323Sed      if (New->getType() == Call->getType()) {
953193323Sed        // Return type not changed? Just replace users then.
954193323Sed        Call->replaceAllUsesWith(New);
955193323Sed        New->takeName(Call);
956206083Srdivacky      } else if (New->getType()->isVoidTy()) {
957193323Sed        // Our return value has uses, but they will get removed later on.
958193323Sed        // Replace by null for now.
959218893Sdim        if (!Call->getType()->isX86_MMXTy())
960218893Sdim          Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
961193323Sed      } else {
962204642Srdivacky        assert(RetTy->isStructTy() &&
963193323Sed               "Return type changed, but not into a void. The old return type"
964193323Sed               " must have been a struct!");
965193323Sed        Instruction *InsertPt = Call;
966193323Sed        if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
967193323Sed          BasicBlock::iterator IP = II->getNormalDest()->begin();
968193323Sed          while (isa<PHINode>(IP)) ++IP;
969193323Sed          InsertPt = IP;
970193323Sed        }
971206083Srdivacky
972193323Sed        // We used to return a struct. Instead of doing smart stuff with all the
973193323Sed        // uses of this struct, we will just rebuild it using
974193323Sed        // extract/insertvalue chaining and let instcombine clean that up.
975193323Sed        //
976193323Sed        // Start out building up our return value from undef
977198090Srdivacky        Value *RetVal = UndefValue::get(RetTy);
978193323Sed        for (unsigned i = 0; i != RetCount; ++i)
979193323Sed          if (NewRetIdxs[i] != -1) {
980193323Sed            Value *V;
981193323Sed            if (RetTypes.size() > 1)
982193323Sed              // We are still returning a struct, so extract the value from our
983193323Sed              // return value
984193323Sed              V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret",
985193323Sed                                           InsertPt);
986193323Sed            else
987193323Sed              // We are now returning a single element, so just insert that
988193323Sed              V = New;
989193323Sed            // Insert the value at the old position
990193323Sed            RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt);
991193323Sed          }
992193323Sed        // Now, replace all uses of the old call instruction with the return
993193323Sed        // struct we built
994193323Sed        Call->replaceAllUsesWith(RetVal);
995193323Sed        New->takeName(Call);
996193323Sed      }
997193323Sed    }
998193323Sed
999193323Sed    // Finally, remove the old call from the program, reducing the use-count of
1000193323Sed    // F.
1001193323Sed    Call->eraseFromParent();
1002193323Sed  }
1003193323Sed
1004193323Sed  // Since we have now created the new function, splice the body of the old
1005193323Sed  // function right into the new function, leaving the old rotting hulk of the
1006193323Sed  // function empty.
1007193323Sed  NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
1008193323Sed
1009221345Sdim  // Loop over the argument list, transferring uses of the old arguments over to
1010221345Sdim  // the new arguments, also transferring over the names as well.
1011193323Sed  i = 0;
1012193323Sed  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
1013193323Sed       I2 = NF->arg_begin(); I != E; ++I, ++i)
1014193323Sed    if (ArgAlive[i]) {
1015193323Sed      // If this is a live argument, move the name and users over to the new
1016193323Sed      // version.
1017193323Sed      I->replaceAllUsesWith(I2);
1018193323Sed      I2->takeName(I);
1019193323Sed      ++I2;
1020193323Sed    } else {
1021193323Sed      // If this argument is dead, replace any uses of it with null constants
1022193323Sed      // (these are guaranteed to become unused later on).
1023218893Sdim      if (!I->getType()->isX86_MMXTy())
1024218893Sdim        I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
1025193323Sed    }
1026193323Sed
1027193323Sed  // If we change the return value of the function we must rewrite any return
1028193323Sed  // instructions.  Check this now.
1029193323Sed  if (F->getReturnType() != NF->getReturnType())
1030193323Sed    for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
1031193323Sed      if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
1032193323Sed        Value *RetVal;
1033193323Sed
1034208599Srdivacky        if (NFTy->getReturnType()->isVoidTy()) {
1035276479Sdim          RetVal = nullptr;
1036193323Sed        } else {
1037204642Srdivacky          assert (RetTy->isStructTy());
1038193323Sed          // The original return value was a struct, insert
1039193323Sed          // extractvalue/insertvalue chains to extract only the values we need
1040193323Sed          // to return and insert them into our new result.
1041193323Sed          // This does generate messy code, but we'll let it to instcombine to
1042193323Sed          // clean that up.
1043193323Sed          Value *OldRet = RI->getOperand(0);
1044193323Sed          // Start out building up our return value from undef
1045198090Srdivacky          RetVal = UndefValue::get(NRetTy);
1046193323Sed          for (unsigned i = 0; i != RetCount; ++i)
1047193323Sed            if (NewRetIdxs[i] != -1) {
1048193323Sed              ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
1049193323Sed                                                              "oldret", RI);
1050193323Sed              if (RetTypes.size() > 1) {
1051193323Sed                // We're still returning a struct, so reinsert the value into
1052193323Sed                // our new return value at the new index
1053193323Sed
1054193323Sed                RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
1055193323Sed                                                 "newret", RI);
1056193323Sed              } else {
1057193323Sed                // We are now only returning a simple value, so just return the
1058193323Sed                // extracted value.
1059193323Sed                RetVal = EV;
1060193323Sed              }
1061193323Sed            }
1062193323Sed        }
1063193323Sed        // Replace the return instruction with one returning the new return
1064193323Sed        // value (possibly 0 if we became void).
1065198090Srdivacky        ReturnInst::Create(F->getContext(), RetVal, RI);
1066193323Sed        BB->getInstList().erase(RI);
1067193323Sed      }
1068193323Sed
1069243830Sdim  // Patch the pointer to LLVM function in debug info descriptor.
1070276479Sdim  auto DI = FunctionDIs.find(F);
1071243830Sdim  if (DI != FunctionDIs.end())
1072243830Sdim    DI->second.replaceFunction(NF);
1073243830Sdim
1074193323Sed  // Now that the old function is dead, delete it.
1075193323Sed  F->eraseFromParent();
1076193323Sed
1077193323Sed  return true;
1078193323Sed}
1079193323Sed
1080193323Sedbool DAE::runOnModule(Module &M) {
1081193323Sed  bool Changed = false;
1082193323Sed
1083243830Sdim  // Collect debug info descriptors for functions.
1084276479Sdim  FunctionDIs = makeSubprogramMap(M);
1085243830Sdim
1086193323Sed  // First pass: Do a simple check to see if any functions can have their "..."
1087193323Sed  // removed.  We can do this if they never call va_start.  This loop cannot be
1088193323Sed  // fused with the next loop, because deleting a function invalidates
1089193323Sed  // information computed while surveying other functions.
1090202375Srdivacky  DEBUG(dbgs() << "DAE - Deleting dead varargs\n");
1091193323Sed  for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
1092193323Sed    Function &F = *I++;
1093193323Sed    if (F.getFunctionType()->isVarArg())
1094193323Sed      Changed |= DeleteDeadVarargs(F);
1095193323Sed  }
1096193323Sed
1097193323Sed  // Second phase:loop through the module, determining which arguments are live.
1098193323Sed  // We assume all arguments are dead unless proven otherwise (allowing us to
1099193323Sed  // determine that dead arguments passed into recursive functions are dead).
1100193323Sed  //
1101202375Srdivacky  DEBUG(dbgs() << "DAE - Determining liveness\n");
1102280031Sdim  for (auto &F : M)
1103280031Sdim    SurveyFunction(F);
1104206083Srdivacky
1105193323Sed  // Now, remove all dead arguments and return values from each function in
1106206083Srdivacky  // turn.
1107193323Sed  for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
1108206083Srdivacky    // Increment now, because the function will probably get removed (ie.
1109193323Sed    // replaced by a new one).
1110193323Sed    Function *F = I++;
1111193323Sed    Changed |= RemoveDeadStuffFromFunction(F);
1112193323Sed  }
1113218893Sdim
1114218893Sdim  // Finally, look for any unused parameters in functions with non-local
1115218893Sdim  // linkage and replace the passed in parameters with undef.
1116280031Sdim  for (auto &F : M)
1117218893Sdim    Changed |= RemoveDeadArgumentsFromCallers(F);
1118218893Sdim
1119193323Sed  return Changed;
1120193323Sed}
1121