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