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