1 //===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
15 // This pass is often useful as a cleanup pass to run after aggressive
16 // interprocedural passes, which add possibly-dead arguments.
18 //===----------------------------------------------------------------------===//
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/ParameterAttributes.h"
30 #include "llvm/Support/CallSite.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/Compiler.h"
37 STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
38 STATISTIC(NumRetValsEliminated , "Number of unused return values removed");
41 /// DAE - The dead argument elimination pass.
43 class VISIBILITY_HIDDEN DAE : public ModulePass {
44 /// Liveness enum - During our initial pass over the program, we determine
45 /// that things are either definately alive, definately dead, or in need of
46 /// interprocedural analysis (MaybeLive).
48 enum Liveness { Live, MaybeLive, Dead };
50 /// LiveArguments, MaybeLiveArguments, DeadArguments - These sets contain
51 /// all of the arguments in the program. The Dead set contains arguments
52 /// which are completely dead (never used in the function). The MaybeLive
53 /// set contains arguments which are only passed into other function calls,
54 /// thus may be live and may be dead. The Live set contains arguments which
55 /// are known to be alive.
57 std::set<Argument*> DeadArguments, MaybeLiveArguments, LiveArguments;
59 /// DeadRetVal, MaybeLiveRetVal, LifeRetVal - These sets contain all of the
60 /// functions in the program. The Dead set contains functions whose return
61 /// value is known to be dead. The MaybeLive set contains functions whose
62 /// return values are only used by return instructions, and the Live set
63 /// contains functions whose return values are used, functions that are
64 /// external, and functions that already return void.
66 std::set<Function*> DeadRetVal, MaybeLiveRetVal, LiveRetVal;
68 /// InstructionsToInspect - As we mark arguments and return values
69 /// MaybeLive, we keep track of which instructions could make the values
70 /// live here. Once the entire program has had the return value and
71 /// arguments analyzed, this set is scanned to promote the MaybeLive objects
72 /// to be Live if they really are used.
73 std::vector<Instruction*> InstructionsToInspect;
75 /// CallSites - Keep track of the call sites of functions that have
76 /// MaybeLive arguments or return values.
77 std::multimap<Function*, CallSite> CallSites;
80 static char ID; // Pass identification, replacement for typeid
81 DAE() : ModulePass((intptr_t)&ID) {}
82 bool runOnModule(Module &M);
84 virtual bool ShouldHackArguments() const { return false; }
87 Liveness getArgumentLiveness(const Argument &A);
88 bool isMaybeLiveArgumentNowLive(Argument *Arg);
90 bool DeleteDeadVarargs(Function &Fn);
91 void SurveyFunction(Function &Fn);
93 void MarkArgumentLive(Argument *Arg);
94 void MarkRetValLive(Function *F);
95 void MarkReturnInstArgumentLive(ReturnInst *RI);
97 void RemoveDeadArgumentsFromFunction(Function *F);
100 RegisterPass<DAE> X("deadargelim", "Dead Argument Elimination");
102 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
103 /// deletes arguments to functions which are external. This is only for use
105 struct DAH : public DAE {
107 virtual bool ShouldHackArguments() const { return true; }
110 RegisterPass<DAH> Y("deadarghaX0r",
111 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)");
114 /// createDeadArgEliminationPass - This pass removes arguments from functions
115 /// which are not used by the body of the function.
117 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
118 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
120 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if
121 /// llvm.vastart is never called, the varargs list is dead for the function.
122 bool DAE::DeleteDeadVarargs(Function &Fn) {
123 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
124 if (Fn.isDeclaration() || !Fn.hasInternalLinkage()) return false;
126 // Ensure that the function is only directly called.
127 for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end(); I != E; ++I) {
128 // If this use is anything other than a call site, give up.
129 CallSite CS = CallSite::get(*I);
130 Instruction *TheCall = CS.getInstruction();
131 if (!TheCall) return false; // Not a direct call site?
133 // The addr of this function is passed to the call.
134 if (I.getOperandNo() != 0) return false;
137 // Okay, we know we can transform this function if safe. Scan its body
138 // looking for calls to llvm.vastart.
139 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
140 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
141 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
142 if (II->getIntrinsicID() == Intrinsic::vastart)
148 // If we get here, there are no calls to llvm.vastart in the function body,
149 // remove the "..." and adjust all the calls.
151 // Start by computing a new prototype for the function, which is the same as
152 // the old function, but has fewer arguments.
153 const FunctionType *FTy = Fn.getFunctionType();
154 std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
155 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), Params, false);
156 unsigned NumArgs = Params.size();
158 // Create the new function body and insert it into the module...
159 Function *NF = new Function(NFTy, Fn.getLinkage());
160 NF->setCallingConv(Fn.getCallingConv());
161 NF->setParamAttrs(Fn.getParamAttrs());
162 Fn.getParent()->getFunctionList().insert(&Fn, NF);
165 // Loop over all of the callers of the function, transforming the call sites
166 // to pass in a smaller number of arguments into the new function.
168 std::vector<Value*> Args;
169 while (!Fn.use_empty()) {
170 CallSite CS = CallSite::get(Fn.use_back());
171 Instruction *Call = CS.getInstruction();
173 // Pass all the same arguments.
174 Args.assign(CS.arg_begin(), CS.arg_begin()+NumArgs);
177 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
178 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
179 Args.begin(), Args.end(), "", Call);
180 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
181 cast<InvokeInst>(New)->setParamAttrs(NF->getParamAttrs());
183 New = new CallInst(NF, Args.begin(), Args.end(), "", Call);
184 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
185 cast<CallInst>(New)->setParamAttrs(NF->getParamAttrs());
186 if (cast<CallInst>(Call)->isTailCall())
187 cast<CallInst>(New)->setTailCall();
191 if (!Call->use_empty())
192 Call->replaceAllUsesWith(New);
196 // Finally, remove the old call from the program, reducing the use-count of
198 Call->eraseFromParent();
201 // Since we have now created the new function, splice the body of the old
202 // function right into the new function, leaving the old rotting hulk of the
204 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
206 // Loop over the argument list, transfering uses of the old arguments over to
207 // the new arguments, also transfering over the names as well. While we're at
208 // it, remove the dead arguments from the DeadArguments list.
210 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
211 I2 = NF->arg_begin(); I != E; ++I, ++I2) {
212 // Move the name and users over to the new version.
213 I->replaceAllUsesWith(I2);
217 // Finally, nuke the old function.
218 Fn.eraseFromParent();
223 static inline bool CallPassesValueThoughVararg(Instruction *Call,
225 CallSite CS = CallSite::get(Call);
226 const Type *CalledValueTy = CS.getCalledValue()->getType();
227 const Type *FTy = cast<PointerType>(CalledValueTy)->getElementType();
228 unsigned NumFixedArgs = cast<FunctionType>(FTy)->getNumParams();
229 for (CallSite::arg_iterator AI = CS.arg_begin()+NumFixedArgs;
230 AI != CS.arg_end(); ++AI)
231 if (AI->get() == Arg)
236 // getArgumentLiveness - Inspect an argument, determining if is known Live
237 // (used in a computation), MaybeLive (only passed as an argument to a call), or
239 DAE::Liveness DAE::getArgumentLiveness(const Argument &A) {
240 const Function *F = A.getParent();
242 // If this is the return value of a struct function, it's not really dead.
243 if (F->isStructReturn() && &*(F->arg_begin()) == &A)
246 if (A.use_empty()) // First check, directly dead?
249 // Scan through all of the uses, looking for non-argument passing uses.
250 for (Value::use_const_iterator I = A.use_begin(), E = A.use_end(); I!=E;++I) {
251 // Return instructions do not immediately effect liveness.
252 if (isa<ReturnInst>(*I))
255 CallSite CS = CallSite::get(const_cast<User*>(*I));
256 if (!CS.getInstruction()) {
257 // If its used by something that is not a call or invoke, it's alive!
260 // If it's an indirect call, mark it alive...
261 Function *Callee = CS.getCalledFunction();
262 if (!Callee) return Live;
264 // Check to see if it's passed through a va_arg area: if so, we cannot
266 if (CallPassesValueThoughVararg(CS.getInstruction(), &A))
267 return Live; // If passed through va_arg area, we cannot remove it
270 return MaybeLive; // It must be used, but only as argument to a function
274 // SurveyFunction - This performs the initial survey of the specified function,
275 // checking out whether or not it uses any of its incoming arguments or whether
276 // any callers use the return value. This fills in the
277 // (Dead|MaybeLive|Live)(Arguments|RetVal) sets.
279 // We consider arguments of non-internal functions to be intrinsically alive as
280 // well as arguments to functions which have their "address taken".
282 void DAE::SurveyFunction(Function &F) {
283 bool FunctionIntrinsicallyLive = false;
284 Liveness RetValLiveness = F.getReturnType() == Type::VoidTy ? Live : Dead;
286 if (!F.hasInternalLinkage() &&
287 (!ShouldHackArguments() || F.getIntrinsicID()))
288 FunctionIntrinsicallyLive = true;
290 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
291 // If this use is anything other than a call site, the function is alive.
292 CallSite CS = CallSite::get(*I);
293 Instruction *TheCall = CS.getInstruction();
294 if (!TheCall) { // Not a direct call site?
295 FunctionIntrinsicallyLive = true;
299 // Check to see if the return value is used...
300 if (RetValLiveness != Live)
301 for (Value::use_iterator I = TheCall->use_begin(),
302 E = TheCall->use_end(); I != E; ++I)
303 if (isa<ReturnInst>(cast<Instruction>(*I))) {
304 RetValLiveness = MaybeLive;
305 } else if (isa<CallInst>(cast<Instruction>(*I)) ||
306 isa<InvokeInst>(cast<Instruction>(*I))) {
307 if (CallPassesValueThoughVararg(cast<Instruction>(*I), TheCall) ||
308 !CallSite::get(cast<Instruction>(*I)).getCalledFunction()) {
309 RetValLiveness = Live;
312 RetValLiveness = MaybeLive;
315 RetValLiveness = Live;
319 // If the function is PASSED IN as an argument, its address has been taken
320 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
322 if (AI->get() == &F) {
323 FunctionIntrinsicallyLive = true;
326 if (FunctionIntrinsicallyLive) break;
329 if (FunctionIntrinsicallyLive) {
330 DOUT << " Intrinsically live fn: " << F.getName() << "\n";
331 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
333 LiveArguments.insert(AI);
334 LiveRetVal.insert(&F);
338 switch (RetValLiveness) {
339 case Live: LiveRetVal.insert(&F); break;
340 case MaybeLive: MaybeLiveRetVal.insert(&F); break;
341 case Dead: DeadRetVal.insert(&F); break;
344 DOUT << " Inspecting args for fn: " << F.getName() << "\n";
346 // If it is not intrinsically alive, we know that all users of the
347 // function are call sites. Mark all of the arguments live which are
348 // directly used, and keep track of all of the call sites of this function
349 // if there are any arguments we assume that are dead.
351 bool AnyMaybeLiveArgs = false;
352 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
354 switch (getArgumentLiveness(*AI)) {
356 DOUT << " Arg live by use: " << AI->getName() << "\n";
357 LiveArguments.insert(AI);
360 DOUT << " Arg definitely dead: " << AI->getName() <<"\n";
361 DeadArguments.insert(AI);
364 DOUT << " Arg only passed to calls: " << AI->getName() << "\n";
365 AnyMaybeLiveArgs = true;
366 MaybeLiveArguments.insert(AI);
370 // If there are any "MaybeLive" arguments, we need to check callees of
371 // this function when/if they become alive. Record which functions are
373 if (AnyMaybeLiveArgs || RetValLiveness == MaybeLive)
374 for (Value::use_iterator I = F.use_begin(), E = F.use_end();
376 if (AnyMaybeLiveArgs)
377 CallSites.insert(std::make_pair(&F, CallSite::get(*I)));
379 if (RetValLiveness == MaybeLive)
380 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
382 InstructionsToInspect.push_back(cast<Instruction>(*UI));
386 // isMaybeLiveArgumentNowLive - Check to see if Arg is alive. At this point, we
387 // know that the only uses of Arg are to be passed in as an argument to a
388 // function call or return. Check to see if the formal argument passed in is in
389 // the LiveArguments set. If so, return true.
391 bool DAE::isMaybeLiveArgumentNowLive(Argument *Arg) {
392 for (Value::use_iterator I = Arg->use_begin(), E = Arg->use_end(); I!=E; ++I){
393 if (isa<ReturnInst>(*I)) {
394 if (LiveRetVal.count(Arg->getParent())) return true;
398 CallSite CS = CallSite::get(*I);
400 // We know that this can only be used for direct calls...
401 Function *Callee = CS.getCalledFunction();
403 // Loop over all of the arguments (because Arg may be passed into the call
404 // multiple times) and check to see if any are now alive...
405 CallSite::arg_iterator CSAI = CS.arg_begin();
406 for (Function::arg_iterator AI = Callee->arg_begin(), E = Callee->arg_end();
407 AI != E; ++AI, ++CSAI)
408 // If this is the argument we are looking for, check to see if it's alive
409 if (*CSAI == Arg && LiveArguments.count(AI))
415 /// MarkArgumentLive - The MaybeLive argument 'Arg' is now known to be alive.
416 /// Mark it live in the specified sets and recursively mark arguments in callers
417 /// live that are needed to pass in a value.
419 void DAE::MarkArgumentLive(Argument *Arg) {
420 std::set<Argument*>::iterator It = MaybeLiveArguments.lower_bound(Arg);
421 if (It == MaybeLiveArguments.end() || *It != Arg) return;
423 DOUT << " MaybeLive argument now live: " << Arg->getName() <<"\n";
424 MaybeLiveArguments.erase(It);
425 LiveArguments.insert(Arg);
427 // Loop over all of the call sites of the function, making any arguments
428 // passed in to provide a value for this argument live as necessary.
430 Function *Fn = Arg->getParent();
431 unsigned ArgNo = std::distance(Fn->arg_begin(), Function::arg_iterator(Arg));
433 std::multimap<Function*, CallSite>::iterator I = CallSites.lower_bound(Fn);
434 for (; I != CallSites.end() && I->first == Fn; ++I) {
435 CallSite CS = I->second;
436 Value *ArgVal = *(CS.arg_begin()+ArgNo);
437 if (Argument *ActualArg = dyn_cast<Argument>(ArgVal)) {
438 MarkArgumentLive(ActualArg);
440 // If the value passed in at this call site is a return value computed by
441 // some other call site, make sure to mark the return value at the other
442 // call site as being needed.
443 CallSite ArgCS = CallSite::get(ArgVal);
444 if (ArgCS.getInstruction())
445 if (Function *Fn = ArgCS.getCalledFunction())
451 /// MarkArgumentLive - The MaybeLive return value for the specified function is
452 /// now known to be alive. Propagate this fact to the return instructions which
454 void DAE::MarkRetValLive(Function *F) {
455 assert(F && "Shame shame, we can't have null pointers here!");
457 // Check to see if we already knew it was live
458 std::set<Function*>::iterator I = MaybeLiveRetVal.lower_bound(F);
459 if (I == MaybeLiveRetVal.end() || *I != F) return; // It's already alive!
461 DOUT << " MaybeLive retval now live: " << F->getName() << "\n";
463 MaybeLiveRetVal.erase(I);
464 LiveRetVal.insert(F); // It is now known to be live!
466 // Loop over all of the functions, noticing that the return value is now live.
467 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
468 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
469 MarkReturnInstArgumentLive(RI);
472 void DAE::MarkReturnInstArgumentLive(ReturnInst *RI) {
473 Value *Op = RI->getOperand(0);
474 if (Argument *A = dyn_cast<Argument>(Op)) {
476 } else if (CallInst *CI = dyn_cast<CallInst>(Op)) {
477 if (Function *F = CI->getCalledFunction())
479 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
480 if (Function *F = II->getCalledFunction())
485 // RemoveDeadArgumentsFromFunction - We know that F has dead arguments, as
486 // specified by the DeadArguments list. Transform the function and all of the
487 // callees of the function to not have these arguments.
489 void DAE::RemoveDeadArgumentsFromFunction(Function *F) {
490 // Start by computing a new prototype for the function, which is the same as
491 // the old function, but has fewer arguments.
492 const FunctionType *FTy = F->getFunctionType();
493 std::vector<const Type*> Params;
495 // Set up to build a new list of parameter attributes
496 ParamAttrsVector ParamAttrsVec;
497 const ParamAttrsList *PAL = F->getParamAttrs();
499 // Construct the new parameter list from non-dead arguments. Also construct
500 // a new set of parameter attributes to correspond.
502 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
504 if (!DeadArguments.count(I)) {
505 Params.push_back(I->getType());
507 uint16_t Attrs = PAL->getParamAttrs(index);
508 if (Attrs != ParamAttr::None)
509 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(),
514 // Reconstruct the ParamAttrsList based on the vector we constructed.
515 if (ParamAttrsVec.empty())
518 PAL = ParamAttrsList::get(ParamAttrsVec);
520 // Make the function return void if the return value is dead.
521 const Type *RetTy = FTy->getReturnType();
522 if (DeadRetVal.count(F)) {
523 RetTy = Type::VoidTy;
527 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
528 // have zero fixed arguments.
530 bool ExtraArgHack = false;
531 if (Params.empty() && FTy->isVarArg()) {
533 Params.push_back(Type::Int32Ty);
536 // Create the new function type based on the recomputed parameters.
537 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
539 // Create the new function body and insert it into the module...
540 Function *NF = new Function(NFTy, F->getLinkage());
541 NF->setCallingConv(F->getCallingConv());
542 NF->setParamAttrs(PAL);
543 F->getParent()->getFunctionList().insert(F, NF);
546 // Loop over all of the callers of the function, transforming the call sites
547 // to pass in a smaller number of arguments into the new function.
549 std::vector<Value*> Args;
550 while (!F->use_empty()) {
551 CallSite CS = CallSite::get(F->use_back());
552 Instruction *Call = CS.getInstruction();
554 // Loop over the operands, deleting dead ones...
555 CallSite::arg_iterator AI = CS.arg_begin();
556 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
558 if (!DeadArguments.count(I)) // Remove operands for dead arguments
562 Args.push_back(UndefValue::get(Type::Int32Ty));
564 // Push any varargs arguments on the list
565 for (; AI != CS.arg_end(); ++AI)
569 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
570 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
571 Args.begin(), Args.end(), "", Call);
572 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
573 cast<InvokeInst>(New)->setParamAttrs(PAL);
575 New = new CallInst(NF, Args.begin(), Args.end(), "", Call);
576 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
577 cast<CallInst>(New)->setParamAttrs(PAL);
578 if (cast<CallInst>(Call)->isTailCall())
579 cast<CallInst>(New)->setTailCall();
583 if (!Call->use_empty()) {
584 if (New->getType() == Type::VoidTy)
585 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
587 Call->replaceAllUsesWith(New);
592 // Finally, remove the old call from the program, reducing the use-count of
594 Call->getParent()->getInstList().erase(Call);
597 // Since we have now created the new function, splice the body of the old
598 // function right into the new function, leaving the old rotting hulk of the
600 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
602 // Loop over the argument list, transfering uses of the old arguments over to
603 // the new arguments, also transfering over the names as well. While we're at
604 // it, remove the dead arguments from the DeadArguments list.
606 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
607 I2 = NF->arg_begin();
609 if (!DeadArguments.count(I)) {
610 // If this is a live argument, move the name and users over to the new
612 I->replaceAllUsesWith(I2);
616 // If this argument is dead, replace any uses of it with null constants
617 // (these are guaranteed to only be operands to call instructions which
618 // will later be simplified).
619 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
620 DeadArguments.erase(I);
623 // If we change the return value of the function we must rewrite any return
624 // instructions. Check this now.
625 if (F->getReturnType() != NF->getReturnType())
626 for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
627 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
628 new ReturnInst(0, RI);
629 BB->getInstList().erase(RI);
632 // Now that the old function is dead, delete it.
633 F->getParent()->getFunctionList().erase(F);
636 bool DAE::runOnModule(Module &M) {
637 bool Changed = false;
638 // First pass: Do a simple check to see if any functions can have their "..."
639 // removed. We can do this if they never call va_start. This loop cannot be
640 // fused with the next loop, because deleting a function invalidates
641 // information computed while surveying other functions.
642 DOUT << "DAE - Deleting dead varargs\n";
643 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
645 if (F.getFunctionType()->isVarArg())
646 Changed |= DeleteDeadVarargs(F);
649 // Second phase:loop through the module, determining which arguments are live.
650 // We assume all arguments are dead unless proven otherwise (allowing us to
651 // determine that dead arguments passed into recursive functions are dead).
653 DOUT << "DAE - Determining liveness\n";
654 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
657 // Loop over the instructions to inspect, propagating liveness among arguments
658 // and return values which are MaybeLive.
659 while (!InstructionsToInspect.empty()) {
660 Instruction *I = InstructionsToInspect.back();
661 InstructionsToInspect.pop_back();
663 if (ReturnInst *RI = dyn_cast<ReturnInst>(I)) {
664 // For return instructions, we just have to check to see if the return
665 // value for the current function is known now to be alive. If so, any
666 // arguments used by it are now alive, and any call instruction return
667 // value is alive as well.
668 if (LiveRetVal.count(RI->getParent()->getParent()))
669 MarkReturnInstArgumentLive(RI);
672 CallSite CS = CallSite::get(I);
673 assert(CS.getInstruction() && "Unknown instruction for the I2I list!");
675 Function *Callee = CS.getCalledFunction();
677 // If we found a call or invoke instruction on this list, that means that
678 // an argument of the function is a call instruction. If the argument is
679 // live, then the return value of the called instruction is now live.
681 CallSite::arg_iterator AI = CS.arg_begin(); // ActualIterator
682 for (Function::arg_iterator FI = Callee->arg_begin(),
683 E = Callee->arg_end(); FI != E; ++AI, ++FI) {
684 // If this argument is another call...
685 CallSite ArgCS = CallSite::get(*AI);
686 if (ArgCS.getInstruction() && LiveArguments.count(FI))
687 if (Function *Callee = ArgCS.getCalledFunction())
688 MarkRetValLive(Callee);
693 // Now we loop over all of the MaybeLive arguments, promoting them to be live
694 // arguments if one of the calls that uses the arguments to the calls they are
695 // passed into requires them to be live. Of course this could make other
696 // arguments live, so process callers recursively.
698 // Because elements can be removed from the MaybeLiveArguments set, copy it to
699 // a temporary vector.
701 std::vector<Argument*> TmpArgList(MaybeLiveArguments.begin(),
702 MaybeLiveArguments.end());
703 for (unsigned i = 0, e = TmpArgList.size(); i != e; ++i) {
704 Argument *MLA = TmpArgList[i];
705 if (MaybeLiveArguments.count(MLA) &&
706 isMaybeLiveArgumentNowLive(MLA))
707 MarkArgumentLive(MLA);
710 // Recover memory early...
713 // At this point, we know that all arguments in DeadArguments and
714 // MaybeLiveArguments are dead. If the two sets are empty, there is nothing
716 if (MaybeLiveArguments.empty() && DeadArguments.empty() &&
717 MaybeLiveRetVal.empty() && DeadRetVal.empty())
720 // Otherwise, compact into one set, and start eliminating the arguments from
722 DeadArguments.insert(MaybeLiveArguments.begin(), MaybeLiveArguments.end());
723 MaybeLiveArguments.clear();
724 DeadRetVal.insert(MaybeLiveRetVal.begin(), MaybeLiveRetVal.end());
725 MaybeLiveRetVal.clear();
727 LiveArguments.clear();
730 NumArgumentsEliminated += DeadArguments.size();
731 NumRetValsEliminated += DeadRetVal.size();
732 while (!DeadArguments.empty())
733 RemoveDeadArgumentsFromFunction((*DeadArguments.begin())->getParent());
735 while (!DeadRetVal.empty())
736 RemoveDeadArgumentsFromFunction(*DeadRetVal.begin());