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