blob: 54f086ff95be5f0239bed2022d4debad7d654c20 [file] [log] [blame]
Chris Lattner08227e42003-06-17 22:21:05 +00001//===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner08227e42003-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 Lattnerc3afd9b2003-10-23 03:48:17 +000012// only passed into function calls as dead arguments of other functions. This
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +000013// pass also deletes dead return values in a similar way.
Chris Lattner08227e42003-06-17 22:21:05 +000014//
15// This pass is often useful as a cleanup pass to run after aggressive
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +000016// interprocedural passes, which add possibly-dead arguments or return values.
Chris Lattner08227e42003-06-17 22:21:05 +000017//
18//===----------------------------------------------------------------------===//
19
Chris Lattner543a0272005-06-24 16:00:46 +000020#define DEBUG_TYPE "deadargelim"
Chris Lattner08227e42003-06-17 22:21:05 +000021#include "llvm/Transforms/IPO.h"
Chris Lattner92044ce2006-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 Lattner4af90ab2006-09-18 07:02:31 +000026#include "llvm/IntrinsicInst.h"
Chris Lattner08227e42003-06-17 22:21:05 +000027#include "llvm/Module.h"
28#include "llvm/Pass.h"
Chris Lattner08227e42003-06-17 22:21:05 +000029#include "llvm/Support/CallSite.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000030#include "llvm/Support/Debug.h"
Chris Lattner58d74912008-03-12 17:45:29 +000031#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/ADT/Statistic.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000033#include "llvm/Support/Compiler.h"
Dan Gohmanc9235d22008-03-21 23:51:57 +000034#include <map>
Chris Lattner08227e42003-06-17 22:21:05 +000035#include <set>
Chris Lattner1e2385b2003-11-21 21:54:22 +000036using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000037
Chris Lattner86453c52006-12-19 22:09:18 +000038STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
39STATISTIC(NumRetValsEliminated , "Number of unused return values removed");
Chris Lattner08227e42003-06-17 22:21:05 +000040
Chris Lattner86453c52006-12-19 22:09:18 +000041namespace {
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000042 /// DAE - The dead argument elimination pass.
43 ///
Reid Spencer9133fe22007-02-05 23:32:05 +000044 class VISIBILITY_HIDDEN DAE : public ModulePass {
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +000045 public:
46
47 /// Struct that represent either a (part of a) return value or a function
48 /// argument. Used so that arguments and return values can be used
49 /// interchangably.
50 struct RetOrArg {
51 RetOrArg(const Function* F, unsigned Idx, bool IsArg) : F(F), Idx(Idx),
52 IsArg(IsArg) {}
53 const Function *F;
54 unsigned Idx;
55 bool IsArg;
56
57 /// Make RetOrArg comparable, so we can put it into a map
58 bool operator<(const RetOrArg &O) const {
59 if (F != O.F)
60 return F < O.F;
61 else if (Idx != O.Idx)
62 return Idx < O.Idx;
63 else
64 return IsArg < O.IsArg;
65 }
66
67 /// Make RetOrArg comparable, so we can easily iterate the multimap
68 bool operator==(const RetOrArg &O) const {
69 return F == O.F && Idx == O.Idx && IsArg == O.IsArg;
70 }
71 };
72
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000073 /// Liveness enum - During our initial pass over the program, we determine
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +000074 /// that things are either alive or maybe alive. We don't mark anything
Matthijs Kooijman177058b2008-06-25 08:10:21 +000075 /// explicitly dead (even if we know they are), since anything not alive
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +000076 /// with no registered uses (in Uses) will never be marked alive and will
77 /// thus become dead in the end.
78 enum Liveness { Live, MaybeLive };
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000079
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +000080 /// Convenience wrapper
81 RetOrArg CreateRet(const Function *F, unsigned Idx) {
82 return RetOrArg(F, Idx, false);
83 }
84 /// Convenience wrapper
85 RetOrArg CreateArg(const Function *F, unsigned Idx) {
86 return RetOrArg(F, Idx, true);
87 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000088
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +000089 typedef std::multimap<RetOrArg, RetOrArg> UseMap;
90 /// This map maps a return value or argument to all return values or
91 /// arguments it uses.
92 /// For example (indices are left out for clarity):
93 /// - Uses[ret F] = ret G
94 /// This means that F calls G, and F returns the value returned by G.
95 /// - Uses[arg F] = ret G
96 /// This means that some function calls G and passes its result as an
97 /// argument to F.
98 /// - Uses[ret F] = arg F
99 /// This means that F returns one of its own arguments.
100 /// - Uses[arg F] = arg G
101 /// This means that G calls F and passes one of its own (G's) arguments
102 /// directly to F.
103 UseMap Uses;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000104
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000105 typedef std::set<RetOrArg> LiveSet;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000106
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000107 /// This set contains all values that have been determined to be live
108 LiveSet LiveValues;
109
110 typedef SmallVector<RetOrArg, 5> UseVector;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000111
112 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000113 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +0000114 DAE() : ModulePass((intptr_t)&ID) {}
Chris Lattnerb12914b2004-09-20 04:48:05 +0000115 bool runOnModule(Module &M);
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000116
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000117 virtual bool ShouldHackArguments() const { return false; }
118
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000119 private:
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000120 Liveness IsMaybeLive(RetOrArg Use, UseVector &MaybeLiveUses);
121 Liveness SurveyUse(Value::use_iterator U, UseVector &MaybeLiveUses,
122 unsigned RetValNum = 0);
123 Liveness SurveyUses(Value *V, UseVector &MaybeLiveUses);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000124
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000125 void SurveyFunction(Function &F);
126 void MarkValue(const RetOrArg &RA, Liveness L,
127 const UseVector &MaybeLiveUses);
128 void MarkLive(RetOrArg RA);
129 bool RemoveDeadStuffFromFunction(Function *F);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000130 bool DeleteDeadVarargs(Function &Fn);
Chris Lattner08227e42003-06-17 22:21:05 +0000131 };
Dan Gohman844731a2008-05-13 00:00:25 +0000132}
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000133
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000134
Dan Gohman844731a2008-05-13 00:00:25 +0000135char DAE::ID = 0;
136static RegisterPass<DAE>
137X("deadargelim", "Dead Argument Elimination");
138
139namespace {
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000140 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
141 /// deletes arguments to functions which are external. This is only for use
142 /// by bugpoint.
143 struct DAH : public DAE {
Devang Patel19974732007-05-03 01:11:54 +0000144 static char ID;
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000145 virtual bool ShouldHackArguments() const { return true; }
146 };
Chris Lattner08227e42003-06-17 22:21:05 +0000147}
148
Dan Gohman844731a2008-05-13 00:00:25 +0000149char DAH::ID = 0;
150static RegisterPass<DAH>
151Y("deadarghaX0r", "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)");
152
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000153/// createDeadArgEliminationPass - This pass removes arguments from functions
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000154/// which are not used by the body of the function.
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000155///
Chris Lattnerb12914b2004-09-20 04:48:05 +0000156ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
157ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
Chris Lattner08227e42003-06-17 22:21:05 +0000158
Chris Lattner4af90ab2006-09-18 07:02:31 +0000159/// DeleteDeadVarargs - If this is an function that takes a ... list, and if
160/// llvm.vastart is never called, the varargs list is dead for the function.
161bool DAE::DeleteDeadVarargs(Function &Fn) {
162 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
Reid Spencer5cbf9852007-01-30 20:08:39 +0000163 if (Fn.isDeclaration() || !Fn.hasInternalLinkage()) return false;
Duncan Sands110c8352007-12-21 19:16:16 +0000164
Chris Lattner4af90ab2006-09-18 07:02:31 +0000165 // Ensure that the function is only directly called.
166 for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end(); I != E; ++I) {
167 // If this use is anything other than a call site, give up.
168 CallSite CS = CallSite::get(*I);
169 Instruction *TheCall = CS.getInstruction();
170 if (!TheCall) return false; // Not a direct call site?
Duncan Sands110c8352007-12-21 19:16:16 +0000171
Chris Lattner4af90ab2006-09-18 07:02:31 +0000172 // The addr of this function is passed to the call.
173 if (I.getOperandNo() != 0) return false;
174 }
Duncan Sands110c8352007-12-21 19:16:16 +0000175
Chris Lattner4af90ab2006-09-18 07:02:31 +0000176 // Okay, we know we can transform this function if safe. Scan its body
177 // looking for calls to llvm.vastart.
178 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
179 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
180 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
181 if (II->getIntrinsicID() == Intrinsic::vastart)
182 return false;
183 }
184 }
185 }
Duncan Sands110c8352007-12-21 19:16:16 +0000186
Chris Lattner4af90ab2006-09-18 07:02:31 +0000187 // If we get here, there are no calls to llvm.vastart in the function body,
188 // remove the "..." and adjust all the calls.
Duncan Sands110c8352007-12-21 19:16:16 +0000189
Chris Lattner4af90ab2006-09-18 07:02:31 +0000190 // Start by computing a new prototype for the function, which is the same as
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000191 // the old function, but doesn't have isVarArg set.
Chris Lattner4af90ab2006-09-18 07:02:31 +0000192 const FunctionType *FTy = Fn.getFunctionType();
193 std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
194 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), Params, false);
195 unsigned NumArgs = Params.size();
Duncan Sands110c8352007-12-21 19:16:16 +0000196
Chris Lattner4af90ab2006-09-18 07:02:31 +0000197 // Create the new function body and insert it into the module...
Gabor Greif051a9502008-04-06 20:25:17 +0000198 Function *NF = Function::Create(NFTy, Fn.getLinkage());
Duncan Sands28c3cff2008-05-26 19:58:59 +0000199 NF->copyAttributesFrom(&Fn);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000200 Fn.getParent()->getFunctionList().insert(&Fn, NF);
Chris Lattner046800a2007-02-11 01:08:35 +0000201 NF->takeName(&Fn);
Duncan Sands110c8352007-12-21 19:16:16 +0000202
Chris Lattner4af90ab2006-09-18 07:02:31 +0000203 // Loop over all of the callers of the function, transforming the call sites
204 // to pass in a smaller number of arguments into the new function.
205 //
206 std::vector<Value*> Args;
207 while (!Fn.use_empty()) {
208 CallSite CS = CallSite::get(Fn.use_back());
209 Instruction *Call = CS.getInstruction();
Duncan Sands110c8352007-12-21 19:16:16 +0000210
Chris Lattnera0bc7fc2007-10-18 18:49:29 +0000211 // Pass all the same arguments.
Chris Lattner4af90ab2006-09-18 07:02:31 +0000212 Args.assign(CS.arg_begin(), CS.arg_begin()+NumArgs);
Duncan Sands110c8352007-12-21 19:16:16 +0000213
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000214 // Drop any attributes that were on the vararg arguments.
Chris Lattner58d74912008-03-12 17:45:29 +0000215 PAListPtr PAL = CS.getParamAttrs();
216 if (!PAL.isEmpty() && PAL.getSlot(PAL.getNumSlots() - 1).Index > NumArgs) {
217 SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
218 for (unsigned i = 0; PAL.getSlot(i).Index <= NumArgs; ++i)
219 ParamAttrsVec.push_back(PAL.getSlot(i));
220 PAL = PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end());
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000221 }
222
Chris Lattner4af90ab2006-09-18 07:02:31 +0000223 Instruction *New;
224 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000225 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
226 Args.begin(), Args.end(), "", Call);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000227 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000228 cast<InvokeInst>(New)->setParamAttrs(PAL);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000229 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000230 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000231 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000232 cast<CallInst>(New)->setParamAttrs(PAL);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000233 if (cast<CallInst>(Call)->isTailCall())
234 cast<CallInst>(New)->setTailCall();
235 }
236 Args.clear();
Duncan Sands110c8352007-12-21 19:16:16 +0000237
Chris Lattner4af90ab2006-09-18 07:02:31 +0000238 if (!Call->use_empty())
Chris Lattnera0bc7fc2007-10-18 18:49:29 +0000239 Call->replaceAllUsesWith(New);
Duncan Sands110c8352007-12-21 19:16:16 +0000240
Chris Lattner046800a2007-02-11 01:08:35 +0000241 New->takeName(Call);
Duncan Sands110c8352007-12-21 19:16:16 +0000242
Chris Lattner4af90ab2006-09-18 07:02:31 +0000243 // Finally, remove the old call from the program, reducing the use-count of
244 // F.
Chris Lattnera0bc7fc2007-10-18 18:49:29 +0000245 Call->eraseFromParent();
Chris Lattner4af90ab2006-09-18 07:02:31 +0000246 }
Duncan Sands110c8352007-12-21 19:16:16 +0000247
Chris Lattner4af90ab2006-09-18 07:02:31 +0000248 // Since we have now created the new function, splice the body of the old
249 // function right into the new function, leaving the old rotting hulk of the
250 // function empty.
251 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
Duncan Sands110c8352007-12-21 19:16:16 +0000252
Chris Lattner4af90ab2006-09-18 07:02:31 +0000253 // Loop over the argument list, transfering uses of the old arguments over to
254 // the new arguments, also transfering over the names as well. While we're at
255 // it, remove the dead arguments from the DeadArguments list.
256 //
257 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
258 I2 = NF->arg_begin(); I != E; ++I, ++I2) {
259 // Move the name and users over to the new version.
260 I->replaceAllUsesWith(I2);
Chris Lattner046800a2007-02-11 01:08:35 +0000261 I2->takeName(I);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000262 }
Duncan Sands110c8352007-12-21 19:16:16 +0000263
Chris Lattner4af90ab2006-09-18 07:02:31 +0000264 // Finally, nuke the old function.
265 Fn.eraseFromParent();
266 return true;
267}
268
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000269/// Convenience function that returns the number of return values. It returns 0
270/// for void functions and 1 for functions not returning a struct. It returns
271/// the number of struct elements for functions returning a struct.
272static unsigned NumRetVals(const Function *F) {
273 if (F->getReturnType() == Type::VoidTy)
274 return 0;
275 else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType()))
276 return STy->getNumElements();
277 else
278 return 1;
Chris Lattner08227e42003-06-17 22:21:05 +0000279}
280
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000281/// IsMaybeAlive - This checks Use for liveness. If Use is live, returns Live,
282/// else returns MaybeLive. Also, adds Use to MaybeLiveUses in the latter case.
283DAE::Liveness DAE::IsMaybeLive(RetOrArg Use, UseVector &MaybeLiveUses) {
284 // We're live if our use is already marked as live
285 if (LiveValues.count(Use))
Chris Lattner92044ce2006-06-27 21:05:04 +0000286 return Live;
Chris Lattner08227e42003-06-17 22:21:05 +0000287
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000288 // We're maybe live otherwise, but remember that we must become live if
289 // Use becomes live.
290 MaybeLiveUses.push_back(Use);
291 return MaybeLive;
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000292}
293
Evan Cheng9f99b7c2008-06-21 00:31:44 +0000294
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000295/// SurveyUse - This looks at a single use of an argument or return value
296/// and determines if it should be alive or not. Adds this use to MaybeLiveUses
297/// if it causes the used value to become MaybeAlive.
298///
299/// RetValNum is the return value number to use when this use is used in a
300/// return instruction. This is used in the recursion, you should always leave
301/// it at 0.
302DAE::Liveness DAE::SurveyUse(Value::use_iterator U, UseVector &MaybeLiveUses,
303 unsigned RetValNum) {
304 Value *V = *U;
305 if (ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
306 // The value is returned from another function. It's only live when the
307 // caller's return value is live
308 RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
309 // We might be live, depending on the liveness of Use
310 return IsMaybeLive(Use, MaybeLiveUses);
311 }
312 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
313 if (U.getOperandNo() != InsertValueInst::getAggregateOperandIndex()
314 && IV->hasIndices())
315 // The use we are examining is inserted into an aggregate. Our liveness
316 // depends on all uses of that aggregate, but if it is used as a return
317 // value, only index at which we were inserted counts.
318 RetValNum = *IV->idx_begin();
319
320 // Note that if we are used as the aggregate operand to the insertvalue,
321 // we don't change RetValNum, but do survey all our uses.
322
323 Liveness Result = MaybeLive;
324 for (Value::use_iterator I = IV->use_begin(),
325 E = V->use_end(); I != E; ++I) {
326 Result = SurveyUse(I, MaybeLiveUses, RetValNum);
327 if (Result == Live)
328 break;
329 }
330 return Result;
331 }
332 CallSite CS = CallSite::get(V);
333 if (CS.getInstruction()) {
334 Function *F = CS.getCalledFunction();
335 if (F) {
336 // Used in a direct call
337
338 // Check for vararg. Do - 1 to skip the first operand to call (the
339 // function itself).
340 if (U.getOperandNo() - 1 >= F->getFunctionType()->getNumParams())
341 // The value is passed in through a vararg! Must be live.
342 return Live;
343
344 // Value passed to a normal call. It's only live when the corresponding
345 // argument (operand number - 1 to skip the function pointer operand) to
346 // the called function turns out live
347 RetOrArg Use = CreateArg(F, U.getOperandNo() - 1);
348 return IsMaybeLive(Use, MaybeLiveUses);
349 } else {
350 // Used in any other way? Value must be live.
351 return Live;
352 }
353 }
354 // Used in any other way? Value must be live.
355 return Live;
356}
357
358/// SurveyUses - This looks at all the uses of the given return value
359/// (possibly a partial return value from a function returning a struct).
360/// Returns the Liveness deduced from the uses of this value.
361///
362/// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses.
363DAE::Liveness DAE::SurveyUses(Value *V, UseVector &MaybeLiveUses) {
364 // Assume it's dead (which will only hold if there are no uses at all..)
365 Liveness Result = MaybeLive;
366 // Check each use
367 for (Value::use_iterator I = V->use_begin(),
368 E = V->use_end(); I != E; ++I) {
369 Result = SurveyUse(I, MaybeLiveUses);
370 if (Result == Live)
371 break;
372 }
373 return Result;
374}
375
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000376// SurveyFunction - This performs the initial survey of the specified function,
377// checking out whether or not it uses any of its incoming arguments or whether
378// any callers use the return value. This fills in the
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000379// LiveValues set and Uses map.
Chris Lattner08227e42003-06-17 22:21:05 +0000380//
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000381// We consider arguments of non-internal functions to be intrinsically alive as
382// well as arguments to functions which have their "address taken".
383//
384void DAE::SurveyFunction(Function &F) {
385 bool FunctionIntrinsicallyLive = false;
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000386 unsigned RetCount = NumRetVals(&F);
387 // Assume all return values are dead
388 typedef SmallVector<Liveness, 5> RetVals;
389 RetVals RetValLiveness(RetCount, MaybeLive);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000390
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000391 // These vectors maps each return value to the uses that make it MaybeLive, so
392 // we can add those to the MaybeLiveRetVals list if the return value
393 // really turns out to be MaybeLive. Initializes to RetCount empty vectors
394 typedef SmallVector<UseVector, 5> RetUses;
395 // Intialized to a list of RetCount empty lists
396 RetUses MaybeLiveRetUses(RetCount);
397
398 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
399 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
400 if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
401 != F.getFunctionType()->getReturnType()) {
402 // We don't support old style multiple return values
403 FunctionIntrinsicallyLive = true;
404 break;
405 }
406
407 if (!F.hasInternalLinkage() && (!ShouldHackArguments() || F.isIntrinsic()))
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000408 FunctionIntrinsicallyLive = true;
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000409
410 if (!FunctionIntrinsicallyLive) {
411 DOUT << "DAE - Inspecting callers for fn: " << F.getName() << "\n";
412 // Keep track of the number of live retvals, so we can skip checks once all
413 // of them turn out to be live.
414 unsigned NumLiveRetVals = 0;
415 const Type *STy = dyn_cast<StructType>(F.getReturnType());
416 // Loop all uses of the function
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000417 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
Matthijs Kooijman41335412008-06-05 08:34:25 +0000418 // If the function is PASSED IN as an argument, its address has been taken
419 if (I.getOperandNo() != 0) {
420 FunctionIntrinsicallyLive = true;
421 break;
422 }
423
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000424 // If this use is anything other than a call site, the function is alive.
425 CallSite CS = CallSite::get(*I);
426 Instruction *TheCall = CS.getInstruction();
427 if (!TheCall) { // Not a direct call site?
428 FunctionIntrinsicallyLive = true;
429 break;
430 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000431
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000432 // If we end up here, we are looking at a direct call to our function.
Evan Cheng9f99b7c2008-06-21 00:31:44 +0000433
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000434 // Now, check how our return value(s) is/are used in this caller. Don't
435 // bother checking return values if all of them are live already
436 if (NumLiveRetVals != RetCount) {
437 if (STy) {
438 // Check all uses of the return value
439 for (Value::use_iterator I = TheCall->use_begin(),
440 E = TheCall->use_end(); I != E; ++I) {
441 ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(*I);
442 if (Ext && Ext->hasIndices()) {
443 // This use uses a part of our return value, survey the uses of
444 // that part and store the results for this index only.
445 unsigned Idx = *Ext->idx_begin();
446 if (RetValLiveness[Idx] != Live) {
447 RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
448 if (RetValLiveness[Idx] == Live)
449 NumLiveRetVals++;
450 }
451 } else {
452 // Used by something else than extractvalue. Mark all
453 // return values as live.
454 for (unsigned i = 0; i != RetCount; ++i )
455 RetValLiveness[i] = Live;
456 NumLiveRetVals = RetCount;
457 break;
458 }
459 }
460 } else {
461 // Single return value
462 RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]);
463 if (RetValLiveness[0] == Live)
464 NumLiveRetVals = RetCount;
465 }
466 }
467 }
468 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000469 if (FunctionIntrinsicallyLive) {
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000470 DOUT << "DAE - Intrinsically live fn: " << F.getName() << "\n";
471 // Mark all arguments as live
472 unsigned i = 0;
Chris Lattner19bdc032005-05-06 05:34:40 +0000473 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000474 AI != E; ++AI, ++i)
475 MarkLive(CreateArg(&F, i));
476 // Mark all return values as live
477 i = 0;
478 for (unsigned i = 0, e = RetValLiveness.size(); i != e; ++i)
479 MarkLive(CreateRet(&F, i));
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000480 return;
481 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000482
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000483 // Now we've inspected all callers, record the liveness of our return values.
484 for (unsigned i = 0, e = RetValLiveness.size(); i != e; ++i) {
485 RetOrArg Ret = CreateRet(&F, i);
486 // Mark the result down
487 MarkValue(Ret, RetValLiveness[i], MaybeLiveRetUses[i]);
Matthijs Kooijmanca85d652008-06-18 11:12:53 +0000488 }
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000489 DOUT << "DAE - Inspecting args for fn: " << F.getName() << "\n";
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000490
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000491 // Now, check all of our arguments
492 unsigned i = 0;
493 UseVector MaybeLiveArgUses;
494 for (Function::arg_iterator AI = F.arg_begin(),
495 E = F.arg_end(); AI != E; ++AI, ++i) {
496 // See what the effect of this use is (recording any uses that cause
497 // MaybeLive in MaybeLiveArgUses)
498 Liveness Result = SurveyUses(AI, MaybeLiveArgUses);
499 RetOrArg Arg = CreateArg(&F, i);
500 // Mark the result down
501 MarkValue(Arg, Result, MaybeLiveArgUses);
502 // Clear the vector again for the next iteration
503 MaybeLiveArgUses.clear();
504 }
505}
Owen Andersonbb3761c2008-06-18 17:32:16 +0000506
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000507/// MarkValue - This function marks the liveness of RA depending on L. If L is
508/// MaybeLive, it also records any uses in MaybeLiveUses such that RA will be
509/// marked live if any use in MaybeLiveUses gets marked live later on.
510void DAE::MarkValue(const RetOrArg &RA, Liveness L,
511 const UseVector &MaybeLiveUses) {
512 switch (L) {
513 case Live: MarkLive(RA); break;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000514 case MaybeLive:
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000515 {
516 // Note any uses of this value, so this return value can be
517 // marked live whenever one of the uses becomes live.
518 UseMap::iterator Where = Uses.begin();
519 for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
520 UE = MaybeLiveUses.end(); UI != UE; ++UI)
521 Where = Uses.insert(Where, UseMap::value_type(*UI, RA));
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000522 break;
523 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000524 }
525}
526
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000527/// MarkLive - Mark the given return value or argument as live. Additionally,
528/// mark any values that are used by this value (according to Uses) live as
529/// well.
530void DAE::MarkLive(RetOrArg RA) {
531 if (!LiveValues.insert(RA).second)
532 return; // We were already marked Live
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000533
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000534 if (RA.IsArg)
535 DOUT << "DAE - Marking argument " << RA.Idx << " to function "
536 << RA.F->getNameStart() << " live\n";
537 else
538 DOUT << "DAE - Marking return value " << RA.Idx << " of function "
539 << RA.F->getNameStart() << " live\n";
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000540
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000541 // We don't use upper_bound (or equal_range) here, because our recursive call
542 // to ourselves is likely to mark the upper_bound (which is the first value
543 // not belonging to RA) to become erased and the iterator invalidated.
544 UseMap::iterator Begin = Uses.lower_bound(RA);
545 UseMap::iterator E = Uses.end();
546 UseMap::iterator I;
547 for (I = Begin; I != E && I->first == RA; ++I)
548 MarkLive(I->second);
Owen Andersonbb3761c2008-06-18 17:32:16 +0000549
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000550 // Erase RA from the Uses map (from the lower bound to wherever we ended up
551 // after the loop).
552 Uses.erase(Begin, I);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000553}
554
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000555// RemoveDeadStuffFromFunction - Remove any arguments and return values from F
556// that are not in LiveValues. This function is a noop for any Function created
557// by this function before, or any function that was not inspected for liveness.
Chris Lattner08227e42003-06-17 22:21:05 +0000558// specified by the DeadArguments list. Transform the function and all of the
559// callees of the function to not have these arguments.
560//
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000561bool DAE::RemoveDeadStuffFromFunction(Function *F) {
562 // Quick exit path for external functions
563 if (!F->hasInternalLinkage() && (!ShouldHackArguments() || F->isIntrinsic()))
564 return false;
565
Chris Lattner08227e42003-06-17 22:21:05 +0000566 // Start by computing a new prototype for the function, which is the same as
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000567 // the old function, but has fewer arguments and a different return type.
Chris Lattner08227e42003-06-17 22:21:05 +0000568 const FunctionType *FTy = F->getFunctionType();
569 std::vector<const Type*> Params;
570
Duncan Sandsdc024672007-11-27 13:23:08 +0000571 // Set up to build a new list of parameter attributes
Chris Lattner58d74912008-03-12 17:45:29 +0000572 SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
573 const PAListPtr &PAL = F->getParamAttrs();
Chris Lattner08227e42003-06-17 22:21:05 +0000574
Duncan Sands110c8352007-12-21 19:16:16 +0000575 // The existing function return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +0000576 ParameterAttributes RAttrs = PAL.getParamAttrs(0);
Duncan Sands110c8352007-12-21 19:16:16 +0000577
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000578
579 // Find out the new return value
580
Duncan Sands110c8352007-12-21 19:16:16 +0000581 const Type *RetTy = FTy->getReturnType();
Matthijs Kooijmanea9e5162008-06-25 08:12:16 +0000582 const Type *NRetTy = NULL;
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000583 unsigned RetCount = NumRetVals(F);
584 // Explicitely track if anything changed, for debugging
585 bool Changed = false;
586 // -1 means unused, other numbers are the new index
587 SmallVector<int, 5> NewRetIdxs(RetCount, -1);
588 std::vector<const Type*> RetTypes;
589 if (RetTy != Type::VoidTy) {
590 const StructType *STy = dyn_cast<StructType>(RetTy);
591 if (STy)
592 // Look at each of the original return values individually
593 for (unsigned i = 0; i != RetCount; ++i) {
594 RetOrArg Ret = CreateRet(F, i);
595 if (LiveValues.erase(Ret)) {
596 RetTypes.push_back(STy->getElementType(i));
597 NewRetIdxs[i] = RetTypes.size() - 1;
598 } else {
599 ++NumRetValsEliminated;
600 DOUT << "DAE - Removing return value " << i << " from "
601 << F->getNameStart() << "\n";
602 Changed = true;
603 }
604 }
605 else
606 // We used to return a single value
607 if (LiveValues.erase(CreateRet(F, 0))) {
608 RetTypes.push_back(RetTy);
609 NewRetIdxs[0] = 0;
610 } else {
611 DOUT << "DAE - Removing return value from " << F->getNameStart()
612 << "\n";
613 ++NumRetValsEliminated;
614 Changed = true;
615 }
Duncan Sandsb58d2112008-06-25 16:31:18 +0000616 if (RetTypes.size() > 1 || (STy && STy->getNumElements()==RetTypes.size()))
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000617 // More than one return type? Return a struct with them. Also, if we used
618 // to return a struct and didn't change the number of return values,
Matthijs Kooijman177058b2008-06-25 08:10:21 +0000619 // return a struct again. This prevents changing {something} into something
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000620 // and {} into void.
621 // Make the new struct packed if we used to return a packed struct
622 // already.
623 NRetTy = StructType::get(RetTypes, STy->isPacked());
624 else if (RetTypes.size() == 1)
625 // One return type? Just a simple value then, but only if we didn't use to
626 // return a struct with that simple value before.
627 NRetTy = RetTypes.front();
628 else if (RetTypes.size() == 0)
Matthijs Kooijman177058b2008-06-25 08:10:21 +0000629 // No return types? Make it void, but only if we didn't use to return {}.
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000630 NRetTy = Type::VoidTy;
631 } else {
632 NRetTy = Type::VoidTy;
Duncan Sands110c8352007-12-21 19:16:16 +0000633 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000634
Matthijs Kooijmanea9e5162008-06-25 08:12:16 +0000635 assert(NRetTy && "No new return type found?");
636
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000637 // Remove any incompatible attributes
638 RAttrs &= ~ParamAttr::typeIncompatible(NRetTy);
Duncan Sands110c8352007-12-21 19:16:16 +0000639 if (RAttrs)
640 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000641
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000642 // Remember which arguments are still alive
643 SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
Duncan Sandsdc024672007-11-27 13:23:08 +0000644 // Construct the new parameter list from non-dead arguments. Also construct
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000645 // a new set of parameter attributes to correspond. Skip the first parameter
646 // attribute, since that belongs to the return value.
647 unsigned i = 0;
648 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
649 I != E; ++I, ++i) {
650 RetOrArg Arg = CreateArg(F, i);
651 if (LiveValues.erase(Arg)) {
Duncan Sandsdc024672007-11-27 13:23:08 +0000652 Params.push_back(I->getType());
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000653 ArgAlive[i] = true;
654
655 // Get the original parameter attributes (skipping the first one, that is
656 // for the return value
657 if (ParameterAttributes Attrs = PAL.getParamAttrs(i + 1))
Duncan Sands110c8352007-12-21 19:16:16 +0000658 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), Attrs));
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000659 } else {
660 ++NumArgumentsEliminated;
661 DOUT << "DAE - Removing argument " << i << " (" << I->getNameStart()
662 << ") from " << F->getNameStart() << "\n";
663 Changed = true;
Duncan Sandsdc024672007-11-27 13:23:08 +0000664 }
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000665 }
Duncan Sandsdc024672007-11-27 13:23:08 +0000666
667 // Reconstruct the ParamAttrsList based on the vector we constructed.
Chris Lattner58d74912008-03-12 17:45:29 +0000668 PAListPtr NewPAL = PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end());
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000669
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000670 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
671 // have zero fixed arguments.
672 //
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000673 // Not that we apply this hack for a vararg fuction that does not have any
674 // arguments anymore, but did have them before (so don't bother fixing
675 // functions that were already broken wrt CWriter).
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000676 bool ExtraArgHack = false;
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000677 if (Params.empty() && FTy->isVarArg() && FTy->getNumParams() != 0) {
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000678 ExtraArgHack = true;
Reid Spencerc5b206b2006-12-31 05:48:39 +0000679 Params.push_back(Type::Int32Ty);
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000680 }
681
Duncan Sandsdc024672007-11-27 13:23:08 +0000682 // Create the new function type based on the recomputed parameters.
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000683 FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
684
685 // No change?
686 if (NFTy == FTy)
687 return false;
688
689 // The function type is only allowed to be different if we actually left out
Matthijs Kooijman177058b2008-06-25 08:10:21 +0000690 // an argument or return value.
691 assert(Changed && "Function type changed while no arguments or return values"
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000692 "were removed!");
Matthijs Kooijman9cb6ec22008-06-20 14:28:52 +0000693
Chris Lattner08227e42003-06-17 22:21:05 +0000694 // Create the new function body and insert it into the module...
Gabor Greif051a9502008-04-06 20:25:17 +0000695 Function *NF = Function::Create(NFTy, F->getLinkage());
Duncan Sands28c3cff2008-05-26 19:58:59 +0000696 NF->copyAttributesFrom(F);
Chris Lattner58d74912008-03-12 17:45:29 +0000697 NF->setParamAttrs(NewPAL);
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000698 // Insert the new function before the old function, so we won't be processing
Matthijs Kooijman177058b2008-06-25 08:10:21 +0000699 // it again.
Chris Lattner08227e42003-06-17 22:21:05 +0000700 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner046800a2007-02-11 01:08:35 +0000701 NF->takeName(F);
Chris Lattner08227e42003-06-17 22:21:05 +0000702
703 // Loop over all of the callers of the function, transforming the call sites
704 // to pass in a smaller number of arguments into the new function.
705 //
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000706 std::vector<Value*> Args;
Chris Lattner08227e42003-06-17 22:21:05 +0000707 while (!F->use_empty()) {
708 CallSite CS = CallSite::get(F->use_back());
709 Instruction *Call = CS.getInstruction();
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000710
Duncan Sands110c8352007-12-21 19:16:16 +0000711 ParamAttrsVec.clear();
Chris Lattner58d74912008-03-12 17:45:29 +0000712 const PAListPtr &CallPAL = CS.getParamAttrs();
Duncan Sands110c8352007-12-21 19:16:16 +0000713
714 // The call return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +0000715 ParameterAttributes RAttrs = CallPAL.getParamAttrs(0);
Duncan Sands110c8352007-12-21 19:16:16 +0000716 // Adjust in case the function was changed to return void.
Duncan Sands6c3470e2008-01-07 17:16:06 +0000717 RAttrs &= ~ParamAttr::typeIncompatible(NF->getReturnType());
Duncan Sands110c8352007-12-21 19:16:16 +0000718 if (RAttrs)
719 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000720
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000721 // Declare these outside of the loops, so we can reuse them for the second
722 // loop, which loops the varargs
723 CallSite::arg_iterator I = CS.arg_begin();
724 unsigned i = 0;
725 // Loop over those operands, corresponding to the normal arguments to the
726 // original function, and add those that are still alive.
727 for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
728 if (ArgAlive[i]) {
729 Args.push_back(*I);
730 // Get original parameter attributes, but skip return attributes
731 if (ParameterAttributes Attrs = CallPAL.getParamAttrs(i + 1))
Duncan Sands110c8352007-12-21 19:16:16 +0000732 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
733 }
734
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000735 if (ExtraArgHack)
Reid Spencerc5b206b2006-12-31 05:48:39 +0000736 Args.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000737
Evan Chengb2fc2a32008-01-17 04:18:54 +0000738 // Push any varargs arguments on the list. Don't forget their attributes.
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000739 for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
740 Args.push_back(*I);
741 if (ParameterAttributes Attrs = CallPAL.getParamAttrs(i + 1))
Evan Chengb2fc2a32008-01-17 04:18:54 +0000742 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
743 }
744
745 // Reconstruct the ParamAttrsList based on the vector we constructed.
Chris Lattner58d74912008-03-12 17:45:29 +0000746 PAListPtr NewCallPAL = PAListPtr::get(ParamAttrsVec.begin(),
747 ParamAttrsVec.end());
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000748
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000749 Instruction *New;
750 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000751 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
752 Args.begin(), Args.end(), "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000753 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner58d74912008-03-12 17:45:29 +0000754 cast<InvokeInst>(New)->setParamAttrs(NewCallPAL);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000755 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000756 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000757 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner58d74912008-03-12 17:45:29 +0000758 cast<CallInst>(New)->setParamAttrs(NewCallPAL);
Chris Lattner1430ef12005-05-06 06:46:58 +0000759 if (cast<CallInst>(Call)->isTailCall())
760 cast<CallInst>(New)->setTailCall();
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000761 }
762 Args.clear();
763
764 if (!Call->use_empty()) {
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000765 if (New->getType() == Call->getType()) {
766 // Return type not changed? Just replace users then
Evan Cheng9f99b7c2008-06-21 00:31:44 +0000767 Call->replaceAllUsesWith(New);
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000768 New->takeName(Call);
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000769 } else if (New->getType() == Type::VoidTy) {
770 // Our return value has uses, but they will get removed later on.
771 // Replace by null for now.
772 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
773 } else {
774 assert(isa<StructType>(RetTy) && "Return type changed, but not into a"
775 "void. The old return type must have"
776 "been a struct!");
777 // The original return value was a struct, update all uses (which are
778 // all extractvalue instructions).
779 for (Value::use_iterator I = Call->use_begin(), E = Call->use_end();
780 I != E;) {
781 assert(isa<ExtractValueInst>(*I) && "Return value not only used by"
782 "extractvalue?");
783 ExtractValueInst *EV = cast<ExtractValueInst>(*I);
784 // Increment now, since we're about to throw away this use.
785 ++I;
786 assert(EV->hasIndices() && "Return value used by extractvalue without"
787 "indices?");
788 unsigned Idx = *EV->idx_begin();
789 if (NewRetIdxs[Idx] != -1) {
790 if (RetTypes.size() > 1) {
791 // We're still returning a struct, create a new extractvalue
792 // instruction with the first index updated
793 std::vector<unsigned> NewIdxs(EV->idx_begin(), EV->idx_end());
794 NewIdxs[0] = NewRetIdxs[Idx];
795 Value *NEV = ExtractValueInst::Create(New, NewIdxs.begin(),
796 NewIdxs.end(), "retval",
797 EV);
798 EV->replaceAllUsesWith(NEV);
799 EV->eraseFromParent();
800 } else {
801 // We are now only returning a simple value, remove the
802 // extractvalue
803 EV->replaceAllUsesWith(New);
804 EV->eraseFromParent();
805 }
806 } else {
807 // Value unused, replace uses by null for now, they will get removed
808 // later on
809 EV->replaceAllUsesWith(Constant::getNullValue(EV->getType()));
810 EV->eraseFromParent();
811 }
812 }
813 New->takeName(Call);
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000814 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000815 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000816
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000817 // Finally, remove the old call from the program, reducing the use-count of
818 // F.
Matthijs Kooijman494661c2008-05-30 12:35:46 +0000819 Call->eraseFromParent();
Chris Lattner08227e42003-06-17 22:21:05 +0000820 }
821
822 // Since we have now created the new function, splice the body of the old
823 // function right into the new function, leaving the old rotting hulk of the
824 // function empty.
825 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
826
827 // Loop over the argument list, transfering uses of the old arguments over to
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000828 // the new arguments, also transfering over the names as well.
829 i = 0;
Chris Lattner19bdc032005-05-06 05:34:40 +0000830 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000831 I2 = NF->arg_begin(); I != E; ++I, ++i)
832 if (ArgAlive[i]) {
Chris Lattner08227e42003-06-17 22:21:05 +0000833 // If this is a live argument, move the name and users over to the new
834 // version.
835 I->replaceAllUsesWith(I2);
Chris Lattner046800a2007-02-11 01:08:35 +0000836 I2->takeName(I);
Chris Lattner08227e42003-06-17 22:21:05 +0000837 ++I2;
838 } else {
839 // If this argument is dead, replace any uses of it with null constants
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000840 // (these are guaranteed to become unused later on)
Chris Lattner08227e42003-06-17 22:21:05 +0000841 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
Chris Lattner08227e42003-06-17 22:21:05 +0000842 }
843
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000844 // If we change the return value of the function we must rewrite any return
845 // instructions. Check this now.
846 if (F->getReturnType() != NF->getReturnType())
847 for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
848 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000849 Value *RetVal;
850
851 if (NFTy->getReturnType() == Type::VoidTy) {
852 RetVal = 0;
853 } else {
854 assert (isa<StructType>(RetTy));
855 // The original return value was a struct, insert
856 // extractvalue/insertvalue chains to extract only the values we need
857 // to return and insert them into our new result.
858 // This does generate messy code, but we'll let it to instcombine to
859 // clean that up
860 Value *OldRet = RI->getOperand(0);
861 // Start out building up our return value from undef
862 RetVal = llvm::UndefValue::get(NRetTy);
863 for (unsigned i = 0; i != RetCount; ++i)
864 if (NewRetIdxs[i] != -1) {
865 ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
866 "newret", RI);
867 if (RetTypes.size() > 1) {
868 // We're still returning a struct, so reinsert the value into
869 // our new return value at the new index
870
871 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
872 "oldret");
873 } else {
874 // We are now only returning a simple value, so just return the
875 // extracted value
876 RetVal = EV;
877 }
878 }
879 }
880 // Replace the return instruction with one returning the new return
881 // value (possibly 0 if we became void).
882 ReturnInst::Create(RetVal, RI);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000883 BB->getInstList().erase(RI);
884 }
885
Chris Lattner08227e42003-06-17 22:21:05 +0000886 // Now that the old function is dead, delete it.
Matthijs Kooijman494661c2008-05-30 12:35:46 +0000887 F->eraseFromParent();
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000888
889 return true;
Chris Lattner08227e42003-06-17 22:21:05 +0000890}
891
Chris Lattnerb12914b2004-09-20 04:48:05 +0000892bool DAE::runOnModule(Module &M) {
Chris Lattner701bc422007-11-15 06:10:55 +0000893 bool Changed = false;
894 // First pass: Do a simple check to see if any functions can have their "..."
895 // removed. We can do this if they never call va_start. This loop cannot be
896 // fused with the next loop, because deleting a function invalidates
897 // information computed while surveying other functions.
898 DOUT << "DAE - Deleting dead varargs\n";
899 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
900 Function &F = *I++;
901 if (F.getFunctionType()->isVarArg())
902 Changed |= DeleteDeadVarargs(F);
903 }
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000904
Chris Lattner701bc422007-11-15 06:10:55 +0000905 // Second phase:loop through the module, determining which arguments are live.
Chris Lattner08227e42003-06-17 22:21:05 +0000906 // We assume all arguments are dead unless proven otherwise (allowing us to
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000907 // determine that dead arguments passed into recursive functions are dead).
Chris Lattner08227e42003-06-17 22:21:05 +0000908 //
Bill Wendling0a81aac2006-11-26 10:02:32 +0000909 DOUT << "DAE - Determining liveness\n";
Chris Lattner701bc422007-11-15 06:10:55 +0000910 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
911 SurveyFunction(*I);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000912
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000913 // Now, remove all dead arguments and return values from each function in
914 // turn
915 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
916 // Increment now, because the function will probably get removed (ie
917 // replaced by a new one)
918 Function *F = I++;
919 Changed |= RemoveDeadStuffFromFunction(F);
Chris Lattner08227e42003-06-17 22:21:05 +0000920 }
921
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000922 return Changed;
Chris Lattner08227e42003-06-17 22:21:05 +0000923}