blob: f361d5b10b9d64de484ab605c4f002fec9953d21 [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"
Chris Lattnerc4998a02006-06-27 21:05:04 +000022#include "llvm/CallingConv.h"
23#include "llvm/Constant.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Instructions.h"
Chris Lattner67a35bb2006-09-18 07:02:31 +000026#include "llvm/IntrinsicInst.h"
Chris Lattner13bf28c2003-06-17 22:21:05 +000027#include "llvm/Module.h"
28#include "llvm/Pass.h"
Chris Lattner13bf28c2003-06-17 22:21:05 +000029#include "llvm/Support/CallSite.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000030#include "llvm/Support/Debug.h"
31#include "llvm/ADT/Statistic.h"
Chris Lattnerc597b8a2006-01-22 23:32:06 +000032#include <iostream>
Chris Lattner13bf28c2003-06-17 22:21:05 +000033#include <set>
Chris Lattnerf52e03c2003-11-21 21:54:22 +000034using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000035
Chris Lattner13bf28c2003-06-17 22:21:05 +000036namespace {
Chris Lattner0658cc22003-10-23 03:48:17 +000037 Statistic<> NumArgumentsEliminated("deadargelim",
38 "Number of unread args removed");
39 Statistic<> NumRetValsEliminated("deadargelim",
40 "Number of unused return values removed");
Chris Lattner13bf28c2003-06-17 22:21:05 +000041
Chris Lattner0658cc22003-10-23 03:48:17 +000042 /// DAE - The dead argument elimination pass.
43 ///
Chris Lattner4f2cf032004-09-20 04:48:05 +000044 class DAE : public ModulePass {
Chris Lattner0658cc22003-10-23 03:48:17 +000045 /// 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:
Chris Lattner4f2cf032004-09-20 04:48:05 +000081 bool runOnModule(Module &M);
Chris Lattner2ab04f72003-06-25 04:12:49 +000082
Chris Lattner9e60ace2003-11-05 21:43:02 +000083 virtual bool ShouldHackArguments() const { return false; }
84
Chris Lattner2ab04f72003-06-25 04:12:49 +000085 private:
Chris Lattner0658cc22003-10-23 03:48:17 +000086 Liveness getArgumentLiveness(const Argument &A);
87 bool isMaybeLiveArgumentNowLive(Argument *Arg);
88
Chris Lattner67a35bb2006-09-18 07:02:31 +000089 bool DeleteDeadVarargs(Function &Fn);
Chris Lattner0658cc22003-10-23 03:48:17 +000090 void SurveyFunction(Function &Fn);
91
92 void MarkArgumentLive(Argument *Arg);
93 void MarkRetValLive(Function *F);
94 void MarkReturnInstArgumentLive(ReturnInst *RI);
Misha Brukmanb1c93172005-04-21 23:48:37 +000095
Chris Lattner0658cc22003-10-23 03:48:17 +000096 void RemoveDeadArgumentsFromFunction(Function *F);
Chris Lattner13bf28c2003-06-17 22:21:05 +000097 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +000098 RegisterPass<DAE> X("deadargelim", "Dead Argument Elimination");
Chris Lattner9e60ace2003-11-05 21:43:02 +000099
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 };
Chris Lattner4e1b4672003-11-05 21:53:41 +0000106 RegisterPass<DAH> Y("deadarghaX0r",
Brian Gaeke6204e752004-02-02 19:32:27 +0000107 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)");
Chris Lattner13bf28c2003-06-17 22:21:05 +0000108}
109
Chris Lattner2ab04f72003-06-25 04:12:49 +0000110/// createDeadArgEliminationPass - This pass removes arguments from functions
Chris Lattner9e60ace2003-11-05 21:43:02 +0000111/// which are not used by the body of the function.
Chris Lattner2ab04f72003-06-25 04:12:49 +0000112///
Chris Lattner4f2cf032004-09-20 04:48:05 +0000113ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
114ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
Chris Lattner13bf28c2003-06-17 22:21:05 +0000115
Chris Lattner67a35bb2006-09-18 07:02:31 +0000116/// 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.
118bool 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
Chris Lattner0658cc22003-10-23 03:48:17 +0000219static 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;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000229 return false;
230}
231
Chris Lattner0658cc22003-10-23 03:48:17 +0000232// getArgumentLiveness - Inspect an argument, determining if is known Live
Chris Lattner13bf28c2003-06-17 22:21:05 +0000233// (used in a computation), MaybeLive (only passed as an argument to a call), or
234// Dead (not used).
Chris Lattner0658cc22003-10-23 03:48:17 +0000235DAE::Liveness DAE::getArgumentLiveness(const Argument &A) {
Chris Lattnerc4998a02006-06-27 21:05:04 +0000236 // 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;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000243
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) {
Chris Lattner0658cc22003-10-23 03:48:17 +0000246 // Return instructions do not immediately effect liveness.
247 if (isa<ReturnInst>(*I))
248 continue;
249
Chris Lattner13bf28c2003-06-17 22:21:05 +0000250 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!
Chris Lattner0658cc22003-10-23 03:48:17 +0000253 return Live;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000254 }
255 // If it's an indirect call, mark it alive...
256 Function *Callee = CS.getCalledFunction();
Chris Lattner0658cc22003-10-23 03:48:17 +0000257 if (!Callee) return Live;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000258
Chris Lattner5d3c1452003-06-18 16:25:51 +0000259 // Check to see if it's passed through a va_arg area: if so, we cannot
260 // remove it.
Chris Lattner0658cc22003-10-23 03:48:17 +0000261 if (CallPassesValueThoughVararg(CS.getInstruction(), &A))
262 return Live; // If passed through va_arg area, we cannot remove it
Chris Lattner13bf28c2003-06-17 22:21:05 +0000263 }
264
265 return MaybeLive; // It must be used, but only as argument to a function
266}
267
Chris Lattner0658cc22003-10-23 03:48:17 +0000268
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.
Chris Lattner13bf28c2003-06-17 22:21:05 +0000273//
Chris Lattner0658cc22003-10-23 03:48:17 +0000274// We consider arguments of non-internal functions to be intrinsically alive as
275// well as arguments to functions which have their "address taken".
276//
277void DAE::SurveyFunction(Function &F) {
278 bool FunctionIntrinsicallyLive = false;
279 Liveness RetValLiveness = F.getReturnType() == Type::VoidTy ? Live : Dead;
280
Chris Lattner4e1b4672003-11-05 21:53:41 +0000281 if (!F.hasInternalLinkage() &&
282 (!ShouldHackArguments() || F.getIntrinsicID()))
Chris Lattner0658cc22003-10-23 03:48:17 +0000283 FunctionIntrinsicallyLive = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000284 else
Chris Lattner0658cc22003-10-23 03:48:17 +0000285 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 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000313
Chris Lattner0658cc22003-10-23 03:48:17 +0000314 // 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");
Chris Lattner53db5462005-05-06 05:34:40 +0000326 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
327 AI != E; ++AI)
Chris Lattner0658cc22003-10-23 03:48:17 +0000328 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;
Chris Lattner53db5462005-05-06 05:34:40 +0000347 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
348 AI != E; ++AI)
Chris Lattner0658cc22003-10-23 03:48:17 +0000349 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//
387bool DAE::isMaybeLiveArgumentNowLive(Argument *Arg) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000388 for (Value::use_iterator I = Arg->use_begin(), E = Arg->use_end(); I!=E; ++I){
Chris Lattner0658cc22003-10-23 03:48:17 +0000389 if (isa<ReturnInst>(*I)) {
390 if (LiveRetVal.count(Arg->getParent())) return true;
391 continue;
392 }
393
Chris Lattner13bf28c2003-06-17 22:21:05 +0000394 CallSite CS = CallSite::get(*I);
395
396 // We know that this can only be used for direct calls...
Chris Lattner7f7285b2003-11-02 02:06:27 +0000397 Function *Callee = CS.getCalledFunction();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000398
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();
Chris Lattner531f9e92005-03-15 04:54:21 +0000402 for (Function::arg_iterator AI = Callee->arg_begin(), E = Callee->arg_end();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000403 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
Chris Lattner0658cc22003-10-23 03:48:17 +0000411/// 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///
415void DAE::MarkArgumentLive(Argument *Arg) {
416 std::set<Argument*>::iterator It = MaybeLiveArguments.lower_bound(Arg);
417 if (It == MaybeLiveArguments.end() || *It != Arg) return;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000418
Chris Lattner13bf28c2003-06-17 22:21:05 +0000419 DEBUG(std::cerr << " MaybeLive argument now live: " << Arg->getName()<<"\n");
Chris Lattner0658cc22003-10-23 03:48:17 +0000420 MaybeLiveArguments.erase(It);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000421 LiveArguments.insert(Arg);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000422
Chris Lattner13bf28c2003-06-17 22:21:05 +0000423 // 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();
Chris Lattner531f9e92005-03-15 04:54:21 +0000427 unsigned ArgNo = std::distance(Fn->arg_begin(), Function::arg_iterator(Arg));
Chris Lattner13bf28c2003-06-17 22:21:05 +0000428
Chris Lattner0658cc22003-10-23 03:48:17 +0000429 std::multimap<Function*, CallSite>::iterator I = CallSites.lower_bound(Fn);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000430 for (; I != CallSites.end() && I->first == Fn; ++I) {
Chris Lattner0658cc22003-10-23 03:48:17 +0000431 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.
450void 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
468void 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);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000478 }
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//
Chris Lattner0658cc22003-10-23 03:48:17 +0000485void DAE::RemoveDeadArgumentsFromFunction(Function *F) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000486 // 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
Chris Lattner531f9e92005-03-15 04:54:21 +0000491 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattner13bf28c2003-06-17 22:21:05 +0000492 if (!DeadArguments.count(I))
493 Params.push_back(I->getType());
494
Chris Lattner0658cc22003-10-23 03:48:17 +0000495 const Type *RetTy = FTy->getReturnType();
496 if (DeadRetVal.count(F)) {
497 RetTy = Type::VoidTy;
498 DeadRetVal.erase(F);
499 }
500
Chris Lattner05c71fb2003-10-23 17:44:53 +0000501 // 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
Chris Lattner0658cc22003-10-23 03:48:17 +0000512 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
513
Chris Lattner13bf28c2003-06-17 22:21:05 +0000514 // Create the new function body and insert it into the module...
Chris Lattner2ab04f72003-06-25 04:12:49 +0000515 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
Chris Lattnerd0525a22005-05-09 01:05:50 +0000516 NF->setCallingConv(F->getCallingConv());
Chris Lattner13bf28c2003-06-17 22:21:05 +0000517 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 //
Chris Lattner0658cc22003-10-23 03:48:17 +0000522 std::vector<Value*> Args;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000523 while (!F->use_empty()) {
524 CallSite CS = CallSite::get(F->use_back());
525 Instruction *Call = CS.getInstruction();
Chris Lattner0658cc22003-10-23 03:48:17 +0000526
Chris Lattner13bf28c2003-06-17 22:21:05 +0000527 // Loop over the operands, deleting dead ones...
528 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattner53db5462005-05-06 05:34:40 +0000529 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
530 I != E; ++I, ++AI)
Chris Lattner0658cc22003-10-23 03:48:17 +0000531 if (!DeadArguments.count(I)) // Remove operands for dead arguments
532 Args.push_back(*AI);
533
Chris Lattner05c71fb2003-10-23 17:44:53 +0000534 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
Chris Lattner0658cc22003-10-23 03:48:17 +0000541 Instruction *New;
542 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +0000543 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner0658cc22003-10-23 03:48:17 +0000544 Args, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000545 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner0658cc22003-10-23 03:48:17 +0000546 } else {
547 New = new CallInst(NF, Args, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000548 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner324d2ee2005-05-06 06:46:58 +0000549 if (cast<CallInst>(Call)->isTailCall())
550 cast<CallInst>(New)->setTailCall();
Chris Lattner0658cc22003-10-23 03:48:17 +0000551 }
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);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000562 }
Chris Lattner0658cc22003-10-23 03:48:17 +0000563 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000564
Chris Lattner0658cc22003-10-23 03:48:17 +0000565 // Finally, remove the old call from the program, reducing the use-count of
566 // F.
567 Call->getParent()->getInstList().erase(Call);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000568 }
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 //
Chris Lattner53db5462005-05-06 05:34:40 +0000579 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
580 I2 = NF->arg_begin();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000581 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
Chris Lattner0658cc22003-10-23 03:48:17 +0000596 // 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
Chris Lattner13bf28c2003-06-17 22:21:05 +0000605 // Now that the old function is dead, delete it.
606 F->getParent()->getFunctionList().erase(F);
607}
608
Chris Lattner4f2cf032004-09-20 04:48:05 +0000609bool DAE::runOnModule(Module &M) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000610 // First phase: loop through the module, determining which arguments are live.
611 // We assume all arguments are dead unless proven otherwise (allowing us to
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000612 // determine that dead arguments passed into recursive functions are dead).
Chris Lattner13bf28c2003-06-17 22:21:05 +0000613 //
Chris Lattner13bf28c2003-06-17 22:21:05 +0000614 DEBUG(std::cerr << "DAE - Determining liveness\n");
Chris Lattner67a35bb2006-09-18 07:02:31 +0000615 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 }
Chris Lattner0658cc22003-10-23 03:48:17 +0000623
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();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000630
Chris Lattner0658cc22003-10-23 03:48:17 +0000631 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
Chris Lattner13bf28c2003-06-17 22:21:05 +0000639 } else {
Chris Lattner0658cc22003-10-23 03:48:17 +0000640 CallSite CS = CallSite::get(I);
641 assert(CS.getInstruction() && "Unknown instruction for the I2I list!");
Chris Lattner13bf28c2003-06-17 22:21:05 +0000642
Chris Lattner0658cc22003-10-23 03:48:17 +0000643 Function *Callee = CS.getCalledFunction();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000644
Chris Lattner0658cc22003-10-23 03:48:17 +0000645 // 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.
Chris Lattner13bf28c2003-06-17 22:21:05 +0000648 //
Chris Lattner0658cc22003-10-23 03:48:17 +0000649 CallSite::arg_iterator AI = CS.arg_begin(); // ActualIterator
Chris Lattner53db5462005-05-06 05:34:40 +0000650 for (Function::arg_iterator FI = Callee->arg_begin(),
651 E = Callee->arg_end(); FI != E; ++AI, ++FI) {
Chris Lattner0658cc22003-10-23 03:48:17 +0000652 // 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 }
Chris Lattner13bf28c2003-06-17 22:21:05 +0000658 }
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 //
Chris Lattner0658cc22003-10-23 03:48:17 +0000666 // Because elements can be removed from the MaybeLiveArguments set, copy it to
667 // a temporary vector.
Chris Lattner13bf28c2003-06-17 22:21:05 +0000668 //
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) &&
Chris Lattner0658cc22003-10-23 03:48:17 +0000674 isMaybeLiveArgumentNowLive(MLA))
675 MarkArgumentLive(MLA);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000676 }
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.
Chris Lattner0658cc22003-10-23 03:48:17 +0000684 if (MaybeLiveArguments.empty() && DeadArguments.empty() &&
685 MaybeLiveRetVal.empty() && DeadRetVal.empty())
Chris Lattner13bf28c2003-06-17 22:21:05 +0000686 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000687
Chris Lattner13bf28c2003-06-17 22:21:05 +0000688 // Otherwise, compact into one set, and start eliminating the arguments from
689 // the functions.
690 DeadArguments.insert(MaybeLiveArguments.begin(), MaybeLiveArguments.end());
691 MaybeLiveArguments.clear();
Chris Lattner0658cc22003-10-23 03:48:17 +0000692 DeadRetVal.insert(MaybeLiveRetVal.begin(), MaybeLiveRetVal.end());
693 MaybeLiveRetVal.clear();
694
695 LiveArguments.clear();
696 LiveRetVal.clear();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000697
698 NumArgumentsEliminated += DeadArguments.size();
Chris Lattner0658cc22003-10-23 03:48:17 +0000699 NumRetValsEliminated += DeadRetVal.size();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000700 while (!DeadArguments.empty())
Chris Lattner0658cc22003-10-23 03:48:17 +0000701 RemoveDeadArgumentsFromFunction((*DeadArguments.begin())->getParent());
702
703 while (!DeadRetVal.empty())
704 RemoveDeadArgumentsFromFunction(*DeadRetVal.begin());
Chris Lattner13bf28c2003-06-17 22:21:05 +0000705 return true;
706}