blob: 9d88a8879fcddec8a1411d0e65255164191dca7f [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 Lattner13bf28c2003-06-17 22:21:05 +000032#include <set>
Chris Lattnerf52e03c2003-11-21 21:54:22 +000033using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000034
Chris Lattner1631bcb2006-12-19 22:09:18 +000035STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
36STATISTIC(NumRetValsEliminated , "Number of unused return values removed");
Chris Lattner13bf28c2003-06-17 22:21:05 +000037
Chris Lattner1631bcb2006-12-19 22:09:18 +000038namespace {
Chris Lattner0658cc22003-10-23 03:48:17 +000039 /// DAE - The dead argument elimination pass.
40 ///
Chris Lattner4f2cf032004-09-20 04:48:05 +000041 class DAE : public ModulePass {
Chris Lattner0658cc22003-10-23 03:48:17 +000042 /// Liveness enum - During our initial pass over the program, we determine
43 /// that things are either definately alive, definately dead, or in need of
44 /// interprocedural analysis (MaybeLive).
45 ///
46 enum Liveness { Live, MaybeLive, Dead };
47
48 /// LiveArguments, MaybeLiveArguments, DeadArguments - These sets contain
49 /// all of the arguments in the program. The Dead set contains arguments
50 /// which are completely dead (never used in the function). The MaybeLive
51 /// set contains arguments which are only passed into other function calls,
52 /// thus may be live and may be dead. The Live set contains arguments which
53 /// are known to be alive.
54 ///
55 std::set<Argument*> DeadArguments, MaybeLiveArguments, LiveArguments;
56
57 /// DeadRetVal, MaybeLiveRetVal, LifeRetVal - These sets contain all of the
58 /// functions in the program. The Dead set contains functions whose return
59 /// value is known to be dead. The MaybeLive set contains functions whose
60 /// return values are only used by return instructions, and the Live set
61 /// contains functions whose return values are used, functions that are
62 /// external, and functions that already return void.
63 ///
64 std::set<Function*> DeadRetVal, MaybeLiveRetVal, LiveRetVal;
65
66 /// InstructionsToInspect - As we mark arguments and return values
67 /// MaybeLive, we keep track of which instructions could make the values
68 /// live here. Once the entire program has had the return value and
69 /// arguments analyzed, this set is scanned to promote the MaybeLive objects
70 /// to be Live if they really are used.
71 std::vector<Instruction*> InstructionsToInspect;
72
73 /// CallSites - Keep track of the call sites of functions that have
74 /// MaybeLive arguments or return values.
75 std::multimap<Function*, CallSite> CallSites;
76
77 public:
Chris Lattner4f2cf032004-09-20 04:48:05 +000078 bool runOnModule(Module &M);
Chris Lattner2ab04f72003-06-25 04:12:49 +000079
Chris Lattner9e60ace2003-11-05 21:43:02 +000080 virtual bool ShouldHackArguments() const { return false; }
81
Chris Lattner2ab04f72003-06-25 04:12:49 +000082 private:
Chris Lattner0658cc22003-10-23 03:48:17 +000083 Liveness getArgumentLiveness(const Argument &A);
84 bool isMaybeLiveArgumentNowLive(Argument *Arg);
85
Chris Lattner67a35bb2006-09-18 07:02:31 +000086 bool DeleteDeadVarargs(Function &Fn);
Chris Lattner0658cc22003-10-23 03:48:17 +000087 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 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +000095 RegisterPass<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 Lattner67a35bb2006-09-18 07:02:31 +0000113/// DeleteDeadVarargs - If this is an function that takes a ... list, and if
114/// llvm.vastart is never called, the varargs list is dead for the function.
115bool DAE::DeleteDeadVarargs(Function &Fn) {
116 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
117 if (Fn.isExternal() || !Fn.hasInternalLinkage()) return false;
118
119 // Ensure that the function is only directly called.
120 for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end(); I != E; ++I) {
121 // If this use is anything other than a call site, give up.
122 CallSite CS = CallSite::get(*I);
123 Instruction *TheCall = CS.getInstruction();
124 if (!TheCall) return false; // Not a direct call site?
125
126 // The addr of this function is passed to the call.
127 if (I.getOperandNo() != 0) return false;
128 }
129
130 // Okay, we know we can transform this function if safe. Scan its body
131 // looking for calls to llvm.vastart.
132 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
133 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
134 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
135 if (II->getIntrinsicID() == Intrinsic::vastart)
136 return false;
137 }
138 }
139 }
140
141 // If we get here, there are no calls to llvm.vastart in the function body,
142 // remove the "..." and adjust all the calls.
143
144 // Start by computing a new prototype for the function, which is the same as
145 // the old function, but has fewer arguments.
146 const FunctionType *FTy = Fn.getFunctionType();
147 std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
148 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), Params, false);
149 unsigned NumArgs = Params.size();
150
151 // Create the new function body and insert it into the module...
152 Function *NF = new Function(NFTy, Fn.getLinkage(), Fn.getName());
153 NF->setCallingConv(Fn.getCallingConv());
154 Fn.getParent()->getFunctionList().insert(&Fn, NF);
155
156 // Loop over all of the callers of the function, transforming the call sites
157 // to pass in a smaller number of arguments into the new function.
158 //
159 std::vector<Value*> Args;
160 while (!Fn.use_empty()) {
161 CallSite CS = CallSite::get(Fn.use_back());
162 Instruction *Call = CS.getInstruction();
163
164 // Loop over the operands, dropping extraneous ones at the end of the list.
165 Args.assign(CS.arg_begin(), CS.arg_begin()+NumArgs);
166
167 Instruction *New;
168 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
169 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
170 Args, "", Call);
171 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
172 } else {
173 New = new CallInst(NF, Args, "", Call);
174 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
175 if (cast<CallInst>(Call)->isTailCall())
176 cast<CallInst>(New)->setTailCall();
177 }
178 Args.clear();
179
180 if (!Call->use_empty())
181 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
182
183 if (Call->hasName()) {
184 std::string Name = Call->getName();
185 Call->setName("");
186 New->setName(Name);
187 }
188
189 // Finally, remove the old call from the program, reducing the use-count of
190 // F.
191 Call->getParent()->getInstList().erase(Call);
192 }
193
194 // Since we have now created the new function, splice the body of the old
195 // function right into the new function, leaving the old rotting hulk of the
196 // function empty.
197 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
198
199 // Loop over the argument list, transfering uses of the old arguments over to
200 // the new arguments, also transfering over the names as well. While we're at
201 // it, remove the dead arguments from the DeadArguments list.
202 //
203 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
204 I2 = NF->arg_begin(); I != E; ++I, ++I2) {
205 // Move the name and users over to the new version.
206 I->replaceAllUsesWith(I2);
207 I2->setName(I->getName());
208 }
209
210 // Finally, nuke the old function.
211 Fn.eraseFromParent();
212 return true;
213}
214
215
Chris Lattner0658cc22003-10-23 03:48:17 +0000216static inline bool CallPassesValueThoughVararg(Instruction *Call,
217 const Value *Arg) {
218 CallSite CS = CallSite::get(Call);
219 const Type *CalledValueTy = CS.getCalledValue()->getType();
220 const Type *FTy = cast<PointerType>(CalledValueTy)->getElementType();
221 unsigned NumFixedArgs = cast<FunctionType>(FTy)->getNumParams();
222 for (CallSite::arg_iterator AI = CS.arg_begin()+NumFixedArgs;
223 AI != CS.arg_end(); ++AI)
224 if (AI->get() == Arg)
225 return true;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000226 return false;
227}
228
Chris Lattner0658cc22003-10-23 03:48:17 +0000229// getArgumentLiveness - Inspect an argument, determining if is known Live
Chris Lattner13bf28c2003-06-17 22:21:05 +0000230// (used in a computation), MaybeLive (only passed as an argument to a call), or
231// Dead (not used).
Chris Lattner0658cc22003-10-23 03:48:17 +0000232DAE::Liveness DAE::getArgumentLiveness(const Argument &A) {
Chris Lattnerc4998a02006-06-27 21:05:04 +0000233 // If this is the return value of a csret function, it's not really dead.
234 if (A.getParent()->getCallingConv() == CallingConv::CSRet &&
235 &*A.getParent()->arg_begin() == &A)
236 return Live;
237
238 if (A.use_empty()) // First check, directly dead?
239 return Dead;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000240
241 // Scan through all of the uses, looking for non-argument passing uses.
242 for (Value::use_const_iterator I = A.use_begin(), E = A.use_end(); I!=E;++I) {
Chris Lattner0658cc22003-10-23 03:48:17 +0000243 // Return instructions do not immediately effect liveness.
244 if (isa<ReturnInst>(*I))
245 continue;
246
Chris Lattner13bf28c2003-06-17 22:21:05 +0000247 CallSite CS = CallSite::get(const_cast<User*>(*I));
248 if (!CS.getInstruction()) {
249 // If its used by something that is not a call or invoke, it's alive!
Chris Lattner0658cc22003-10-23 03:48:17 +0000250 return Live;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000251 }
252 // If it's an indirect call, mark it alive...
253 Function *Callee = CS.getCalledFunction();
Chris Lattner0658cc22003-10-23 03:48:17 +0000254 if (!Callee) return Live;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000255
Chris Lattner5d3c1452003-06-18 16:25:51 +0000256 // Check to see if it's passed through a va_arg area: if so, we cannot
257 // remove it.
Chris Lattner0658cc22003-10-23 03:48:17 +0000258 if (CallPassesValueThoughVararg(CS.getInstruction(), &A))
259 return Live; // If passed through va_arg area, we cannot remove it
Chris Lattner13bf28c2003-06-17 22:21:05 +0000260 }
261
262 return MaybeLive; // It must be used, but only as argument to a function
263}
264
Chris Lattner0658cc22003-10-23 03:48:17 +0000265
266// SurveyFunction - This performs the initial survey of the specified function,
267// checking out whether or not it uses any of its incoming arguments or whether
268// any callers use the return value. This fills in the
269// (Dead|MaybeLive|Live)(Arguments|RetVal) sets.
Chris Lattner13bf28c2003-06-17 22:21:05 +0000270//
Chris Lattner0658cc22003-10-23 03:48:17 +0000271// We consider arguments of non-internal functions to be intrinsically alive as
272// well as arguments to functions which have their "address taken".
273//
274void DAE::SurveyFunction(Function &F) {
275 bool FunctionIntrinsicallyLive = false;
276 Liveness RetValLiveness = F.getReturnType() == Type::VoidTy ? Live : Dead;
277
Chris Lattner4e1b4672003-11-05 21:53:41 +0000278 if (!F.hasInternalLinkage() &&
279 (!ShouldHackArguments() || F.getIntrinsicID()))
Chris Lattner0658cc22003-10-23 03:48:17 +0000280 FunctionIntrinsicallyLive = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000281 else
Chris Lattner0658cc22003-10-23 03:48:17 +0000282 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
283 // If this use is anything other than a call site, the function is alive.
284 CallSite CS = CallSite::get(*I);
285 Instruction *TheCall = CS.getInstruction();
286 if (!TheCall) { // Not a direct call site?
287 FunctionIntrinsicallyLive = true;
288 break;
289 }
290
291 // Check to see if the return value is used...
292 if (RetValLiveness != Live)
293 for (Value::use_iterator I = TheCall->use_begin(),
294 E = TheCall->use_end(); I != E; ++I)
295 if (isa<ReturnInst>(cast<Instruction>(*I))) {
296 RetValLiveness = MaybeLive;
297 } else if (isa<CallInst>(cast<Instruction>(*I)) ||
298 isa<InvokeInst>(cast<Instruction>(*I))) {
299 if (CallPassesValueThoughVararg(cast<Instruction>(*I), TheCall) ||
300 !CallSite::get(cast<Instruction>(*I)).getCalledFunction()) {
301 RetValLiveness = Live;
302 break;
303 } else {
304 RetValLiveness = MaybeLive;
305 }
306 } else {
307 RetValLiveness = Live;
308 break;
309 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000310
Chris Lattner0658cc22003-10-23 03:48:17 +0000311 // If the function is PASSED IN as an argument, its address has been taken
312 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
313 AI != E; ++AI)
314 if (AI->get() == &F) {
315 FunctionIntrinsicallyLive = true;
316 break;
317 }
318 if (FunctionIntrinsicallyLive) break;
319 }
320
321 if (FunctionIntrinsicallyLive) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000322 DOUT << " Intrinsically live fn: " << F.getName() << "\n";
Chris Lattner53db5462005-05-06 05:34:40 +0000323 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
324 AI != E; ++AI)
Chris Lattner0658cc22003-10-23 03:48:17 +0000325 LiveArguments.insert(AI);
326 LiveRetVal.insert(&F);
327 return;
328 }
329
330 switch (RetValLiveness) {
331 case Live: LiveRetVal.insert(&F); break;
332 case MaybeLive: MaybeLiveRetVal.insert(&F); break;
333 case Dead: DeadRetVal.insert(&F); break;
334 }
335
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000336 DOUT << " Inspecting args for fn: " << F.getName() << "\n";
Chris Lattner0658cc22003-10-23 03:48:17 +0000337
338 // If it is not intrinsically alive, we know that all users of the
339 // function are call sites. Mark all of the arguments live which are
340 // directly used, and keep track of all of the call sites of this function
341 // if there are any arguments we assume that are dead.
342 //
343 bool AnyMaybeLiveArgs = false;
Chris Lattner53db5462005-05-06 05:34:40 +0000344 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
345 AI != E; ++AI)
Chris Lattner0658cc22003-10-23 03:48:17 +0000346 switch (getArgumentLiveness(*AI)) {
347 case Live:
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000348 DOUT << " Arg live by use: " << AI->getName() << "\n";
Chris Lattner0658cc22003-10-23 03:48:17 +0000349 LiveArguments.insert(AI);
350 break;
351 case Dead:
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000352 DOUT << " Arg definitely dead: " << AI->getName() <<"\n";
Chris Lattner0658cc22003-10-23 03:48:17 +0000353 DeadArguments.insert(AI);
354 break;
355 case MaybeLive:
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000356 DOUT << " Arg only passed to calls: " << AI->getName() << "\n";
Chris Lattner0658cc22003-10-23 03:48:17 +0000357 AnyMaybeLiveArgs = true;
358 MaybeLiveArguments.insert(AI);
359 break;
360 }
361
362 // If there are any "MaybeLive" arguments, we need to check callees of
363 // this function when/if they become alive. Record which functions are
364 // callees...
365 if (AnyMaybeLiveArgs || RetValLiveness == MaybeLive)
366 for (Value::use_iterator I = F.use_begin(), E = F.use_end();
367 I != E; ++I) {
368 if (AnyMaybeLiveArgs)
369 CallSites.insert(std::make_pair(&F, CallSite::get(*I)));
370
371 if (RetValLiveness == MaybeLive)
372 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
373 UI != E; ++UI)
374 InstructionsToInspect.push_back(cast<Instruction>(*UI));
375 }
376}
377
378// isMaybeLiveArgumentNowLive - Check to see if Arg is alive. At this point, we
379// know that the only uses of Arg are to be passed in as an argument to a
380// function call or return. Check to see if the formal argument passed in is in
381// the LiveArguments set. If so, return true.
382//
383bool DAE::isMaybeLiveArgumentNowLive(Argument *Arg) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000384 for (Value::use_iterator I = Arg->use_begin(), E = Arg->use_end(); I!=E; ++I){
Chris Lattner0658cc22003-10-23 03:48:17 +0000385 if (isa<ReturnInst>(*I)) {
386 if (LiveRetVal.count(Arg->getParent())) return true;
387 continue;
388 }
389
Chris Lattner13bf28c2003-06-17 22:21:05 +0000390 CallSite CS = CallSite::get(*I);
391
392 // We know that this can only be used for direct calls...
Chris Lattner7f7285b2003-11-02 02:06:27 +0000393 Function *Callee = CS.getCalledFunction();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000394
395 // Loop over all of the arguments (because Arg may be passed into the call
396 // multiple times) and check to see if any are now alive...
397 CallSite::arg_iterator CSAI = CS.arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +0000398 for (Function::arg_iterator AI = Callee->arg_begin(), E = Callee->arg_end();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000399 AI != E; ++AI, ++CSAI)
400 // If this is the argument we are looking for, check to see if it's alive
401 if (*CSAI == Arg && LiveArguments.count(AI))
402 return true;
403 }
404 return false;
405}
406
Chris Lattner0658cc22003-10-23 03:48:17 +0000407/// MarkArgumentLive - The MaybeLive argument 'Arg' is now known to be alive.
408/// Mark it live in the specified sets and recursively mark arguments in callers
409/// live that are needed to pass in a value.
410///
411void DAE::MarkArgumentLive(Argument *Arg) {
412 std::set<Argument*>::iterator It = MaybeLiveArguments.lower_bound(Arg);
413 if (It == MaybeLiveArguments.end() || *It != Arg) return;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000414
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000415 DOUT << " MaybeLive argument now live: " << Arg->getName() <<"\n";
Chris Lattner0658cc22003-10-23 03:48:17 +0000416 MaybeLiveArguments.erase(It);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000417 LiveArguments.insert(Arg);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000418
Chris Lattner13bf28c2003-06-17 22:21:05 +0000419 // Loop over all of the call sites of the function, making any arguments
420 // passed in to provide a value for this argument live as necessary.
421 //
422 Function *Fn = Arg->getParent();
Chris Lattner531f9e92005-03-15 04:54:21 +0000423 unsigned ArgNo = std::distance(Fn->arg_begin(), Function::arg_iterator(Arg));
Chris Lattner13bf28c2003-06-17 22:21:05 +0000424
Chris Lattner0658cc22003-10-23 03:48:17 +0000425 std::multimap<Function*, CallSite>::iterator I = CallSites.lower_bound(Fn);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000426 for (; I != CallSites.end() && I->first == Fn; ++I) {
Chris Lattner0658cc22003-10-23 03:48:17 +0000427 CallSite CS = I->second;
428 Value *ArgVal = *(CS.arg_begin()+ArgNo);
429 if (Argument *ActualArg = dyn_cast<Argument>(ArgVal)) {
430 MarkArgumentLive(ActualArg);
431 } else {
432 // If the value passed in at this call site is a return value computed by
433 // some other call site, make sure to mark the return value at the other
434 // call site as being needed.
435 CallSite ArgCS = CallSite::get(ArgVal);
436 if (ArgCS.getInstruction())
437 if (Function *Fn = ArgCS.getCalledFunction())
438 MarkRetValLive(Fn);
439 }
440 }
441}
442
443/// MarkArgumentLive - The MaybeLive return value for the specified function is
444/// now known to be alive. Propagate this fact to the return instructions which
445/// produce it.
446void DAE::MarkRetValLive(Function *F) {
447 assert(F && "Shame shame, we can't have null pointers here!");
448
449 // Check to see if we already knew it was live
450 std::set<Function*>::iterator I = MaybeLiveRetVal.lower_bound(F);
451 if (I == MaybeLiveRetVal.end() || *I != F) return; // It's already alive!
452
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000453 DOUT << " MaybeLive retval now live: " << F->getName() << "\n";
Chris Lattner0658cc22003-10-23 03:48:17 +0000454
455 MaybeLiveRetVal.erase(I);
456 LiveRetVal.insert(F); // It is now known to be live!
457
458 // Loop over all of the functions, noticing that the return value is now live.
459 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
460 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
461 MarkReturnInstArgumentLive(RI);
462}
463
464void DAE::MarkReturnInstArgumentLive(ReturnInst *RI) {
465 Value *Op = RI->getOperand(0);
466 if (Argument *A = dyn_cast<Argument>(Op)) {
467 MarkArgumentLive(A);
468 } else if (CallInst *CI = dyn_cast<CallInst>(Op)) {
469 if (Function *F = CI->getCalledFunction())
470 MarkRetValLive(F);
471 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
472 if (Function *F = II->getCalledFunction())
473 MarkRetValLive(F);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000474 }
475}
476
477// RemoveDeadArgumentsFromFunction - We know that F has dead arguments, as
478// specified by the DeadArguments list. Transform the function and all of the
479// callees of the function to not have these arguments.
480//
Chris Lattner0658cc22003-10-23 03:48:17 +0000481void DAE::RemoveDeadArgumentsFromFunction(Function *F) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000482 // Start by computing a new prototype for the function, which is the same as
483 // the old function, but has fewer arguments.
484 const FunctionType *FTy = F->getFunctionType();
485 std::vector<const Type*> Params;
486
Chris Lattner531f9e92005-03-15 04:54:21 +0000487 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattner13bf28c2003-06-17 22:21:05 +0000488 if (!DeadArguments.count(I))
489 Params.push_back(I->getType());
490
Chris Lattner0658cc22003-10-23 03:48:17 +0000491 const Type *RetTy = FTy->getReturnType();
492 if (DeadRetVal.count(F)) {
493 RetTy = Type::VoidTy;
494 DeadRetVal.erase(F);
495 }
496
Chris Lattner05c71fb2003-10-23 17:44:53 +0000497 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
498 // have zero fixed arguments.
499 //
Chris Lattner05c71fb2003-10-23 17:44:53 +0000500 bool ExtraArgHack = false;
501 if (Params.empty() && FTy->isVarArg()) {
502 ExtraArgHack = true;
503 Params.push_back(Type::IntTy);
504 }
505
Chris Lattner0658cc22003-10-23 03:48:17 +0000506 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
507
Chris Lattner13bf28c2003-06-17 22:21:05 +0000508 // Create the new function body and insert it into the module...
Chris Lattner2ab04f72003-06-25 04:12:49 +0000509 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
Chris Lattnerd0525a22005-05-09 01:05:50 +0000510 NF->setCallingConv(F->getCallingConv());
Chris Lattner13bf28c2003-06-17 22:21:05 +0000511 F->getParent()->getFunctionList().insert(F, NF);
512
513 // Loop over all of the callers of the function, transforming the call sites
514 // to pass in a smaller number of arguments into the new function.
515 //
Chris Lattner0658cc22003-10-23 03:48:17 +0000516 std::vector<Value*> Args;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000517 while (!F->use_empty()) {
518 CallSite CS = CallSite::get(F->use_back());
519 Instruction *Call = CS.getInstruction();
Chris Lattner0658cc22003-10-23 03:48:17 +0000520
Chris Lattner13bf28c2003-06-17 22:21:05 +0000521 // Loop over the operands, deleting dead ones...
522 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattner53db5462005-05-06 05:34:40 +0000523 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
524 I != E; ++I, ++AI)
Chris Lattner0658cc22003-10-23 03:48:17 +0000525 if (!DeadArguments.count(I)) // Remove operands for dead arguments
526 Args.push_back(*AI);
527
Chris Lattner05c71fb2003-10-23 17:44:53 +0000528 if (ExtraArgHack)
Chris Lattnerfd5f03e2006-12-16 21:21:53 +0000529 Args.push_back(UndefValue::get(Type::IntTy));
Chris Lattner05c71fb2003-10-23 17:44:53 +0000530
531 // Push any varargs arguments on the list
532 for (; AI != CS.arg_end(); ++AI)
533 Args.push_back(*AI);
534
Chris Lattner0658cc22003-10-23 03:48:17 +0000535 Instruction *New;
536 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +0000537 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner0658cc22003-10-23 03:48:17 +0000538 Args, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000539 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner0658cc22003-10-23 03:48:17 +0000540 } else {
541 New = new CallInst(NF, Args, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000542 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner324d2ee2005-05-06 06:46:58 +0000543 if (cast<CallInst>(Call)->isTailCall())
544 cast<CallInst>(New)->setTailCall();
Chris Lattner0658cc22003-10-23 03:48:17 +0000545 }
546 Args.clear();
547
548 if (!Call->use_empty()) {
549 if (New->getType() == Type::VoidTy)
550 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
551 else {
552 Call->replaceAllUsesWith(New);
553 std::string Name = Call->getName();
554 Call->setName("");
555 New->setName(Name);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000556 }
Chris Lattner0658cc22003-10-23 03:48:17 +0000557 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000558
Chris Lattner0658cc22003-10-23 03:48:17 +0000559 // Finally, remove the old call from the program, reducing the use-count of
560 // F.
561 Call->getParent()->getInstList().erase(Call);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000562 }
563
564 // Since we have now created the new function, splice the body of the old
565 // function right into the new function, leaving the old rotting hulk of the
566 // function empty.
567 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
568
569 // Loop over the argument list, transfering uses of the old arguments over to
570 // the new arguments, also transfering over the names as well. While we're at
571 // it, remove the dead arguments from the DeadArguments list.
572 //
Chris Lattner53db5462005-05-06 05:34:40 +0000573 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
574 I2 = NF->arg_begin();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000575 I != E; ++I)
576 if (!DeadArguments.count(I)) {
577 // If this is a live argument, move the name and users over to the new
578 // version.
579 I->replaceAllUsesWith(I2);
580 I2->setName(I->getName());
581 ++I2;
582 } else {
583 // If this argument is dead, replace any uses of it with null constants
584 // (these are guaranteed to only be operands to call instructions which
585 // will later be simplified).
586 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
587 DeadArguments.erase(I);
588 }
589
Chris Lattner0658cc22003-10-23 03:48:17 +0000590 // If we change the return value of the function we must rewrite any return
591 // instructions. Check this now.
592 if (F->getReturnType() != NF->getReturnType())
593 for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
594 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
595 new ReturnInst(0, RI);
596 BB->getInstList().erase(RI);
597 }
598
Chris Lattner13bf28c2003-06-17 22:21:05 +0000599 // Now that the old function is dead, delete it.
600 F->getParent()->getFunctionList().erase(F);
601}
602
Chris Lattner4f2cf032004-09-20 04:48:05 +0000603bool DAE::runOnModule(Module &M) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000604 // First phase: loop through the module, determining which arguments are live.
605 // We assume all arguments are dead unless proven otherwise (allowing us to
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000606 // determine that dead arguments passed into recursive functions are dead).
Chris Lattner13bf28c2003-06-17 22:21:05 +0000607 //
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000608 DOUT << "DAE - Determining liveness\n";
Chris Lattner67a35bb2006-09-18 07:02:31 +0000609 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
610 Function &F = *I++;
611 if (F.getFunctionType()->isVarArg())
612 if (DeleteDeadVarargs(F))
613 continue;
614
615 SurveyFunction(F);
616 }
Chris Lattner0658cc22003-10-23 03:48:17 +0000617
618 // Loop over the instructions to inspect, propagating liveness among arguments
619 // and return values which are MaybeLive.
620
621 while (!InstructionsToInspect.empty()) {
622 Instruction *I = InstructionsToInspect.back();
623 InstructionsToInspect.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000624
Chris Lattner0658cc22003-10-23 03:48:17 +0000625 if (ReturnInst *RI = dyn_cast<ReturnInst>(I)) {
626 // For return instructions, we just have to check to see if the return
627 // value for the current function is known now to be alive. If so, any
628 // arguments used by it are now alive, and any call instruction return
629 // value is alive as well.
630 if (LiveRetVal.count(RI->getParent()->getParent()))
631 MarkReturnInstArgumentLive(RI);
632
Chris Lattner13bf28c2003-06-17 22:21:05 +0000633 } else {
Chris Lattner0658cc22003-10-23 03:48:17 +0000634 CallSite CS = CallSite::get(I);
635 assert(CS.getInstruction() && "Unknown instruction for the I2I list!");
Chris Lattner13bf28c2003-06-17 22:21:05 +0000636
Chris Lattner0658cc22003-10-23 03:48:17 +0000637 Function *Callee = CS.getCalledFunction();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000638
Chris Lattner0658cc22003-10-23 03:48:17 +0000639 // If we found a call or invoke instruction on this list, that means that
640 // an argument of the function is a call instruction. If the argument is
641 // live, then the return value of the called instruction is now live.
Chris Lattner13bf28c2003-06-17 22:21:05 +0000642 //
Chris Lattner0658cc22003-10-23 03:48:17 +0000643 CallSite::arg_iterator AI = CS.arg_begin(); // ActualIterator
Chris Lattner53db5462005-05-06 05:34:40 +0000644 for (Function::arg_iterator FI = Callee->arg_begin(),
645 E = Callee->arg_end(); FI != E; ++AI, ++FI) {
Chris Lattner0658cc22003-10-23 03:48:17 +0000646 // If this argument is another call...
647 CallSite ArgCS = CallSite::get(*AI);
648 if (ArgCS.getInstruction() && LiveArguments.count(FI))
649 if (Function *Callee = ArgCS.getCalledFunction())
650 MarkRetValLive(Callee);
651 }
Chris Lattner13bf28c2003-06-17 22:21:05 +0000652 }
653 }
654
655 // Now we loop over all of the MaybeLive arguments, promoting them to be live
656 // arguments if one of the calls that uses the arguments to the calls they are
657 // passed into requires them to be live. Of course this could make other
658 // arguments live, so process callers recursively.
659 //
Chris Lattner0658cc22003-10-23 03:48:17 +0000660 // Because elements can be removed from the MaybeLiveArguments set, copy it to
661 // a temporary vector.
Chris Lattner13bf28c2003-06-17 22:21:05 +0000662 //
663 std::vector<Argument*> TmpArgList(MaybeLiveArguments.begin(),
664 MaybeLiveArguments.end());
665 for (unsigned i = 0, e = TmpArgList.size(); i != e; ++i) {
666 Argument *MLA = TmpArgList[i];
667 if (MaybeLiveArguments.count(MLA) &&
Chris Lattner0658cc22003-10-23 03:48:17 +0000668 isMaybeLiveArgumentNowLive(MLA))
669 MarkArgumentLive(MLA);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000670 }
671
672 // Recover memory early...
673 CallSites.clear();
674
675 // At this point, we know that all arguments in DeadArguments and
676 // MaybeLiveArguments are dead. If the two sets are empty, there is nothing
677 // to do.
Chris Lattner0658cc22003-10-23 03:48:17 +0000678 if (MaybeLiveArguments.empty() && DeadArguments.empty() &&
679 MaybeLiveRetVal.empty() && DeadRetVal.empty())
Chris Lattner13bf28c2003-06-17 22:21:05 +0000680 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000681
Chris Lattner13bf28c2003-06-17 22:21:05 +0000682 // Otherwise, compact into one set, and start eliminating the arguments from
683 // the functions.
684 DeadArguments.insert(MaybeLiveArguments.begin(), MaybeLiveArguments.end());
685 MaybeLiveArguments.clear();
Chris Lattner0658cc22003-10-23 03:48:17 +0000686 DeadRetVal.insert(MaybeLiveRetVal.begin(), MaybeLiveRetVal.end());
687 MaybeLiveRetVal.clear();
688
689 LiveArguments.clear();
690 LiveRetVal.clear();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000691
692 NumArgumentsEliminated += DeadArguments.size();
Chris Lattner0658cc22003-10-23 03:48:17 +0000693 NumRetValsEliminated += DeadRetVal.size();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000694 while (!DeadArguments.empty())
Chris Lattner0658cc22003-10-23 03:48:17 +0000695 RemoveDeadArgumentsFromFunction((*DeadArguments.begin())->getParent());
696
697 while (!DeadRetVal.empty())
698 RemoveDeadArgumentsFromFunction(*DeadRetVal.begin());
Chris Lattner13bf28c2003-06-17 22:21:05 +0000699 return true;
700}