f361d5b10b9d64de484ab605c4f002fec9953d21
[oota-llvm.git] / lib / Transforms / IPO / DeadArgumentElimination.cpp
1 //===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 arguments 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.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #define DEBUG_TYPE "deadargelim"
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constant.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/Module.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/CallSite.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/Statistic.h"
32 #include <iostream>
33 #include <set>
34 using namespace llvm;
35
36 namespace {
37   Statistic<> NumArgumentsEliminated("deadargelim",
38                                      "Number of unread args removed");
39   Statistic<> NumRetValsEliminated("deadargelim",
40                                    "Number of unused return values removed");
41
42   /// DAE - The dead argument elimination pass.
43   ///
44   class DAE : public ModulePass {
45     /// Liveness enum - During our initial pass over the program, we determine
46     /// that things are either definately alive, definately dead, or in need of
47     /// interprocedural analysis (MaybeLive).
48     ///
49     enum Liveness { Live, MaybeLive, Dead };
50
51     /// LiveArguments, MaybeLiveArguments, DeadArguments - These sets contain
52     /// all of the arguments in the program.  The Dead set contains arguments
53     /// which are completely dead (never used in the function).  The MaybeLive
54     /// set contains arguments which are only passed into other function calls,
55     /// thus may be live and may be dead.  The Live set contains arguments which
56     /// are known to be alive.
57     ///
58     std::set<Argument*> DeadArguments, MaybeLiveArguments, LiveArguments;
59
60     /// DeadRetVal, MaybeLiveRetVal, LifeRetVal - These sets contain all of the
61     /// functions in the program.  The Dead set contains functions whose return
62     /// value is known to be dead.  The MaybeLive set contains functions whose
63     /// return values are only used by return instructions, and the Live set
64     /// contains functions whose return values are used, functions that are
65     /// external, and functions that already return void.
66     ///
67     std::set<Function*> DeadRetVal, MaybeLiveRetVal, LiveRetVal;
68
69     /// InstructionsToInspect - As we mark arguments and return values
70     /// MaybeLive, we keep track of which instructions could make the values
71     /// live here.  Once the entire program has had the return value and
72     /// arguments analyzed, this set is scanned to promote the MaybeLive objects
73     /// to be Live if they really are used.
74     std::vector<Instruction*> InstructionsToInspect;
75
76     /// CallSites - Keep track of the call sites of functions that have
77     /// MaybeLive arguments or return values.
78     std::multimap<Function*, CallSite> CallSites;
79
80   public:
81     bool runOnModule(Module &M);
82
83     virtual bool ShouldHackArguments() const { return false; }
84
85   private:
86     Liveness getArgumentLiveness(const Argument &A);
87     bool isMaybeLiveArgumentNowLive(Argument *Arg);
88
89     bool DeleteDeadVarargs(Function &Fn);
90     void SurveyFunction(Function &Fn);
91
92     void MarkArgumentLive(Argument *Arg);
93     void MarkRetValLive(Function *F);
94     void MarkReturnInstArgumentLive(ReturnInst *RI);
95
96     void RemoveDeadArgumentsFromFunction(Function *F);
97   };
98   RegisterPass<DAE> X("deadargelim", "Dead Argument Elimination");
99
100   /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
101   /// deletes arguments to functions which are external.  This is only for use
102   /// by bugpoint.
103   struct DAH : public DAE {
104     virtual bool ShouldHackArguments() const { return true; }
105   };
106   RegisterPass<DAH> Y("deadarghaX0r",
107                       "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)");
108 }
109
110 /// createDeadArgEliminationPass - This pass removes arguments from functions
111 /// which are not used by the body of the function.
112 ///
113 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
114 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
115
116 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if
117 /// llvm.vastart is never called, the varargs list is dead for the function.
118 bool DAE::DeleteDeadVarargs(Function &Fn) {
119   assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
120   if (Fn.isExternal() || !Fn.hasInternalLinkage()) return false;
121   
122   // Ensure that the function is only directly called.
123   for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end(); I != E; ++I) {
124     // If this use is anything other than a call site, give up.
125     CallSite CS = CallSite::get(*I);
126     Instruction *TheCall = CS.getInstruction();
127     if (!TheCall) return false;   // Not a direct call site?
128    
129     // The addr of this function is passed to the call.
130     if (I.getOperandNo() != 0) return false;
131   }
132   
133   // Okay, we know we can transform this function if safe.  Scan its body
134   // looking for calls to llvm.vastart.
135   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
136     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
137       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
138         if (II->getIntrinsicID() == Intrinsic::vastart)
139           return false;
140       }
141     }
142   }
143   
144   // If we get here, there are no calls to llvm.vastart in the function body,
145   // remove the "..." and adjust all the calls.
146   
147   // Start by computing a new prototype for the function, which is the same as
148   // the old function, but has fewer arguments.
149   const FunctionType *FTy = Fn.getFunctionType();
150   std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
151   FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), Params, false);
152   unsigned NumArgs = Params.size();
153   
154   // Create the new function body and insert it into the module...
155   Function *NF = new Function(NFTy, Fn.getLinkage(), Fn.getName());
156   NF->setCallingConv(Fn.getCallingConv());
157   Fn.getParent()->getFunctionList().insert(&Fn, NF);
158   
159   // Loop over all of the callers of the function, transforming the call sites
160   // to pass in a smaller number of arguments into the new function.
161   //
162   std::vector<Value*> Args;
163   while (!Fn.use_empty()) {
164     CallSite CS = CallSite::get(Fn.use_back());
165     Instruction *Call = CS.getInstruction();
166     
167     // Loop over the operands, dropping extraneous ones at the end of the list.
168     Args.assign(CS.arg_begin(), CS.arg_begin()+NumArgs);
169     
170     Instruction *New;
171     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
172       New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
173                            Args, "", Call);
174       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
175     } else {
176       New = new CallInst(NF, Args, "", Call);
177       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
178       if (cast<CallInst>(Call)->isTailCall())
179         cast<CallInst>(New)->setTailCall();
180     }
181     Args.clear();
182     
183     if (!Call->use_empty())
184       Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
185     
186     if (Call->hasName()) {
187       std::string Name = Call->getName();
188       Call->setName("");
189       New->setName(Name);
190     }
191     
192     // Finally, remove the old call from the program, reducing the use-count of
193     // F.
194     Call->getParent()->getInstList().erase(Call);
195   }
196   
197   // Since we have now created the new function, splice the body of the old
198   // function right into the new function, leaving the old rotting hulk of the
199   // function empty.
200   NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
201   
202   // Loop over the argument list, transfering uses of the old arguments over to
203   // the new arguments, also transfering over the names as well.  While we're at
204   // it, remove the dead arguments from the DeadArguments list.
205   //
206   for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
207        I2 = NF->arg_begin(); I != E; ++I, ++I2) {
208     // Move the name and users over to the new version.
209     I->replaceAllUsesWith(I2);
210     I2->setName(I->getName());
211   }
212   
213   // Finally, nuke the old function.
214   Fn.eraseFromParent();
215   return true;
216 }
217
218
219 static inline bool CallPassesValueThoughVararg(Instruction *Call,
220                                                const Value *Arg) {
221   CallSite CS = CallSite::get(Call);
222   const Type *CalledValueTy = CS.getCalledValue()->getType();
223   const Type *FTy = cast<PointerType>(CalledValueTy)->getElementType();
224   unsigned NumFixedArgs = cast<FunctionType>(FTy)->getNumParams();
225   for (CallSite::arg_iterator AI = CS.arg_begin()+NumFixedArgs;
226        AI != CS.arg_end(); ++AI)
227     if (AI->get() == Arg)
228       return true;
229   return false;
230 }
231
232 // getArgumentLiveness - Inspect an argument, determining if is known Live
233 // (used in a computation), MaybeLive (only passed as an argument to a call), or
234 // Dead (not used).
235 DAE::Liveness DAE::getArgumentLiveness(const Argument &A) {
236   // If this is the return value of a csret function, it's not really dead.
237   if (A.getParent()->getCallingConv() == CallingConv::CSRet &&
238       &*A.getParent()->arg_begin() == &A)
239     return Live;
240   
241   if (A.use_empty())  // First check, directly dead?
242     return Dead;
243
244   // Scan through all of the uses, looking for non-argument passing uses.
245   for (Value::use_const_iterator I = A.use_begin(), E = A.use_end(); I!=E;++I) {
246     // Return instructions do not immediately effect liveness.
247     if (isa<ReturnInst>(*I))
248       continue;
249
250     CallSite CS = CallSite::get(const_cast<User*>(*I));
251     if (!CS.getInstruction()) {
252       // If its used by something that is not a call or invoke, it's alive!
253       return Live;
254     }
255     // If it's an indirect call, mark it alive...
256     Function *Callee = CS.getCalledFunction();
257     if (!Callee) return Live;
258
259     // Check to see if it's passed through a va_arg area: if so, we cannot
260     // remove it.
261     if (CallPassesValueThoughVararg(CS.getInstruction(), &A))
262       return Live;   // If passed through va_arg area, we cannot remove it
263   }
264
265   return MaybeLive;  // It must be used, but only as argument to a function
266 }
267
268
269 // SurveyFunction - This performs the initial survey of the specified function,
270 // checking out whether or not it uses any of its incoming arguments or whether
271 // any callers use the return value.  This fills in the
272 // (Dead|MaybeLive|Live)(Arguments|RetVal) sets.
273 //
274 // We consider arguments of non-internal functions to be intrinsically alive as
275 // well as arguments to functions which have their "address taken".
276 //
277 void DAE::SurveyFunction(Function &F) {
278   bool FunctionIntrinsicallyLive = false;
279   Liveness RetValLiveness = F.getReturnType() == Type::VoidTy ? Live : Dead;
280
281   if (!F.hasInternalLinkage() &&
282       (!ShouldHackArguments() || F.getIntrinsicID()))
283     FunctionIntrinsicallyLive = true;
284   else
285     for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
286       // If this use is anything other than a call site, the function is alive.
287       CallSite CS = CallSite::get(*I);
288       Instruction *TheCall = CS.getInstruction();
289       if (!TheCall) {   // Not a direct call site?
290         FunctionIntrinsicallyLive = true;
291         break;
292       }
293
294       // Check to see if the return value is used...
295       if (RetValLiveness != Live)
296         for (Value::use_iterator I = TheCall->use_begin(),
297                E = TheCall->use_end(); I != E; ++I)
298           if (isa<ReturnInst>(cast<Instruction>(*I))) {
299             RetValLiveness = MaybeLive;
300           } else if (isa<CallInst>(cast<Instruction>(*I)) ||
301                      isa<InvokeInst>(cast<Instruction>(*I))) {
302             if (CallPassesValueThoughVararg(cast<Instruction>(*I), TheCall) ||
303                 !CallSite::get(cast<Instruction>(*I)).getCalledFunction()) {
304               RetValLiveness = Live;
305               break;
306             } else {
307               RetValLiveness = MaybeLive;
308             }
309           } else {
310             RetValLiveness = Live;
311             break;
312           }
313
314       // If the function is PASSED IN as an argument, its address has been taken
315       for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
316            AI != E; ++AI)
317         if (AI->get() == &F) {
318           FunctionIntrinsicallyLive = true;
319           break;
320         }
321       if (FunctionIntrinsicallyLive) break;
322     }
323
324   if (FunctionIntrinsicallyLive) {
325     DEBUG(std::cerr << "  Intrinsically live fn: " << F.getName() << "\n");
326     for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
327          AI != E; ++AI)
328       LiveArguments.insert(AI);
329     LiveRetVal.insert(&F);
330     return;
331   }
332
333   switch (RetValLiveness) {
334   case Live:      LiveRetVal.insert(&F); break;
335   case MaybeLive: MaybeLiveRetVal.insert(&F); break;
336   case Dead:      DeadRetVal.insert(&F); break;
337   }
338
339   DEBUG(std::cerr << "  Inspecting args for fn: " << F.getName() << "\n");
340
341   // If it is not intrinsically alive, we know that all users of the
342   // function are call sites.  Mark all of the arguments live which are
343   // directly used, and keep track of all of the call sites of this function
344   // if there are any arguments we assume that are dead.
345   //
346   bool AnyMaybeLiveArgs = false;
347   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
348        AI != E; ++AI)
349     switch (getArgumentLiveness(*AI)) {
350     case Live:
351       DEBUG(std::cerr << "    Arg live by use: " << AI->getName() << "\n");
352       LiveArguments.insert(AI);
353       break;
354     case Dead:
355       DEBUG(std::cerr << "    Arg definitely dead: " <<AI->getName()<<"\n");
356       DeadArguments.insert(AI);
357       break;
358     case MaybeLive:
359       DEBUG(std::cerr << "    Arg only passed to calls: "
360             << AI->getName() << "\n");
361       AnyMaybeLiveArgs = true;
362       MaybeLiveArguments.insert(AI);
363       break;
364     }
365
366   // If there are any "MaybeLive" arguments, we need to check callees of
367   // this function when/if they become alive.  Record which functions are
368   // callees...
369   if (AnyMaybeLiveArgs || RetValLiveness == MaybeLive)
370     for (Value::use_iterator I = F.use_begin(), E = F.use_end();
371          I != E; ++I) {
372       if (AnyMaybeLiveArgs)
373         CallSites.insert(std::make_pair(&F, CallSite::get(*I)));
374
375       if (RetValLiveness == MaybeLive)
376         for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
377              UI != E; ++UI)
378           InstructionsToInspect.push_back(cast<Instruction>(*UI));
379     }
380 }
381
382 // isMaybeLiveArgumentNowLive - Check to see if Arg is alive.  At this point, we
383 // know that the only uses of Arg are to be passed in as an argument to a
384 // function call or return.  Check to see if the formal argument passed in is in
385 // the LiveArguments set.  If so, return true.
386 //
387 bool DAE::isMaybeLiveArgumentNowLive(Argument *Arg) {
388   for (Value::use_iterator I = Arg->use_begin(), E = Arg->use_end(); I!=E; ++I){
389     if (isa<ReturnInst>(*I)) {
390       if (LiveRetVal.count(Arg->getParent())) return true;
391       continue;
392     }
393
394     CallSite CS = CallSite::get(*I);
395
396     // We know that this can only be used for direct calls...
397     Function *Callee = CS.getCalledFunction();
398
399     // Loop over all of the arguments (because Arg may be passed into the call
400     // multiple times) and check to see if any are now alive...
401     CallSite::arg_iterator CSAI = CS.arg_begin();
402     for (Function::arg_iterator AI = Callee->arg_begin(), E = Callee->arg_end();
403          AI != E; ++AI, ++CSAI)
404       // If this is the argument we are looking for, check to see if it's alive
405       if (*CSAI == Arg && LiveArguments.count(AI))
406         return true;
407   }
408   return false;
409 }
410
411 /// MarkArgumentLive - The MaybeLive argument 'Arg' is now known to be alive.
412 /// Mark it live in the specified sets and recursively mark arguments in callers
413 /// live that are needed to pass in a value.
414 ///
415 void DAE::MarkArgumentLive(Argument *Arg) {
416   std::set<Argument*>::iterator It = MaybeLiveArguments.lower_bound(Arg);
417   if (It == MaybeLiveArguments.end() || *It != Arg) return;
418
419   DEBUG(std::cerr << "  MaybeLive argument now live: " << Arg->getName()<<"\n");
420   MaybeLiveArguments.erase(It);
421   LiveArguments.insert(Arg);
422
423   // Loop over all of the call sites of the function, making any arguments
424   // passed in to provide a value for this argument live as necessary.
425   //
426   Function *Fn = Arg->getParent();
427   unsigned ArgNo = std::distance(Fn->arg_begin(), Function::arg_iterator(Arg));
428
429   std::multimap<Function*, CallSite>::iterator I = CallSites.lower_bound(Fn);
430   for (; I != CallSites.end() && I->first == Fn; ++I) {
431     CallSite CS = I->second;
432     Value *ArgVal = *(CS.arg_begin()+ArgNo);
433     if (Argument *ActualArg = dyn_cast<Argument>(ArgVal)) {
434       MarkArgumentLive(ActualArg);
435     } else {
436       // If the value passed in at this call site is a return value computed by
437       // some other call site, make sure to mark the return value at the other
438       // call site as being needed.
439       CallSite ArgCS = CallSite::get(ArgVal);
440       if (ArgCS.getInstruction())
441         if (Function *Fn = ArgCS.getCalledFunction())
442           MarkRetValLive(Fn);
443     }
444   }
445 }
446
447 /// MarkArgumentLive - The MaybeLive return value for the specified function is
448 /// now known to be alive.  Propagate this fact to the return instructions which
449 /// produce it.
450 void DAE::MarkRetValLive(Function *F) {
451   assert(F && "Shame shame, we can't have null pointers here!");
452
453   // Check to see if we already knew it was live
454   std::set<Function*>::iterator I = MaybeLiveRetVal.lower_bound(F);
455   if (I == MaybeLiveRetVal.end() || *I != F) return;  // It's already alive!
456
457   DEBUG(std::cerr << "  MaybeLive retval now live: " << F->getName() << "\n");
458
459   MaybeLiveRetVal.erase(I);
460   LiveRetVal.insert(F);        // It is now known to be live!
461
462   // Loop over all of the functions, noticing that the return value is now live.
463   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
464     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
465       MarkReturnInstArgumentLive(RI);
466 }
467
468 void DAE::MarkReturnInstArgumentLive(ReturnInst *RI) {
469   Value *Op = RI->getOperand(0);
470   if (Argument *A = dyn_cast<Argument>(Op)) {
471     MarkArgumentLive(A);
472   } else if (CallInst *CI = dyn_cast<CallInst>(Op)) {
473     if (Function *F = CI->getCalledFunction())
474       MarkRetValLive(F);
475   } else if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
476     if (Function *F = II->getCalledFunction())
477       MarkRetValLive(F);
478   }
479 }
480
481 // RemoveDeadArgumentsFromFunction - We know that F has dead arguments, as
482 // specified by the DeadArguments list.  Transform the function and all of the
483 // callees of the function to not have these arguments.
484 //
485 void DAE::RemoveDeadArgumentsFromFunction(Function *F) {
486   // Start by computing a new prototype for the function, which is the same as
487   // the old function, but has fewer arguments.
488   const FunctionType *FTy = F->getFunctionType();
489   std::vector<const Type*> Params;
490
491   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
492     if (!DeadArguments.count(I))
493       Params.push_back(I->getType());
494
495   const Type *RetTy = FTy->getReturnType();
496   if (DeadRetVal.count(F)) {
497     RetTy = Type::VoidTy;
498     DeadRetVal.erase(F);
499   }
500
501   // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
502   // have zero fixed arguments.
503   //
504   // FIXME: once this bug is fixed in the CWriter, this hack should be removed.
505   //
506   bool ExtraArgHack = false;
507   if (Params.empty() && FTy->isVarArg()) {
508     ExtraArgHack = true;
509     Params.push_back(Type::IntTy);
510   }
511
512   FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
513
514   // Create the new function body and insert it into the module...
515   Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
516   NF->setCallingConv(F->getCallingConv());
517   F->getParent()->getFunctionList().insert(F, NF);
518
519   // Loop over all of the callers of the function, transforming the call sites
520   // to pass in a smaller number of arguments into the new function.
521   //
522   std::vector<Value*> Args;
523   while (!F->use_empty()) {
524     CallSite CS = CallSite::get(F->use_back());
525     Instruction *Call = CS.getInstruction();
526
527     // Loop over the operands, deleting dead ones...
528     CallSite::arg_iterator AI = CS.arg_begin();
529     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
530          I != E; ++I, ++AI)
531       if (!DeadArguments.count(I))      // Remove operands for dead arguments
532         Args.push_back(*AI);
533
534     if (ExtraArgHack)
535       Args.push_back(Constant::getNullValue(Type::IntTy));
536
537     // Push any varargs arguments on the list
538     for (; AI != CS.arg_end(); ++AI)
539       Args.push_back(*AI);
540
541     Instruction *New;
542     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
543       New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
544                            Args, "", Call);
545       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
546     } else {
547       New = new CallInst(NF, Args, "", Call);
548       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
549       if (cast<CallInst>(Call)->isTailCall())
550         cast<CallInst>(New)->setTailCall();
551     }
552     Args.clear();
553
554     if (!Call->use_empty()) {
555       if (New->getType() == Type::VoidTy)
556         Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
557       else {
558         Call->replaceAllUsesWith(New);
559         std::string Name = Call->getName();
560         Call->setName("");
561         New->setName(Name);
562       }
563     }
564
565     // Finally, remove the old call from the program, reducing the use-count of
566     // F.
567     Call->getParent()->getInstList().erase(Call);
568   }
569
570   // Since we have now created the new function, splice the body of the old
571   // function right into the new function, leaving the old rotting hulk of the
572   // function empty.
573   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
574
575   // Loop over the argument list, transfering uses of the old arguments over to
576   // the new arguments, also transfering over the names as well.  While we're at
577   // it, remove the dead arguments from the DeadArguments list.
578   //
579   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
580          I2 = NF->arg_begin();
581        I != E; ++I)
582     if (!DeadArguments.count(I)) {
583       // If this is a live argument, move the name and users over to the new
584       // version.
585       I->replaceAllUsesWith(I2);
586       I2->setName(I->getName());
587       ++I2;
588     } else {
589       // If this argument is dead, replace any uses of it with null constants
590       // (these are guaranteed to only be operands to call instructions which
591       // will later be simplified).
592       I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
593       DeadArguments.erase(I);
594     }
595
596   // If we change the return value of the function we must rewrite any return
597   // instructions.  Check this now.
598   if (F->getReturnType() != NF->getReturnType())
599     for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
600       if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
601         new ReturnInst(0, RI);
602         BB->getInstList().erase(RI);
603       }
604
605   // Now that the old function is dead, delete it.
606   F->getParent()->getFunctionList().erase(F);
607 }
608
609 bool DAE::runOnModule(Module &M) {
610   // First phase: loop through the module, determining which arguments are live.
611   // We assume all arguments are dead unless proven otherwise (allowing us to
612   // determine that dead arguments passed into recursive functions are dead).
613   //
614   DEBUG(std::cerr << "DAE - Determining liveness\n");
615   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
616     Function &F = *I++;
617     if (F.getFunctionType()->isVarArg())
618       if (DeleteDeadVarargs(F))
619         continue;
620       
621     SurveyFunction(F);
622   }
623
624   // Loop over the instructions to inspect, propagating liveness among arguments
625   // and return values which are MaybeLive.
626
627   while (!InstructionsToInspect.empty()) {
628     Instruction *I = InstructionsToInspect.back();
629     InstructionsToInspect.pop_back();
630
631     if (ReturnInst *RI = dyn_cast<ReturnInst>(I)) {
632       // For return instructions, we just have to check to see if the return
633       // value for the current function is known now to be alive.  If so, any
634       // arguments used by it are now alive, and any call instruction return
635       // value is alive as well.
636       if (LiveRetVal.count(RI->getParent()->getParent()))
637         MarkReturnInstArgumentLive(RI);
638
639     } else {
640       CallSite CS = CallSite::get(I);
641       assert(CS.getInstruction() && "Unknown instruction for the I2I list!");
642
643       Function *Callee = CS.getCalledFunction();
644
645       // If we found a call or invoke instruction on this list, that means that
646       // an argument of the function is a call instruction.  If the argument is
647       // live, then the return value of the called instruction is now live.
648       //
649       CallSite::arg_iterator AI = CS.arg_begin();  // ActualIterator
650       for (Function::arg_iterator FI = Callee->arg_begin(),
651              E = Callee->arg_end(); FI != E; ++AI, ++FI) {
652         // If this argument is another call...
653         CallSite ArgCS = CallSite::get(*AI);
654         if (ArgCS.getInstruction() && LiveArguments.count(FI))
655           if (Function *Callee = ArgCS.getCalledFunction())
656             MarkRetValLive(Callee);
657       }
658     }
659   }
660
661   // Now we loop over all of the MaybeLive arguments, promoting them to be live
662   // arguments if one of the calls that uses the arguments to the calls they are
663   // passed into requires them to be live.  Of course this could make other
664   // arguments live, so process callers recursively.
665   //
666   // Because elements can be removed from the MaybeLiveArguments set, copy it to
667   // a temporary vector.
668   //
669   std::vector<Argument*> TmpArgList(MaybeLiveArguments.begin(),
670                                     MaybeLiveArguments.end());
671   for (unsigned i = 0, e = TmpArgList.size(); i != e; ++i) {
672     Argument *MLA = TmpArgList[i];
673     if (MaybeLiveArguments.count(MLA) &&
674         isMaybeLiveArgumentNowLive(MLA))
675       MarkArgumentLive(MLA);
676   }
677
678   // Recover memory early...
679   CallSites.clear();
680
681   // At this point, we know that all arguments in DeadArguments and
682   // MaybeLiveArguments are dead.  If the two sets are empty, there is nothing
683   // to do.
684   if (MaybeLiveArguments.empty() && DeadArguments.empty() &&
685       MaybeLiveRetVal.empty() && DeadRetVal.empty())
686     return false;
687
688   // Otherwise, compact into one set, and start eliminating the arguments from
689   // the functions.
690   DeadArguments.insert(MaybeLiveArguments.begin(), MaybeLiveArguments.end());
691   MaybeLiveArguments.clear();
692   DeadRetVal.insert(MaybeLiveRetVal.begin(), MaybeLiveRetVal.end());
693   MaybeLiveRetVal.clear();
694
695   LiveArguments.clear();
696   LiveRetVal.clear();
697
698   NumArgumentsEliminated += DeadArguments.size();
699   NumRetValsEliminated   += DeadRetVal.size();
700   while (!DeadArguments.empty())
701     RemoveDeadArgumentsFromFunction((*DeadArguments.begin())->getParent());
702
703   while (!DeadRetVal.empty())
704     RemoveDeadArgumentsFromFunction(*DeadRetVal.begin());
705   return true;
706 }