blob: e742f924e9881ac7708451bb19c283a377552182 [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 Kooijmanc95e44b2008-06-20 09:36:16 +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 Kooijmanc95e44b2008-06-20 09:36:16 +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 Kooijmanc95e44b2008-06-20 09:36:16 +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 {
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +000051 RetOrArg(const Function* F, unsigned Idx, bool IsArg) : F(F), Idx(Idx),
52 IsArg(IsArg) {}
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +000053 const Function *F;
54 unsigned Idx;
55 bool IsArg;
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +000056
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +000057 /// 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 };
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +000072
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000073 /// Liveness enum - During our initial pass over the program, we determine
74 /// that things are either definately alive, definately dead, or in need of
75 /// interprocedural analysis (MaybeLive).
76 ///
77 enum Liveness { Live, MaybeLive, Dead };
78
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +000079 /// Convenience wrapper
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +000080 RetOrArg CreateRet(const Function *F, unsigned Idx) {
81 return RetOrArg(F, Idx, false);
82 }
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +000083 /// Convenience wrapper
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +000084 RetOrArg CreateArg(const Function *F, unsigned Idx) {
85 return RetOrArg(F, Idx, true);
86 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000087
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +000088 typedef std::multimap<RetOrArg, RetOrArg> UseMap;
89 /// This map maps a return value or argument to all return values or
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +000090 /// arguments it uses.
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +000091 /// For example (indices are left out for clarity):
92 /// - Uses[ret F] = ret G
93 /// This means that F calls G, and F returns the value returned by G.
94 /// - Uses[arg F] = ret G
95 /// This means that some function calls G and passes its result as an
96 /// argument to F.
97 /// - Uses[ret F] = arg F
98 /// This means that F returns one of its own arguments.
99 /// - Uses[arg F] = arg G
100 /// This means that G calls F and passes one of its own (G's) arguments
101 /// directly to F.
102 UseMap Uses;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000103
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000104 typedef std::set<RetOrArg> LiveSet;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000105
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000106 /// This set contains all values that have been determined to be live
107 LiveSet LiveValues;
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000108
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000109 typedef SmallVector<RetOrArg, 5> UseVector;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000110
111 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000112 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +0000113 DAE() : ModulePass((intptr_t)&ID) {}
Chris Lattnerb12914b2004-09-20 04:48:05 +0000114 bool runOnModule(Module &M);
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000115
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000116 virtual bool ShouldHackArguments() const { return false; }
117
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000118 private:
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000119 Liveness IsMaybeLive(RetOrArg Use, UseVector &MaybeLiveUses);
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000120 Liveness SurveyUse(Value::use_iterator U, UseVector &MaybeLiveUses,
121 unsigned RetValNum = 0);
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000122 Liveness SurveyUses(Value *V, UseVector &MaybeLiveUses);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000123
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000124 void SurveyFunction(Function &F);
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000125 void MarkValue(const RetOrArg &RA, Liveness L,
126 const UseVector &MaybeLiveUses);
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000127 void MarkLive(RetOrArg RA);
128 bool RemoveDeadStuffFromFunction(Function *F);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000129 bool DeleteDeadVarargs(Function &Fn);
Chris Lattner08227e42003-06-17 22:21:05 +0000130 };
Dan Gohman844731a2008-05-13 00:00:25 +0000131}
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000132
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000133
Dan Gohman844731a2008-05-13 00:00:25 +0000134char DAE::ID = 0;
135static RegisterPass<DAE>
136X("deadargelim", "Dead Argument Elimination");
137
138namespace {
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000139 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
140 /// deletes arguments to functions which are external. This is only for use
141 /// by bugpoint.
142 struct DAH : public DAE {
Devang Patel19974732007-05-03 01:11:54 +0000143 static char ID;
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000144 virtual bool ShouldHackArguments() const { return true; }
145 };
Chris Lattner08227e42003-06-17 22:21:05 +0000146}
147
Dan Gohman844731a2008-05-13 00:00:25 +0000148char DAH::ID = 0;
149static RegisterPass<DAH>
150Y("deadarghaX0r", "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)");
151
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000152/// createDeadArgEliminationPass - This pass removes arguments from functions
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000153/// which are not used by the body of the function.
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000154///
Chris Lattnerb12914b2004-09-20 04:48:05 +0000155ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
156ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
Chris Lattner08227e42003-06-17 22:21:05 +0000157
Chris Lattner4af90ab2006-09-18 07:02:31 +0000158/// DeleteDeadVarargs - If this is an function that takes a ... list, and if
159/// llvm.vastart is never called, the varargs list is dead for the function.
160bool DAE::DeleteDeadVarargs(Function &Fn) {
161 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
Reid Spencer5cbf9852007-01-30 20:08:39 +0000162 if (Fn.isDeclaration() || !Fn.hasInternalLinkage()) return false;
Duncan Sands110c8352007-12-21 19:16:16 +0000163
Chris Lattner4af90ab2006-09-18 07:02:31 +0000164 // Ensure that the function is only directly called.
165 for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end(); I != E; ++I) {
166 // If this use is anything other than a call site, give up.
167 CallSite CS = CallSite::get(*I);
168 Instruction *TheCall = CS.getInstruction();
169 if (!TheCall) return false; // Not a direct call site?
Duncan Sands110c8352007-12-21 19:16:16 +0000170
Chris Lattner4af90ab2006-09-18 07:02:31 +0000171 // The addr of this function is passed to the call.
172 if (I.getOperandNo() != 0) return false;
173 }
Duncan Sands110c8352007-12-21 19:16:16 +0000174
Chris Lattner4af90ab2006-09-18 07:02:31 +0000175 // Okay, we know we can transform this function if safe. Scan its body
176 // looking for calls to llvm.vastart.
177 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
178 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
179 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
180 if (II->getIntrinsicID() == Intrinsic::vastart)
181 return false;
182 }
183 }
184 }
Duncan Sands110c8352007-12-21 19:16:16 +0000185
Chris Lattner4af90ab2006-09-18 07:02:31 +0000186 // If we get here, there are no calls to llvm.vastart in the function body,
187 // remove the "..." and adjust all the calls.
Duncan Sands110c8352007-12-21 19:16:16 +0000188
Chris Lattner4af90ab2006-09-18 07:02:31 +0000189 // Start by computing a new prototype for the function, which is the same as
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000190 // the old function, but doesn't have isVarArg set.
Chris Lattner4af90ab2006-09-18 07:02:31 +0000191 const FunctionType *FTy = Fn.getFunctionType();
192 std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
193 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), Params, false);
194 unsigned NumArgs = Params.size();
Duncan Sands110c8352007-12-21 19:16:16 +0000195
Chris Lattner4af90ab2006-09-18 07:02:31 +0000196 // Create the new function body and insert it into the module...
Gabor Greif051a9502008-04-06 20:25:17 +0000197 Function *NF = Function::Create(NFTy, Fn.getLinkage());
Duncan Sands28c3cff2008-05-26 19:58:59 +0000198 NF->copyAttributesFrom(&Fn);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000199 Fn.getParent()->getFunctionList().insert(&Fn, NF);
Chris Lattner046800a2007-02-11 01:08:35 +0000200 NF->takeName(&Fn);
Duncan Sands110c8352007-12-21 19:16:16 +0000201
Chris Lattner4af90ab2006-09-18 07:02:31 +0000202 // Loop over all of the callers of the function, transforming the call sites
203 // to pass in a smaller number of arguments into the new function.
204 //
205 std::vector<Value*> Args;
206 while (!Fn.use_empty()) {
207 CallSite CS = CallSite::get(Fn.use_back());
208 Instruction *Call = CS.getInstruction();
Duncan Sands110c8352007-12-21 19:16:16 +0000209
Chris Lattnera0bc7fc2007-10-18 18:49:29 +0000210 // Pass all the same arguments.
Chris Lattner4af90ab2006-09-18 07:02:31 +0000211 Args.assign(CS.arg_begin(), CS.arg_begin()+NumArgs);
Duncan Sands110c8352007-12-21 19:16:16 +0000212
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000213 // Drop any attributes that were on the vararg arguments.
Chris Lattner58d74912008-03-12 17:45:29 +0000214 PAListPtr PAL = CS.getParamAttrs();
215 if (!PAL.isEmpty() && PAL.getSlot(PAL.getNumSlots() - 1).Index > NumArgs) {
216 SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
217 for (unsigned i = 0; PAL.getSlot(i).Index <= NumArgs; ++i)
218 ParamAttrsVec.push_back(PAL.getSlot(i));
219 PAL = PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end());
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000220 }
221
Chris Lattner4af90ab2006-09-18 07:02:31 +0000222 Instruction *New;
223 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000224 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
225 Args.begin(), Args.end(), "", Call);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000226 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000227 cast<InvokeInst>(New)->setParamAttrs(PAL);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000228 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000229 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000230 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000231 cast<CallInst>(New)->setParamAttrs(PAL);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000232 if (cast<CallInst>(Call)->isTailCall())
233 cast<CallInst>(New)->setTailCall();
234 }
235 Args.clear();
Duncan Sands110c8352007-12-21 19:16:16 +0000236
Chris Lattner4af90ab2006-09-18 07:02:31 +0000237 if (!Call->use_empty())
Chris Lattnera0bc7fc2007-10-18 18:49:29 +0000238 Call->replaceAllUsesWith(New);
Duncan Sands110c8352007-12-21 19:16:16 +0000239
Chris Lattner046800a2007-02-11 01:08:35 +0000240 New->takeName(Call);
Duncan Sands110c8352007-12-21 19:16:16 +0000241
Chris Lattner4af90ab2006-09-18 07:02:31 +0000242 // Finally, remove the old call from the program, reducing the use-count of
243 // F.
Chris Lattnera0bc7fc2007-10-18 18:49:29 +0000244 Call->eraseFromParent();
Chris Lattner4af90ab2006-09-18 07:02:31 +0000245 }
Duncan Sands110c8352007-12-21 19:16:16 +0000246
Chris Lattner4af90ab2006-09-18 07:02:31 +0000247 // Since we have now created the new function, splice the body of the old
248 // function right into the new function, leaving the old rotting hulk of the
249 // function empty.
250 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
Duncan Sands110c8352007-12-21 19:16:16 +0000251
Chris Lattner4af90ab2006-09-18 07:02:31 +0000252 // Loop over the argument list, transfering uses of the old arguments over to
253 // the new arguments, also transfering over the names as well. While we're at
254 // it, remove the dead arguments from the DeadArguments list.
255 //
256 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
257 I2 = NF->arg_begin(); I != E; ++I, ++I2) {
258 // Move the name and users over to the new version.
259 I->replaceAllUsesWith(I2);
Chris Lattner046800a2007-02-11 01:08:35 +0000260 I2->takeName(I);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000261 }
Duncan Sands110c8352007-12-21 19:16:16 +0000262
Chris Lattner4af90ab2006-09-18 07:02:31 +0000263 // Finally, nuke the old function.
264 Fn.eraseFromParent();
265 return true;
266}
267
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000268/// Convenience function that returns the number of return values. It returns 0
269/// for void functions and 1 for functions not returning a struct. It returns
270/// the number of struct elements for functions returning a struct.
271static unsigned NumRetVals(const Function *F) {
272 if (F->getReturnType() == Type::VoidTy)
273 return 0;
274 else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType()))
275 return STy->getNumElements();
276 else
277 return 1;
Chris Lattner08227e42003-06-17 22:21:05 +0000278}
279
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000280/// IsMaybeAlive - This checks Use for liveness. If Use is live, returns Live,
281/// else returns MaybeLive. Also, adds Use to MaybeLiveUses in the latter case.
282DAE::Liveness DAE::IsMaybeLive(RetOrArg Use, UseVector &MaybeLiveUses) {
283 // We're live if our use is already marked as live
284 if (LiveValues.count(Use))
Chris Lattner92044ce2006-06-27 21:05:04 +0000285 return Live;
Chris Lattner08227e42003-06-17 22:21:05 +0000286
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000287 // We're maybe live otherwise, but remember that we must become live if
288 // Use becomes live.
289 MaybeLiveUses.push_back(Use);
290 return MaybeLive;
Matthijs Kooijmanca85d652008-06-18 11:12:53 +0000291}
292
Owen Andersonbb3761c2008-06-18 17:32:16 +0000293
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000294/// SurveyUse - This looks at a single use of an argument or return value
295/// and determines if it should be alive or not. Adds this use to MaybeLiveUses
296/// if it causes the used value to become MaybeAlive.
297///
298/// RetValNum is the return value number to use when this use is used in a
299/// return instruction. This is used in the recursion, you should always leave
300/// it at 0.
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000301DAE::Liveness DAE::SurveyUse(Value::use_iterator U, UseVector &MaybeLiveUses,
302 unsigned RetValNum) {
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000303 Value *V = *U;
304 if (ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
305 // The value is returned from another function. It's only live when the
306 // caller's return value is live
307 RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
308 // We might be live, depending on the liveness of Use
309 return IsMaybeLive(Use, MaybeLiveUses);
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000310 }
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000311 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000312 if (U.getOperandNo() != InsertValueInst::getAggregateOperandIndex()
313 && IV->hasIndices())
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000314 // The use we are examining is inserted into an aggregate. Our liveness
315 // depends on all uses of that aggregate, but if it is used as a return
316 // value, only index at which we were inserted counts.
317 RetValNum = *IV->idx_begin();
318
319 // Note that if we are used as the aggregate operand to the insertvalue,
320 // we don't change RetValNum, but do survey all our uses.
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000321
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000322 Liveness Result = Dead;
323 for (Value::use_iterator I = IV->use_begin(),
324 E = V->use_end(); I != E; ++I) {
325 Result = SurveyUse(I, MaybeLiveUses, RetValNum);
326 if (Result == Live)
327 break;
328 }
329 return Result;
330 }
331 CallSite CS = CallSite::get(V);
332 if (CS.getInstruction()) {
333 Function *F = CS.getCalledFunction();
334 if (F) {
335 // Used in a direct call
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000336
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000337 // Check for vararg. Do - 1 to skip the first operand to call (the
338 // function itself).
339 if (U.getOperandNo() - 1 >= F->getFunctionType()->getNumParams())
340 // The value is passed in through a vararg! Must be live.
341 return Live;
342
343 // Value passed to a normal call. It's only live when the corresponding
344 // argument (operand number - 1 to skip the function pointer operand) to
345 // the called function turns out live
346 RetOrArg Use = CreateArg(F, U.getOperandNo() - 1);
347 return IsMaybeLive(Use, MaybeLiveUses);
348 } else {
349 // Used in any other way? Value must be live.
350 return Live;
351 }
352 }
353 // Used in any other way? Value must be live.
354 return Live;
355}
356
357/// SurveyUses - This looks at all the uses of the given return value
358/// (possibly a partial return value from a function returning a struct).
359/// Returns the Liveness deduced from the uses of this value.
360///
361/// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses.
362DAE::Liveness DAE::SurveyUses(Value *V, UseVector &MaybeLiveUses) {
363 // Assume it's dead (which will only hold if there are no uses at all..)
364 Liveness Result = Dead;
365 // Check each use
366 for (Value::use_iterator I = V->use_begin(),
367 E = V->use_end(); I != E; ++I) {
368 Result = SurveyUse(I, MaybeLiveUses);
369 if (Result == Live)
370 break;
371 }
372 return Result;
373}
374
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000375// SurveyFunction - This performs the initial survey of the specified function,
376// checking out whether or not it uses any of its incoming arguments or whether
377// any callers use the return value. This fills in the
378// (Dead|MaybeLive|Live)(Arguments|RetVal) sets.
Chris Lattner08227e42003-06-17 22:21:05 +0000379//
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000380// We consider arguments of non-internal functions to be intrinsically alive as
381// well as arguments to functions which have their "address taken".
382//
383void DAE::SurveyFunction(Function &F) {
384 bool FunctionIntrinsicallyLive = false;
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000385 unsigned RetCount = NumRetVals(&F);
386 // Assume all return values are dead
387 typedef SmallVector<Liveness, 5> RetVals;
388 RetVals RetValLiveness(RetCount, Dead);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000389
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000390 // These vectors maps each return value to the uses that make it MaybeLive, so
391 // we can add those to the MaybeLiveRetVals list if the return value
392 // really turns out to be MaybeLive. Initializes to RetCount empty vectors
393 typedef SmallVector<UseVector, 5> RetUses;
394 // Intialized to a list of RetCount empty lists
395 RetUses MaybeLiveRetUses(RetCount);
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000396
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000397 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
398 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000399 if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
400 != F.getFunctionType()->getReturnType()) {
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000401 // We don't support old style multiple return values
402 FunctionIntrinsicallyLive = true;
403 break;
404 }
405
406 if (!F.hasInternalLinkage() && (!ShouldHackArguments() || F.isIntrinsic()))
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000407 FunctionIntrinsicallyLive = true;
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000408
409 if (!FunctionIntrinsicallyLive) {
410 DOUT << "DAE - Inspecting callers for fn: " << F.getName() << "\n";
411 // Keep track of the number of live retvals, so we can skip checks once all
412 // of them turn out to be live.
413 unsigned NumLiveRetVals = 0;
414 const Type *STy = dyn_cast<StructType>(F.getReturnType());
415 // Loop all uses of the function
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000416 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
Matthijs Kooijman41335412008-06-05 08:34:25 +0000417 // If the function is PASSED IN as an argument, its address has been taken
418 if (I.getOperandNo() != 0) {
419 FunctionIntrinsicallyLive = true;
420 break;
421 }
422
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000423 // If this use is anything other than a call site, the function is alive.
424 CallSite CS = CallSite::get(*I);
425 Instruction *TheCall = CS.getInstruction();
426 if (!TheCall) { // Not a direct call site?
427 FunctionIntrinsicallyLive = true;
428 break;
429 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000430
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000431 // If we end up here, we are looking at a direct call to our function.
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000432
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000433 // Now, check how our return value(s) is/are used in this caller. Don't
434 // bother checking return values if all of them are live already
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000435 if (NumLiveRetVals != RetCount) {
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000436 if (STy) {
437 // Check all uses of the return value
438 for (Value::use_iterator I = TheCall->use_begin(),
439 E = TheCall->use_end(); I != E; ++I) {
440 ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(*I);
441 if (Ext && Ext->hasIndices()) {
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000442 // This use uses a part of our return value, survey the uses of
443 // that part and store the results for this index only.
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000444 unsigned Idx = *Ext->idx_begin();
445 if (RetValLiveness[Idx] != Live) {
446 RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
447 if (RetValLiveness[Idx] == Live)
448 NumLiveRetVals++;
449 }
Owen Andersonbb3761c2008-06-18 17:32:16 +0000450 } else {
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000451 // Used by something else than extractvalue. Mark all
452 // return values as live.
453 for (unsigned i = 0; i != RetCount; ++i )
454 RetValLiveness[i] = Live;
455 NumLiveRetVals = RetCount;
456 break;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000457 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000458 }
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000459 } else {
460 // Single return value
461 RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]);
462 if (RetValLiveness[0] == Live)
463 NumLiveRetVals = RetCount;
464 }
465 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000466 }
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000467 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000468 if (FunctionIntrinsicallyLive) {
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000469 DOUT << "DAE - Intrinsically live fn: " << F.getName() << "\n";
470 // Mark all arguments as live
471 unsigned i = 0;
Chris Lattner19bdc032005-05-06 05:34:40 +0000472 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000473 AI != E; ++AI, ++i)
474 MarkLive(CreateArg(&F, i));
475 // Mark all return values as live
476 i = 0;
477 for (unsigned i = 0, e = RetValLiveness.size(); i != e; ++i)
478 MarkLive(CreateRet(&F, i));
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000479 return;
480 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000481
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000482 // Now we've inspected all callers, record the liveness of our return values.
483 for (unsigned i = 0, e = RetValLiveness.size(); i != e; ++i) {
484 RetOrArg Ret = CreateRet(&F, i);
485 // Mark the result down
486 MarkValue(Ret, RetValLiveness[i], MaybeLiveRetUses[i]);
Matthijs Kooijmanca85d652008-06-18 11:12:53 +0000487 }
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000488 DOUT << "DAE - Inspecting args for fn: " << F.getName() << "\n";
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000489
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000490 // Now, check all of our arguments
491 unsigned i = 0;
492 UseVector MaybeLiveArgUses;
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000493 for (Function::arg_iterator AI = F.arg_begin(),
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000494 E = F.arg_end(); AI != E; ++AI, ++i) {
495 // See what the effect of this use is (recording any uses that cause
496 // MaybeLive in MaybeLiveArgUses)
497 Liveness Result = SurveyUses(AI, MaybeLiveArgUses);
498 RetOrArg Arg = CreateArg(&F, i);
499 // Mark the result down
500 MarkValue(Arg, Result, MaybeLiveArgUses);
501 // Clear the vector again for the next iteration
502 MaybeLiveArgUses.clear();
503 }
504}
Owen Andersonbb3761c2008-06-18 17:32:16 +0000505
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000506/// MarkValue - This function marks the liveness of RA depending on L. If L is
507/// MaybeLive, it also records any uses in MaybeLiveUses such that RA will be
508/// marked live if any use in MaybeLiveUses gets marked live later on.
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000509void DAE::MarkValue(const RetOrArg &RA, Liveness L,
510 const UseVector &MaybeLiveUses) {
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000511 switch (L) {
512 case Live: MarkLive(RA); break;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000513 case MaybeLive:
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000514 {
515 // Note any uses of this value, so this return value can be
516 // marked live whenever one of the uses becomes live.
517 UseMap::iterator Where = Uses.begin();
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000518 for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000519 UE = MaybeLiveUses.end(); UI != UE; ++UI)
520 Where = Uses.insert(Where, UseMap::value_type(*UI, RA));
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000521 break;
522 }
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000523 case Dead: break;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000524 }
525}
526
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +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 Kooijmanc95e44b2008-06-20 09:36:16 +0000534 if (RA.IsArg)
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000535 DOUT << "DAE - Marking argument " << RA.Idx << " to function "
536 << RA.F->getNameStart() << " live\n";
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000537 else
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000538 DOUT << "DAE - Marking return value " << RA.Idx << " of function "
539 << RA.F->getNameStart() << " live\n";
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000540
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +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 Kooijmanc95e44b2008-06-20 09:36:16 +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 Kooijmanc95e44b2008-06-20 09:36:16 +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 Kooijmanc95e44b2008-06-20 09:36:16 +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 Kooijmanc95e44b2008-06-20 09:36:16 +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 Kooijman7e43b3b2008-06-20 15:34:07 +0000578
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000579 // Find out the new return value
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000580
Duncan Sands110c8352007-12-21 19:16:16 +0000581 const Type *RetTy = FTy->getReturnType();
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000582 const Type *NRetTy;
583 unsigned RetCount = NumRetVals(F);
Matthijs Kooijman9cb6ec22008-06-20 14:28:52 +0000584 // Explicitely track if anything changed, for debugging
585 bool Changed = false;
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000586 // -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;
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000600 DOUT << "DAE - Removing return value " << i << " from "
601 << F->getNameStart() << "\n";
Matthijs Kooijman9cb6ec22008-06-20 14:28:52 +0000602 Changed = true;
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000603 }
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 {
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000611 DOUT << "DAE - Removing return value from " << F->getNameStart()
612 << "\n";
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000613 ++NumRetValsEliminated;
Matthijs Kooijman9cb6ec22008-06-20 14:28:52 +0000614 Changed = true;
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000615 }
616 if (RetTypes.size() > 1 || STy && STy->getNumElements() == RetTypes.size())
Matthijs Kooijman03d18562008-06-20 15:16:45 +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,
619 // return a struct again. This prevents chaning {something} into something
620 // and {} into void.
621 // Make the new struct packed if we used to return a packed struct
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000622 // already.
Matthijs Kooijman03d18562008-06-20 15:16:45 +0000623 NRetTy = StructType::get(RetTypes, STy->isPacked());
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000624 else if (RetTypes.size() == 1)
Matthijs Kooijman03d18562008-06-20 15:16:45 +0000625 // 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.
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000627 NRetTy = RetTypes.front();
Matthijs Kooijman03d18562008-06-20 15:16:45 +0000628 else if (RetTypes.size() == 0)
629 // No return types? Make it void, but only if we didn't use to return {}
630 NRetTy = Type::VoidTy;
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000631 } else {
632 NRetTy = Type::VoidTy;
Duncan Sands110c8352007-12-21 19:16:16 +0000633 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000634
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000635 // Remove any incompatible attributes
636 RAttrs &= ~ParamAttr::typeIncompatible(NRetTy);
Duncan Sands110c8352007-12-21 19:16:16 +0000637 if (RAttrs)
638 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000639
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000640 // Remember which arguments are still alive
641 SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
Duncan Sandsdc024672007-11-27 13:23:08 +0000642 // Construct the new parameter list from non-dead arguments. Also construct
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000643 // a new set of parameter attributes to correspond. Skip the first parameter
644 // attribute, since that belongs to the return value.
645 unsigned i = 0;
646 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
647 I != E; ++I, ++i) {
648 RetOrArg Arg = CreateArg(F, i);
649 if (LiveValues.erase(Arg)) {
Duncan Sandsdc024672007-11-27 13:23:08 +0000650 Params.push_back(I->getType());
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000651 ArgAlive[i] = true;
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000652
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000653 // Get the original parameter attributes (skipping the first one, that is
654 // for the return value
655 if (ParameterAttributes Attrs = PAL.getParamAttrs(i + 1))
Duncan Sands110c8352007-12-21 19:16:16 +0000656 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), Attrs));
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000657 } else {
658 ++NumArgumentsEliminated;
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000659 DOUT << "DAE - Removing argument " << i << " (" << I->getNameStart()
660 << ") from " << F->getNameStart() << "\n";
Matthijs Kooijman9cb6ec22008-06-20 14:28:52 +0000661 Changed = true;
Duncan Sandsdc024672007-11-27 13:23:08 +0000662 }
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000663 }
Duncan Sandsdc024672007-11-27 13:23:08 +0000664
665 // Reconstruct the ParamAttrsList based on the vector we constructed.
Chris Lattner58d74912008-03-12 17:45:29 +0000666 PAListPtr NewPAL = PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end());
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000667
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000668 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
669 // have zero fixed arguments.
670 //
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000671 // Not that we apply this hack for a vararg fuction that does not have any
672 // arguments anymore, but did have them before (so don't bother fixing
673 // functions that were already broken wrt CWriter).
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000674 bool ExtraArgHack = false;
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000675 if (Params.empty() && FTy->isVarArg() && FTy->getNumParams() != 0) {
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000676 ExtraArgHack = true;
Reid Spencerc5b206b2006-12-31 05:48:39 +0000677 Params.push_back(Type::Int32Ty);
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000678 }
679
Duncan Sandsdc024672007-11-27 13:23:08 +0000680 // Create the new function type based on the recomputed parameters.
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000681 FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000682
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000683 // No change?
684 if (NFTy == FTy)
685 return false;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000686
Matthijs Kooijman9cb6ec22008-06-20 14:28:52 +0000687 // The function type is only allowed to be different if we actually left out
688 // an argument or return value
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000689 assert(Changed && "Function type changed while no arguments or retrurn values"
690 "were removed!");
Matthijs Kooijman9cb6ec22008-06-20 14:28:52 +0000691
Chris Lattner08227e42003-06-17 22:21:05 +0000692 // Create the new function body and insert it into the module...
Gabor Greif051a9502008-04-06 20:25:17 +0000693 Function *NF = Function::Create(NFTy, F->getLinkage());
Duncan Sands28c3cff2008-05-26 19:58:59 +0000694 NF->copyAttributesFrom(F);
Chris Lattner58d74912008-03-12 17:45:29 +0000695 NF->setParamAttrs(NewPAL);
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000696 // Insert the new function before the old function, so we won't be processing
697 // it again
Chris Lattner08227e42003-06-17 22:21:05 +0000698 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner046800a2007-02-11 01:08:35 +0000699 NF->takeName(F);
Chris Lattner08227e42003-06-17 22:21:05 +0000700
701 // Loop over all of the callers of the function, transforming the call sites
702 // to pass in a smaller number of arguments into the new function.
703 //
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000704 std::vector<Value*> Args;
Chris Lattner08227e42003-06-17 22:21:05 +0000705 while (!F->use_empty()) {
706 CallSite CS = CallSite::get(F->use_back());
707 Instruction *Call = CS.getInstruction();
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000708
Duncan Sands110c8352007-12-21 19:16:16 +0000709 ParamAttrsVec.clear();
Chris Lattner58d74912008-03-12 17:45:29 +0000710 const PAListPtr &CallPAL = CS.getParamAttrs();
Duncan Sands110c8352007-12-21 19:16:16 +0000711
712 // The call return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +0000713 ParameterAttributes RAttrs = CallPAL.getParamAttrs(0);
Duncan Sands110c8352007-12-21 19:16:16 +0000714 // Adjust in case the function was changed to return void.
Duncan Sands6c3470e2008-01-07 17:16:06 +0000715 RAttrs &= ~ParamAttr::typeIncompatible(NF->getReturnType());
Duncan Sands110c8352007-12-21 19:16:16 +0000716 if (RAttrs)
717 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000718
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000719 // Declare these outside of the loops, so we can reuse them for the second
720 // loop, which loops the varargs
721 CallSite::arg_iterator I = CS.arg_begin();
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000722 unsigned i = 0;
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000723 // Loop over those operands, corresponding to the normal arguments to the
724 // original function, and add those that are still alive.
725 for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
726 if (ArgAlive[i]) {
727 Args.push_back(*I);
728 // Get original parameter attributes, but skip return attributes
729 if (ParameterAttributes Attrs = CallPAL.getParamAttrs(i + 1))
Duncan Sands110c8352007-12-21 19:16:16 +0000730 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
731 }
732
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000733 if (ExtraArgHack)
Reid Spencerc5b206b2006-12-31 05:48:39 +0000734 Args.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000735
Evan Chengb2fc2a32008-01-17 04:18:54 +0000736 // Push any varargs arguments on the list. Don't forget their attributes.
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000737 for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
738 Args.push_back(*I);
739 if (ParameterAttributes Attrs = CallPAL.getParamAttrs(i + 1))
Evan Chengb2fc2a32008-01-17 04:18:54 +0000740 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
741 }
742
743 // Reconstruct the ParamAttrsList based on the vector we constructed.
Chris Lattner58d74912008-03-12 17:45:29 +0000744 PAListPtr NewCallPAL = PAListPtr::get(ParamAttrsVec.begin(),
745 ParamAttrsVec.end());
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000746
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000747 Instruction *New;
748 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000749 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
750 Args.begin(), Args.end(), "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000751 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner58d74912008-03-12 17:45:29 +0000752 cast<InvokeInst>(New)->setParamAttrs(NewCallPAL);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000753 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000754 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000755 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner58d74912008-03-12 17:45:29 +0000756 cast<CallInst>(New)->setParamAttrs(NewCallPAL);
Chris Lattner1430ef12005-05-06 06:46:58 +0000757 if (cast<CallInst>(Call)->isTailCall())
758 cast<CallInst>(New)->setTailCall();
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000759 }
760 Args.clear();
761
762 if (!Call->use_empty()) {
Matthijs Kooijmandf0891d2008-06-20 15:25:43 +0000763 if (New->getType() == Call->getType()) {
764 // Return type not changed? Just replace users then
765 Call->replaceAllUsesWith(New);
766 New->takeName(Call);
767 } else if (New->getType() == Type::VoidTy) {
768 // Our return value has uses, but they will get removed later on.
769 // Replace by null for now.
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000770 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
Matthijs Kooijmandf0891d2008-06-20 15:25:43 +0000771 } else {
772 assert(isa<StructType>(RetTy) && "Return type changed, but not into a"
773 "void. The old return type must have"
774 "been a struct!");
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000775 // The original return value was a struct, update all uses (which are
776 // all extractvalue instructions).
777 for (Value::use_iterator I = Call->use_begin(), E = Call->use_end();
778 I != E;) {
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000779 assert(isa<ExtractValueInst>(*I) && "Return value not only used by"
780 "extractvalue?");
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000781 ExtractValueInst *EV = cast<ExtractValueInst>(*I);
782 // Increment now, since we're about to throw away this use.
783 ++I;
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000784 assert(EV->hasIndices() && "Return value used by extractvalue without"
785 "indices?");
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000786 unsigned Idx = *EV->idx_begin();
787 if (NewRetIdxs[Idx] != -1) {
788 if (RetTypes.size() > 1) {
789 // We're still returning a struct, create a new extractvalue
790 // instruction with the first index updated
791 std::vector<unsigned> NewIdxs(EV->idx_begin(), EV->idx_end());
792 NewIdxs[0] = NewRetIdxs[Idx];
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000793 Value *NEV = ExtractValueInst::Create(New, NewIdxs.begin(),
794 NewIdxs.end(), "retval",
795 EV);
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000796 EV->replaceAllUsesWith(NEV);
797 EV->eraseFromParent();
798 } else {
799 // We are now only returning a simple value, remove the
800 // extractvalue
801 EV->replaceAllUsesWith(New);
802 EV->eraseFromParent();
803 }
804 } else {
805 // Value unused, replace uses by null for now, they will get removed
806 // later on
807 EV->replaceAllUsesWith(Constant::getNullValue(EV->getType()));
808 EV->eraseFromParent();
809 }
810 }
811 New->takeName(Call);
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000812 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000813 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000814
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000815 // Finally, remove the old call from the program, reducing the use-count of
816 // F.
Matthijs Kooijman494661c2008-05-30 12:35:46 +0000817 Call->eraseFromParent();
Chris Lattner08227e42003-06-17 22:21:05 +0000818 }
819
820 // Since we have now created the new function, splice the body of the old
821 // function right into the new function, leaving the old rotting hulk of the
822 // function empty.
823 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
824
825 // Loop over the argument list, transfering uses of the old arguments over to
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000826 // the new arguments, also transfering over the names as well.
827 i = 0;
Chris Lattner19bdc032005-05-06 05:34:40 +0000828 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000829 I2 = NF->arg_begin(); I != E; ++I, ++i)
830 if (ArgAlive[i]) {
Chris Lattner08227e42003-06-17 22:21:05 +0000831 // If this is a live argument, move the name and users over to the new
832 // version.
833 I->replaceAllUsesWith(I2);
Chris Lattner046800a2007-02-11 01:08:35 +0000834 I2->takeName(I);
Chris Lattner08227e42003-06-17 22:21:05 +0000835 ++I2;
836 } else {
837 // If this argument is dead, replace any uses of it with null constants
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000838 // (these are guaranteed to become unused later on)
Chris Lattner08227e42003-06-17 22:21:05 +0000839 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
Chris Lattner08227e42003-06-17 22:21:05 +0000840 }
841
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000842 // If we change the return value of the function we must rewrite any return
843 // instructions. Check this now.
844 if (F->getReturnType() != NF->getReturnType())
845 for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
846 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000847 Value *RetVal;
848
849 if (NFTy->getReturnType() == Type::VoidTy) {
850 RetVal = 0;
851 } else {
852 assert (isa<StructType>(RetTy));
853 // The original return value was a struct, insert
854 // extractvalue/insertvalue chains to extract only the values we need
855 // to return and insert them into our new result.
856 // This does generate messy code, but we'll let it to instcombine to
857 // clean that up
858 Value *OldRet = RI->getOperand(0);
859 // Start out building up our return value from undef
860 RetVal = llvm::UndefValue::get(NRetTy);
861 for (unsigned i = 0; i != RetCount; ++i)
862 if (NewRetIdxs[i] != -1) {
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000863 ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
864 "newret", RI);
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000865 if (RetTypes.size() > 1) {
866 // We're still returning a struct, so reinsert the value into
867 // our new return value at the new index
868
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000869 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
870 "oldret");
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000871 } else {
872 // We are now only returning a simple value, so just return the
873 // extracted value
874 RetVal = EV;
875 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000876 }
877 }
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000878 // Replace the return instruction with one returning the new return
879 // value (possibly 0 if we became void).
880 ReturnInst::Create(RetVal, RI);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000881 BB->getInstList().erase(RI);
882 }
883
Chris Lattner08227e42003-06-17 22:21:05 +0000884 // Now that the old function is dead, delete it.
Matthijs Kooijman494661c2008-05-30 12:35:46 +0000885 F->eraseFromParent();
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000886
887 return true;
Chris Lattner08227e42003-06-17 22:21:05 +0000888}
889
Chris Lattnerb12914b2004-09-20 04:48:05 +0000890bool DAE::runOnModule(Module &M) {
Chris Lattner701bc422007-11-15 06:10:55 +0000891 bool Changed = false;
892 // First pass: Do a simple check to see if any functions can have their "..."
893 // removed. We can do this if they never call va_start. This loop cannot be
894 // fused with the next loop, because deleting a function invalidates
895 // information computed while surveying other functions.
896 DOUT << "DAE - Deleting dead varargs\n";
897 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
898 Function &F = *I++;
899 if (F.getFunctionType()->isVarArg())
900 Changed |= DeleteDeadVarargs(F);
901 }
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000902
Chris Lattner701bc422007-11-15 06:10:55 +0000903 // Second phase:loop through the module, determining which arguments are live.
Chris Lattner08227e42003-06-17 22:21:05 +0000904 // We assume all arguments are dead unless proven otherwise (allowing us to
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000905 // determine that dead arguments passed into recursive functions are dead).
Chris Lattner08227e42003-06-17 22:21:05 +0000906 //
Bill Wendling0a81aac2006-11-26 10:02:32 +0000907 DOUT << "DAE - Determining liveness\n";
Chris Lattner701bc422007-11-15 06:10:55 +0000908 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
909 SurveyFunction(*I);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000910
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000911 // Now, remove all dead arguments and return values from each function in
912 // turn
913 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
914 // Increment now, because the function will probably get removed (ie
915 // replaced by a new one)
916 Function *F = I++;
917 Changed |= RemoveDeadStuffFromFunction(F);
Chris Lattner08227e42003-06-17 22:21:05 +0000918 }
919
Matthijs Kooijmanc95e44b2008-06-20 09:36:16 +0000920 return Changed;
Chris Lattner08227e42003-06-17 22:21:05 +0000921}