blob: 10f2a37429416fe6eab4de98971ce6a572e82050 [file] [log] [blame]
Chris Lattner13bf28c2003-06-17 22:21:05 +00001//===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// 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.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner13bf28c2003-06-17 22:21:05 +00009//
10// This pass deletes dead arguments from internal functions. Dead argument
11// elimination removes arguments which are directly dead, as well as arguments
Chris Lattner0658cc22003-10-23 03:48:17 +000012// only passed into function calls as dead arguments of other functions. This
13// pass also deletes dead arguments in a similar way.
Chris Lattner13bf28c2003-06-17 22:21:05 +000014//
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
Chris Lattner9610c6f2005-06-24 16:00:46 +000020#define DEBUG_TYPE "deadargelim"
Chris Lattner13bf28c2003-06-17 22:21:05 +000021#include "llvm/Transforms/IPO.h"
22#include "llvm/Module.h"
23#include "llvm/Pass.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Constant.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000026#include "llvm/Instructions.h"
Chris Lattner13bf28c2003-06-17 22:21:05 +000027#include "llvm/Support/CallSite.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000028#include "llvm/Support/Debug.h"
29#include "llvm/ADT/Statistic.h"
30#include "llvm/ADT/iterator"
Chris Lattner13bf28c2003-06-17 22:21:05 +000031#include <set>
Chris Lattnerf52e03c2003-11-21 21:54:22 +000032using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000033
Chris Lattner13bf28c2003-06-17 22:21:05 +000034namespace {
Chris Lattner0658cc22003-10-23 03:48:17 +000035 Statistic<> NumArgumentsEliminated("deadargelim",
36 "Number of unread args removed");
37 Statistic<> NumRetValsEliminated("deadargelim",
38 "Number of unused return values removed");
Chris Lattner13bf28c2003-06-17 22:21:05 +000039
Chris Lattner0658cc22003-10-23 03:48:17 +000040 /// DAE - The dead argument elimination pass.
41 ///
Chris Lattner4f2cf032004-09-20 04:48:05 +000042 class DAE : public ModulePass {
Chris Lattner0658cc22003-10-23 03:48:17 +000043 /// Liveness enum - During our initial pass over the program, we determine
44 /// that things are either definately alive, definately dead, or in need of
45 /// interprocedural analysis (MaybeLive).
46 ///
47 enum Liveness { Live, MaybeLive, Dead };
48
49 /// LiveArguments, MaybeLiveArguments, DeadArguments - These sets contain
50 /// all of the arguments in the program. The Dead set contains arguments
51 /// which are completely dead (never used in the function). The MaybeLive
52 /// set contains arguments which are only passed into other function calls,
53 /// thus may be live and may be dead. The Live set contains arguments which
54 /// are known to be alive.
55 ///
56 std::set<Argument*> DeadArguments, MaybeLiveArguments, LiveArguments;
57
58 /// DeadRetVal, MaybeLiveRetVal, LifeRetVal - These sets contain all of the
59 /// functions in the program. The Dead set contains functions whose return
60 /// value is known to be dead. The MaybeLive set contains functions whose
61 /// return values are only used by return instructions, and the Live set
62 /// contains functions whose return values are used, functions that are
63 /// external, and functions that already return void.
64 ///
65 std::set<Function*> DeadRetVal, MaybeLiveRetVal, LiveRetVal;
66
67 /// InstructionsToInspect - As we mark arguments and return values
68 /// MaybeLive, we keep track of which instructions could make the values
69 /// live here. Once the entire program has had the return value and
70 /// arguments analyzed, this set is scanned to promote the MaybeLive objects
71 /// to be Live if they really are used.
72 std::vector<Instruction*> InstructionsToInspect;
73
74 /// CallSites - Keep track of the call sites of functions that have
75 /// MaybeLive arguments or return values.
76 std::multimap<Function*, CallSite> CallSites;
77
78 public:
Chris Lattner4f2cf032004-09-20 04:48:05 +000079 bool runOnModule(Module &M);
Chris Lattner2ab04f72003-06-25 04:12:49 +000080
Chris Lattner9e60ace2003-11-05 21:43:02 +000081 virtual bool ShouldHackArguments() const { return false; }
82
Chris Lattner2ab04f72003-06-25 04:12:49 +000083 private:
Chris Lattner0658cc22003-10-23 03:48:17 +000084 Liveness getArgumentLiveness(const Argument &A);
85 bool isMaybeLiveArgumentNowLive(Argument *Arg);
86
87 void SurveyFunction(Function &Fn);
88
89 void MarkArgumentLive(Argument *Arg);
90 void MarkRetValLive(Function *F);
91 void MarkReturnInstArgumentLive(ReturnInst *RI);
Misha Brukmanb1c93172005-04-21 23:48:37 +000092
Chris Lattner0658cc22003-10-23 03:48:17 +000093 void RemoveDeadArgumentsFromFunction(Function *F);
Chris Lattner13bf28c2003-06-17 22:21:05 +000094 };
95 RegisterOpt<DAE> X("deadargelim", "Dead Argument Elimination");
Chris Lattner9e60ace2003-11-05 21:43:02 +000096
97 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
98 /// deletes arguments to functions which are external. This is only for use
99 /// by bugpoint.
100 struct DAH : public DAE {
101 virtual bool ShouldHackArguments() const { return true; }
102 };
Chris Lattner4e1b4672003-11-05 21:53:41 +0000103 RegisterPass<DAH> Y("deadarghaX0r",
Brian Gaeke6204e752004-02-02 19:32:27 +0000104 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)");
Chris Lattner13bf28c2003-06-17 22:21:05 +0000105}
106
Chris Lattner2ab04f72003-06-25 04:12:49 +0000107/// createDeadArgEliminationPass - This pass removes arguments from functions
Chris Lattner9e60ace2003-11-05 21:43:02 +0000108/// which are not used by the body of the function.
Chris Lattner2ab04f72003-06-25 04:12:49 +0000109///
Chris Lattner4f2cf032004-09-20 04:48:05 +0000110ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
111ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
Chris Lattner13bf28c2003-06-17 22:21:05 +0000112
Chris Lattner0658cc22003-10-23 03:48:17 +0000113static inline bool CallPassesValueThoughVararg(Instruction *Call,
114 const Value *Arg) {
115 CallSite CS = CallSite::get(Call);
116 const Type *CalledValueTy = CS.getCalledValue()->getType();
117 const Type *FTy = cast<PointerType>(CalledValueTy)->getElementType();
118 unsigned NumFixedArgs = cast<FunctionType>(FTy)->getNumParams();
119 for (CallSite::arg_iterator AI = CS.arg_begin()+NumFixedArgs;
120 AI != CS.arg_end(); ++AI)
121 if (AI->get() == Arg)
122 return true;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000123 return false;
124}
125
Chris Lattner0658cc22003-10-23 03:48:17 +0000126// getArgumentLiveness - Inspect an argument, determining if is known Live
Chris Lattner13bf28c2003-06-17 22:21:05 +0000127// (used in a computation), MaybeLive (only passed as an argument to a call), or
128// Dead (not used).
Chris Lattner0658cc22003-10-23 03:48:17 +0000129DAE::Liveness DAE::getArgumentLiveness(const Argument &A) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000130 if (A.use_empty()) return Dead; // First check, directly dead?
131
132 // Scan through all of the uses, looking for non-argument passing uses.
133 for (Value::use_const_iterator I = A.use_begin(), E = A.use_end(); I!=E;++I) {
Chris Lattner0658cc22003-10-23 03:48:17 +0000134 // Return instructions do not immediately effect liveness.
135 if (isa<ReturnInst>(*I))
136 continue;
137
Chris Lattner13bf28c2003-06-17 22:21:05 +0000138 CallSite CS = CallSite::get(const_cast<User*>(*I));
139 if (!CS.getInstruction()) {
140 // If its used by something that is not a call or invoke, it's alive!
Chris Lattner0658cc22003-10-23 03:48:17 +0000141 return Live;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000142 }
143 // If it's an indirect call, mark it alive...
144 Function *Callee = CS.getCalledFunction();
Chris Lattner0658cc22003-10-23 03:48:17 +0000145 if (!Callee) return Live;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000146
Chris Lattner5d3c1452003-06-18 16:25:51 +0000147 // Check to see if it's passed through a va_arg area: if so, we cannot
148 // remove it.
Chris Lattner0658cc22003-10-23 03:48:17 +0000149 if (CallPassesValueThoughVararg(CS.getInstruction(), &A))
150 return Live; // If passed through va_arg area, we cannot remove it
Chris Lattner13bf28c2003-06-17 22:21:05 +0000151 }
152
153 return MaybeLive; // It must be used, but only as argument to a function
154}
155
Chris Lattner0658cc22003-10-23 03:48:17 +0000156
157// SurveyFunction - This performs the initial survey of the specified function,
158// checking out whether or not it uses any of its incoming arguments or whether
159// any callers use the return value. This fills in the
160// (Dead|MaybeLive|Live)(Arguments|RetVal) sets.
Chris Lattner13bf28c2003-06-17 22:21:05 +0000161//
Chris Lattner0658cc22003-10-23 03:48:17 +0000162// We consider arguments of non-internal functions to be intrinsically alive as
163// well as arguments to functions which have their "address taken".
164//
165void DAE::SurveyFunction(Function &F) {
166 bool FunctionIntrinsicallyLive = false;
167 Liveness RetValLiveness = F.getReturnType() == Type::VoidTy ? Live : Dead;
168
Chris Lattner4e1b4672003-11-05 21:53:41 +0000169 if (!F.hasInternalLinkage() &&
170 (!ShouldHackArguments() || F.getIntrinsicID()))
Chris Lattner0658cc22003-10-23 03:48:17 +0000171 FunctionIntrinsicallyLive = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000172 else
Chris Lattner0658cc22003-10-23 03:48:17 +0000173 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
174 // If this use is anything other than a call site, the function is alive.
175 CallSite CS = CallSite::get(*I);
176 Instruction *TheCall = CS.getInstruction();
177 if (!TheCall) { // Not a direct call site?
178 FunctionIntrinsicallyLive = true;
179 break;
180 }
181
182 // Check to see if the return value is used...
183 if (RetValLiveness != Live)
184 for (Value::use_iterator I = TheCall->use_begin(),
185 E = TheCall->use_end(); I != E; ++I)
186 if (isa<ReturnInst>(cast<Instruction>(*I))) {
187 RetValLiveness = MaybeLive;
188 } else if (isa<CallInst>(cast<Instruction>(*I)) ||
189 isa<InvokeInst>(cast<Instruction>(*I))) {
190 if (CallPassesValueThoughVararg(cast<Instruction>(*I), TheCall) ||
191 !CallSite::get(cast<Instruction>(*I)).getCalledFunction()) {
192 RetValLiveness = Live;
193 break;
194 } else {
195 RetValLiveness = MaybeLive;
196 }
197 } else {
198 RetValLiveness = Live;
199 break;
200 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000201
Chris Lattner0658cc22003-10-23 03:48:17 +0000202 // If the function is PASSED IN as an argument, its address has been taken
203 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
204 AI != E; ++AI)
205 if (AI->get() == &F) {
206 FunctionIntrinsicallyLive = true;
207 break;
208 }
209 if (FunctionIntrinsicallyLive) break;
210 }
211
212 if (FunctionIntrinsicallyLive) {
213 DEBUG(std::cerr << " Intrinsically live fn: " << F.getName() << "\n");
Chris Lattner53db5462005-05-06 05:34:40 +0000214 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
215 AI != E; ++AI)
Chris Lattner0658cc22003-10-23 03:48:17 +0000216 LiveArguments.insert(AI);
217 LiveRetVal.insert(&F);
218 return;
219 }
220
221 switch (RetValLiveness) {
222 case Live: LiveRetVal.insert(&F); break;
223 case MaybeLive: MaybeLiveRetVal.insert(&F); break;
224 case Dead: DeadRetVal.insert(&F); break;
225 }
226
227 DEBUG(std::cerr << " Inspecting args for fn: " << F.getName() << "\n");
228
229 // If it is not intrinsically alive, we know that all users of the
230 // function are call sites. Mark all of the arguments live which are
231 // directly used, and keep track of all of the call sites of this function
232 // if there are any arguments we assume that are dead.
233 //
234 bool AnyMaybeLiveArgs = false;
Chris Lattner53db5462005-05-06 05:34:40 +0000235 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
236 AI != E; ++AI)
Chris Lattner0658cc22003-10-23 03:48:17 +0000237 switch (getArgumentLiveness(*AI)) {
238 case Live:
239 DEBUG(std::cerr << " Arg live by use: " << AI->getName() << "\n");
240 LiveArguments.insert(AI);
241 break;
242 case Dead:
243 DEBUG(std::cerr << " Arg definitely dead: " <<AI->getName()<<"\n");
244 DeadArguments.insert(AI);
245 break;
246 case MaybeLive:
247 DEBUG(std::cerr << " Arg only passed to calls: "
248 << AI->getName() << "\n");
249 AnyMaybeLiveArgs = true;
250 MaybeLiveArguments.insert(AI);
251 break;
252 }
253
254 // If there are any "MaybeLive" arguments, we need to check callees of
255 // this function when/if they become alive. Record which functions are
256 // callees...
257 if (AnyMaybeLiveArgs || RetValLiveness == MaybeLive)
258 for (Value::use_iterator I = F.use_begin(), E = F.use_end();
259 I != E; ++I) {
260 if (AnyMaybeLiveArgs)
261 CallSites.insert(std::make_pair(&F, CallSite::get(*I)));
262
263 if (RetValLiveness == MaybeLive)
264 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
265 UI != E; ++UI)
266 InstructionsToInspect.push_back(cast<Instruction>(*UI));
267 }
268}
269
270// isMaybeLiveArgumentNowLive - Check to see if Arg is alive. At this point, we
271// know that the only uses of Arg are to be passed in as an argument to a
272// function call or return. Check to see if the formal argument passed in is in
273// the LiveArguments set. If so, return true.
274//
275bool DAE::isMaybeLiveArgumentNowLive(Argument *Arg) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000276 for (Value::use_iterator I = Arg->use_begin(), E = Arg->use_end(); I!=E; ++I){
Chris Lattner0658cc22003-10-23 03:48:17 +0000277 if (isa<ReturnInst>(*I)) {
278 if (LiveRetVal.count(Arg->getParent())) return true;
279 continue;
280 }
281
Chris Lattner13bf28c2003-06-17 22:21:05 +0000282 CallSite CS = CallSite::get(*I);
283
284 // We know that this can only be used for direct calls...
Chris Lattner7f7285b2003-11-02 02:06:27 +0000285 Function *Callee = CS.getCalledFunction();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000286
287 // Loop over all of the arguments (because Arg may be passed into the call
288 // multiple times) and check to see if any are now alive...
289 CallSite::arg_iterator CSAI = CS.arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +0000290 for (Function::arg_iterator AI = Callee->arg_begin(), E = Callee->arg_end();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000291 AI != E; ++AI, ++CSAI)
292 // If this is the argument we are looking for, check to see if it's alive
293 if (*CSAI == Arg && LiveArguments.count(AI))
294 return true;
295 }
296 return false;
297}
298
Chris Lattner0658cc22003-10-23 03:48:17 +0000299/// MarkArgumentLive - The MaybeLive argument 'Arg' is now known to be alive.
300/// Mark it live in the specified sets and recursively mark arguments in callers
301/// live that are needed to pass in a value.
302///
303void DAE::MarkArgumentLive(Argument *Arg) {
304 std::set<Argument*>::iterator It = MaybeLiveArguments.lower_bound(Arg);
305 if (It == MaybeLiveArguments.end() || *It != Arg) return;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000306
Chris Lattner13bf28c2003-06-17 22:21:05 +0000307 DEBUG(std::cerr << " MaybeLive argument now live: " << Arg->getName()<<"\n");
Chris Lattner0658cc22003-10-23 03:48:17 +0000308 MaybeLiveArguments.erase(It);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000309 LiveArguments.insert(Arg);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000310
Chris Lattner13bf28c2003-06-17 22:21:05 +0000311 // Loop over all of the call sites of the function, making any arguments
312 // passed in to provide a value for this argument live as necessary.
313 //
314 Function *Fn = Arg->getParent();
Chris Lattner531f9e92005-03-15 04:54:21 +0000315 unsigned ArgNo = std::distance(Fn->arg_begin(), Function::arg_iterator(Arg));
Chris Lattner13bf28c2003-06-17 22:21:05 +0000316
Chris Lattner0658cc22003-10-23 03:48:17 +0000317 std::multimap<Function*, CallSite>::iterator I = CallSites.lower_bound(Fn);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000318 for (; I != CallSites.end() && I->first == Fn; ++I) {
Chris Lattner0658cc22003-10-23 03:48:17 +0000319 CallSite CS = I->second;
320 Value *ArgVal = *(CS.arg_begin()+ArgNo);
321 if (Argument *ActualArg = dyn_cast<Argument>(ArgVal)) {
322 MarkArgumentLive(ActualArg);
323 } else {
324 // If the value passed in at this call site is a return value computed by
325 // some other call site, make sure to mark the return value at the other
326 // call site as being needed.
327 CallSite ArgCS = CallSite::get(ArgVal);
328 if (ArgCS.getInstruction())
329 if (Function *Fn = ArgCS.getCalledFunction())
330 MarkRetValLive(Fn);
331 }
332 }
333}
334
335/// MarkArgumentLive - The MaybeLive return value for the specified function is
336/// now known to be alive. Propagate this fact to the return instructions which
337/// produce it.
338void DAE::MarkRetValLive(Function *F) {
339 assert(F && "Shame shame, we can't have null pointers here!");
340
341 // Check to see if we already knew it was live
342 std::set<Function*>::iterator I = MaybeLiveRetVal.lower_bound(F);
343 if (I == MaybeLiveRetVal.end() || *I != F) return; // It's already alive!
344
345 DEBUG(std::cerr << " MaybeLive retval now live: " << F->getName() << "\n");
346
347 MaybeLiveRetVal.erase(I);
348 LiveRetVal.insert(F); // It is now known to be live!
349
350 // Loop over all of the functions, noticing that the return value is now live.
351 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
352 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
353 MarkReturnInstArgumentLive(RI);
354}
355
356void DAE::MarkReturnInstArgumentLive(ReturnInst *RI) {
357 Value *Op = RI->getOperand(0);
358 if (Argument *A = dyn_cast<Argument>(Op)) {
359 MarkArgumentLive(A);
360 } else if (CallInst *CI = dyn_cast<CallInst>(Op)) {
361 if (Function *F = CI->getCalledFunction())
362 MarkRetValLive(F);
363 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
364 if (Function *F = II->getCalledFunction())
365 MarkRetValLive(F);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000366 }
367}
368
369// RemoveDeadArgumentsFromFunction - We know that F has dead arguments, as
370// specified by the DeadArguments list. Transform the function and all of the
371// callees of the function to not have these arguments.
372//
Chris Lattner0658cc22003-10-23 03:48:17 +0000373void DAE::RemoveDeadArgumentsFromFunction(Function *F) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000374 // Start by computing a new prototype for the function, which is the same as
375 // the old function, but has fewer arguments.
376 const FunctionType *FTy = F->getFunctionType();
377 std::vector<const Type*> Params;
378
Chris Lattner531f9e92005-03-15 04:54:21 +0000379 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattner13bf28c2003-06-17 22:21:05 +0000380 if (!DeadArguments.count(I))
381 Params.push_back(I->getType());
382
Chris Lattner0658cc22003-10-23 03:48:17 +0000383 const Type *RetTy = FTy->getReturnType();
384 if (DeadRetVal.count(F)) {
385 RetTy = Type::VoidTy;
386 DeadRetVal.erase(F);
387 }
388
Chris Lattner05c71fb2003-10-23 17:44:53 +0000389 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
390 // have zero fixed arguments.
391 //
392 // FIXME: once this bug is fixed in the CWriter, this hack should be removed.
393 //
394 bool ExtraArgHack = false;
395 if (Params.empty() && FTy->isVarArg()) {
396 ExtraArgHack = true;
397 Params.push_back(Type::IntTy);
398 }
399
Chris Lattner0658cc22003-10-23 03:48:17 +0000400 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
401
Chris Lattner13bf28c2003-06-17 22:21:05 +0000402 // Create the new function body and insert it into the module...
Chris Lattner2ab04f72003-06-25 04:12:49 +0000403 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
Chris Lattnerd0525a22005-05-09 01:05:50 +0000404 NF->setCallingConv(F->getCallingConv());
Chris Lattner13bf28c2003-06-17 22:21:05 +0000405 F->getParent()->getFunctionList().insert(F, NF);
406
407 // Loop over all of the callers of the function, transforming the call sites
408 // to pass in a smaller number of arguments into the new function.
409 //
Chris Lattner0658cc22003-10-23 03:48:17 +0000410 std::vector<Value*> Args;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000411 while (!F->use_empty()) {
412 CallSite CS = CallSite::get(F->use_back());
413 Instruction *Call = CS.getInstruction();
Chris Lattner0658cc22003-10-23 03:48:17 +0000414
Chris Lattner13bf28c2003-06-17 22:21:05 +0000415 // Loop over the operands, deleting dead ones...
416 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattner53db5462005-05-06 05:34:40 +0000417 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
418 I != E; ++I, ++AI)
Chris Lattner0658cc22003-10-23 03:48:17 +0000419 if (!DeadArguments.count(I)) // Remove operands for dead arguments
420 Args.push_back(*AI);
421
Chris Lattner05c71fb2003-10-23 17:44:53 +0000422 if (ExtraArgHack)
423 Args.push_back(Constant::getNullValue(Type::IntTy));
424
425 // Push any varargs arguments on the list
426 for (; AI != CS.arg_end(); ++AI)
427 Args.push_back(*AI);
428
Chris Lattner0658cc22003-10-23 03:48:17 +0000429 Instruction *New;
430 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +0000431 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner0658cc22003-10-23 03:48:17 +0000432 Args, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000433 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner0658cc22003-10-23 03:48:17 +0000434 } else {
435 New = new CallInst(NF, Args, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000436 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner324d2ee2005-05-06 06:46:58 +0000437 if (cast<CallInst>(Call)->isTailCall())
438 cast<CallInst>(New)->setTailCall();
Chris Lattner0658cc22003-10-23 03:48:17 +0000439 }
440 Args.clear();
441
442 if (!Call->use_empty()) {
443 if (New->getType() == Type::VoidTy)
444 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
445 else {
446 Call->replaceAllUsesWith(New);
447 std::string Name = Call->getName();
448 Call->setName("");
449 New->setName(Name);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000450 }
Chris Lattner0658cc22003-10-23 03:48:17 +0000451 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000452
Chris Lattner0658cc22003-10-23 03:48:17 +0000453 // Finally, remove the old call from the program, reducing the use-count of
454 // F.
455 Call->getParent()->getInstList().erase(Call);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000456 }
457
458 // Since we have now created the new function, splice the body of the old
459 // function right into the new function, leaving the old rotting hulk of the
460 // function empty.
461 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
462
463 // Loop over the argument list, transfering uses of the old arguments over to
464 // the new arguments, also transfering over the names as well. While we're at
465 // it, remove the dead arguments from the DeadArguments list.
466 //
Chris Lattner53db5462005-05-06 05:34:40 +0000467 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
468 I2 = NF->arg_begin();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000469 I != E; ++I)
470 if (!DeadArguments.count(I)) {
471 // If this is a live argument, move the name and users over to the new
472 // version.
473 I->replaceAllUsesWith(I2);
474 I2->setName(I->getName());
475 ++I2;
476 } else {
477 // If this argument is dead, replace any uses of it with null constants
478 // (these are guaranteed to only be operands to call instructions which
479 // will later be simplified).
480 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
481 DeadArguments.erase(I);
482 }
483
Chris Lattner0658cc22003-10-23 03:48:17 +0000484 // If we change the return value of the function we must rewrite any return
485 // instructions. Check this now.
486 if (F->getReturnType() != NF->getReturnType())
487 for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
488 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
489 new ReturnInst(0, RI);
490 BB->getInstList().erase(RI);
491 }
492
Chris Lattner13bf28c2003-06-17 22:21:05 +0000493 // Now that the old function is dead, delete it.
494 F->getParent()->getFunctionList().erase(F);
495}
496
Chris Lattner4f2cf032004-09-20 04:48:05 +0000497bool DAE::runOnModule(Module &M) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000498 // First phase: loop through the module, determining which arguments are live.
499 // We assume all arguments are dead unless proven otherwise (allowing us to
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000500 // determine that dead arguments passed into recursive functions are dead).
Chris Lattner13bf28c2003-06-17 22:21:05 +0000501 //
Chris Lattner13bf28c2003-06-17 22:21:05 +0000502 DEBUG(std::cerr << "DAE - Determining liveness\n");
Chris Lattner0658cc22003-10-23 03:48:17 +0000503 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
504 SurveyFunction(*I);
505
506 // Loop over the instructions to inspect, propagating liveness among arguments
507 // and return values which are MaybeLive.
508
509 while (!InstructionsToInspect.empty()) {
510 Instruction *I = InstructionsToInspect.back();
511 InstructionsToInspect.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000512
Chris Lattner0658cc22003-10-23 03:48:17 +0000513 if (ReturnInst *RI = dyn_cast<ReturnInst>(I)) {
514 // For return instructions, we just have to check to see if the return
515 // value for the current function is known now to be alive. If so, any
516 // arguments used by it are now alive, and any call instruction return
517 // value is alive as well.
518 if (LiveRetVal.count(RI->getParent()->getParent()))
519 MarkReturnInstArgumentLive(RI);
520
Chris Lattner13bf28c2003-06-17 22:21:05 +0000521 } else {
Chris Lattner0658cc22003-10-23 03:48:17 +0000522 CallSite CS = CallSite::get(I);
523 assert(CS.getInstruction() && "Unknown instruction for the I2I list!");
Chris Lattner13bf28c2003-06-17 22:21:05 +0000524
Chris Lattner0658cc22003-10-23 03:48:17 +0000525 Function *Callee = CS.getCalledFunction();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000526
Chris Lattner0658cc22003-10-23 03:48:17 +0000527 // If we found a call or invoke instruction on this list, that means that
528 // an argument of the function is a call instruction. If the argument is
529 // live, then the return value of the called instruction is now live.
Chris Lattner13bf28c2003-06-17 22:21:05 +0000530 //
Chris Lattner0658cc22003-10-23 03:48:17 +0000531 CallSite::arg_iterator AI = CS.arg_begin(); // ActualIterator
Chris Lattner53db5462005-05-06 05:34:40 +0000532 for (Function::arg_iterator FI = Callee->arg_begin(),
533 E = Callee->arg_end(); FI != E; ++AI, ++FI) {
Chris Lattner0658cc22003-10-23 03:48:17 +0000534 // If this argument is another call...
535 CallSite ArgCS = CallSite::get(*AI);
536 if (ArgCS.getInstruction() && LiveArguments.count(FI))
537 if (Function *Callee = ArgCS.getCalledFunction())
538 MarkRetValLive(Callee);
539 }
Chris Lattner13bf28c2003-06-17 22:21:05 +0000540 }
541 }
542
543 // Now we loop over all of the MaybeLive arguments, promoting them to be live
544 // arguments if one of the calls that uses the arguments to the calls they are
545 // passed into requires them to be live. Of course this could make other
546 // arguments live, so process callers recursively.
547 //
Chris Lattner0658cc22003-10-23 03:48:17 +0000548 // Because elements can be removed from the MaybeLiveArguments set, copy it to
549 // a temporary vector.
Chris Lattner13bf28c2003-06-17 22:21:05 +0000550 //
551 std::vector<Argument*> TmpArgList(MaybeLiveArguments.begin(),
552 MaybeLiveArguments.end());
553 for (unsigned i = 0, e = TmpArgList.size(); i != e; ++i) {
554 Argument *MLA = TmpArgList[i];
555 if (MaybeLiveArguments.count(MLA) &&
Chris Lattner0658cc22003-10-23 03:48:17 +0000556 isMaybeLiveArgumentNowLive(MLA))
557 MarkArgumentLive(MLA);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000558 }
559
560 // Recover memory early...
561 CallSites.clear();
562
563 // At this point, we know that all arguments in DeadArguments and
564 // MaybeLiveArguments are dead. If the two sets are empty, there is nothing
565 // to do.
Chris Lattner0658cc22003-10-23 03:48:17 +0000566 if (MaybeLiveArguments.empty() && DeadArguments.empty() &&
567 MaybeLiveRetVal.empty() && DeadRetVal.empty())
Chris Lattner13bf28c2003-06-17 22:21:05 +0000568 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000569
Chris Lattner13bf28c2003-06-17 22:21:05 +0000570 // Otherwise, compact into one set, and start eliminating the arguments from
571 // the functions.
572 DeadArguments.insert(MaybeLiveArguments.begin(), MaybeLiveArguments.end());
573 MaybeLiveArguments.clear();
Chris Lattner0658cc22003-10-23 03:48:17 +0000574 DeadRetVal.insert(MaybeLiveRetVal.begin(), MaybeLiveRetVal.end());
575 MaybeLiveRetVal.clear();
576
577 LiveArguments.clear();
578 LiveRetVal.clear();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000579
580 NumArgumentsEliminated += DeadArguments.size();
Chris Lattner0658cc22003-10-23 03:48:17 +0000581 NumRetValsEliminated += DeadRetVal.size();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000582 while (!DeadArguments.empty())
Chris Lattner0658cc22003-10-23 03:48:17 +0000583 RemoveDeadArgumentsFromFunction((*DeadArguments.begin())->getParent());
584
585 while (!DeadRetVal.empty())
586 RemoveDeadArgumentsFromFunction(*DeadRetVal.begin());
Chris Lattner13bf28c2003-06-17 22:21:05 +0000587 return true;
588}