1 //===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
3 // This pass deletes dead arguments from internal functions. Dead argument
4 // elimination removes arguments which are directly dead, as well as arguments
5 // only passed into function calls as dead arguments of other functions.
7 // This pass is often useful as a cleanup pass to run after aggressive
8 // interprocedural passes, which add possibly-dead arguments.
10 //===----------------------------------------------------------------------===//
12 #include "llvm/Transforms/IPO.h"
13 #include "llvm/Module.h"
14 #include "llvm/Pass.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Constant.h"
17 #include "llvm/iOther.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/Support/CallSite.h"
20 #include "Support/Statistic.h"
21 #include "Support/iterator"
25 Statistic<> NumArgumentsEliminated("deadargelim", "Number of args removed");
27 struct DAE : public Pass {
30 RegisterOpt<DAE> X("deadargelim", "Dead Argument Elimination");
33 // createDeadArgEliminationPass - This pass removes arguments from functions
34 // which are not used by the body of the function.
36 Pass *createDeadArgEliminationPass() { return new DAE(); }
39 // FunctionArgumentsIntrinsicallyAlive - Return true if the arguments of the
40 // specified function are intrinsically alive.
42 // We consider arguments of non-internal functions to be intrinsically alive as
43 // well as arguments to functions which have their "address taken".
45 static bool FunctionArgumentsIntrinsicallyAlive(const Function &F) {
46 if (!F.hasInternalLinkage()) return true;
48 for (Value::use_const_iterator I = F.use_begin(), E = F.use_end(); I!=E; ++I){
49 // If this use is anything other than a call site, the function is alive.
50 CallSite CS = CallSite::get(const_cast<User*>(*I));
51 if (!CS.getInstruction()) return true; // Not a valid call site?
53 // If the function is PASSED IN as an argument, its address has been taken
54 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end(); AI != E;
56 if (AI->get() == &F) return true;
62 enum ArgumentLiveness { Alive, MaybeLive, Dead };
65 // getArgumentLiveness - Inspect an argument, determining if is known Alive
66 // (used in a computation), MaybeLive (only passed as an argument to a call), or
68 static ArgumentLiveness getArgumentLiveness(const Argument &A) {
69 if (A.use_empty()) return Dead; // First check, directly dead?
71 // Scan through all of the uses, looking for non-argument passing uses.
72 for (Value::use_const_iterator I = A.use_begin(), E = A.use_end(); I!=E;++I) {
73 CallSite CS = CallSite::get(const_cast<User*>(*I));
74 if (!CS.getInstruction()) {
75 // If its used by something that is not a call or invoke, it's alive!
78 // If it's an indirect call, mark it alive...
79 Function *Callee = CS.getCalledFunction();
80 if (!Callee) return Alive;
82 // FIXME: check to see if it's passed through a va_arg area
85 return MaybeLive; // It must be used, but only as argument to a function
88 // isMaybeLiveArgumentNowAlive - Check to see if Arg is alive. At this point,
89 // we know that the only uses of Arg are to be passed in as an argument to a
90 // function call. Check to see if the formal argument passed in is in the
91 // LiveArguments set. If so, return true.
93 static bool isMaybeLiveArgumentNowAlive(Argument *Arg,
94 const std::set<Argument*> &LiveArguments) {
95 for (Value::use_iterator I = Arg->use_begin(), E = Arg->use_end(); I!=E; ++I){
96 CallSite CS = CallSite::get(*I);
98 // We know that this can only be used for direct calls...
99 Function *Callee = cast<Function>(CS.getCalledValue());
101 // Loop over all of the arguments (because Arg may be passed into the call
102 // multiple times) and check to see if any are now alive...
103 CallSite::arg_iterator CSAI = CS.arg_begin();
104 for (Function::aiterator AI = Callee->abegin(), E = Callee->aend();
105 AI != E; ++AI, ++CSAI)
106 // If this is the argument we are looking for, check to see if it's alive
107 if (*CSAI == Arg && LiveArguments.count(AI))
113 // MarkArgumentLive - The MaybeLive argument 'Arg' is now known to be alive.
114 // Mark it live in the specified sets and recursively mark arguments in callers
115 // live that are needed to pass in a value.
117 static void MarkArgumentLive(Argument *Arg,
118 std::set<Argument*> &MaybeLiveArguments,
119 std::set<Argument*> &LiveArguments,
120 const std::multimap<Function*, CallSite> &CallSites) {
121 DEBUG(std::cerr << " MaybeLive argument now live: " << Arg->getName()<<"\n");
122 assert(MaybeLiveArguments.count(Arg) && !LiveArguments.count(Arg) &&
123 "Arg not MaybeLive?");
124 MaybeLiveArguments.erase(Arg);
125 LiveArguments.insert(Arg);
127 // Loop over all of the call sites of the function, making any arguments
128 // passed in to provide a value for this argument live as necessary.
130 Function *Fn = Arg->getParent();
131 unsigned ArgNo = std::distance(Fn->abegin(), Function::aiterator(Arg));
133 std::multimap<Function*, CallSite>::const_iterator I =
134 CallSites.lower_bound(Fn);
135 for (; I != CallSites.end() && I->first == Fn; ++I) {
136 const CallSite &CS = I->second;
137 if (Argument *ActualArg = dyn_cast<Argument>(*(CS.arg_begin()+ArgNo)))
138 if (MaybeLiveArguments.count(ActualArg))
139 MarkArgumentLive(ActualArg, MaybeLiveArguments, LiveArguments,
144 // RemoveDeadArgumentsFromFunction - We know that F has dead arguments, as
145 // specified by the DeadArguments list. Transform the function and all of the
146 // callees of the function to not have these arguments.
148 static void RemoveDeadArgumentsFromFunction(Function *F,
149 std::set<Argument*> &DeadArguments){
150 // Start by computing a new prototype for the function, which is the same as
151 // the old function, but has fewer arguments.
152 const FunctionType *FTy = F->getFunctionType();
153 std::vector<const Type*> Params;
155 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
156 if (!DeadArguments.count(I))
157 Params.push_back(I->getType());
159 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), Params,
162 // Create the new function body and insert it into the module...
163 Function *NF = new Function(NFTy, Function::InternalLinkage, F->getName());
164 F->getParent()->getFunctionList().insert(F, NF);
166 // Loop over all of the callers of the function, transforming the call sites
167 // to pass in a smaller number of arguments into the new function.
169 while (!F->use_empty()) {
170 CallSite CS = CallSite::get(F->use_back());
171 Instruction *Call = CS.getInstruction();
172 CS.setCalledFunction(NF); // Reduce the uses count of F
174 // Loop over the operands, deleting dead ones...
175 CallSite::arg_iterator AI = CS.arg_begin();
176 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
177 if (DeadArguments.count(I)) { // Remove operands for dead arguments
178 AI = Call->op_erase(AI);
180 ++AI; // Leave live operands alone...
184 // Since we have now created the new function, splice the body of the old
185 // function right into the new function, leaving the old rotting hulk of the
187 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
189 // Loop over the argument list, transfering uses of the old arguments over to
190 // the new arguments, also transfering over the names as well. While we're at
191 // it, remove the dead arguments from the DeadArguments list.
193 for (Function::aiterator I = F->abegin(), E = F->aend(), I2 = NF->abegin();
195 if (!DeadArguments.count(I)) {
196 // If this is a live argument, move the name and users over to the new
198 I->replaceAllUsesWith(I2);
199 I2->setName(I->getName());
202 // If this argument is dead, replace any uses of it with null constants
203 // (these are guaranteed to only be operands to call instructions which
204 // will later be simplified).
205 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
206 DeadArguments.erase(I);
209 // Now that the old function is dead, delete it.
210 F->getParent()->getFunctionList().erase(F);
213 bool DAE::run(Module &M) {
214 // First phase: loop through the module, determining which arguments are live.
215 // We assume all arguments are dead unless proven otherwise (allowing us to
216 // determing that dead arguments passed into recursive functions are dead).
218 std::set<Argument*> LiveArguments, MaybeLiveArguments, DeadArguments;
219 std::multimap<Function*, CallSite> CallSites;
221 DEBUG(std::cerr << "DAE - Determining liveness\n");
222 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
224 // If the function is intrinsically alive, just mark the arguments alive.
225 if (FunctionArgumentsIntrinsicallyAlive(Fn)) {
226 for (Function::aiterator AI = Fn.abegin(), E = Fn.aend(); AI != E; ++AI)
227 LiveArguments.insert(AI);
228 DEBUG(std::cerr << " Args intrinsically live for fn: " << Fn.getName()
231 DEBUG(std::cerr << " Inspecting args for fn: " << Fn.getName() << "\n");
233 // If it is not intrinsically alive, we know that all users of the
234 // function are call sites. Mark all of the arguments live which are
235 // directly used, and keep track of all of the call sites of this function
236 // if there are any arguments we assume that are dead.
238 bool AnyMaybeLiveArgs = false;
239 for (Function::aiterator AI = Fn.abegin(), E = Fn.aend(); AI != E; ++AI)
240 switch (getArgumentLiveness(*AI)) {
242 DEBUG(std::cerr << " Arg live by use: " << AI->getName() << "\n");
243 LiveArguments.insert(AI);
246 DEBUG(std::cerr << " Arg definately dead: " <<AI->getName()<<"\n");
247 DeadArguments.insert(AI);
250 DEBUG(std::cerr << " Arg only passed to calls: "
251 << AI->getName() << "\n");
252 AnyMaybeLiveArgs = true;
253 MaybeLiveArguments.insert(AI);
257 // If there are any "MaybeLive" arguments, we need to check callees of
258 // this function when/if they become alive. Record which functions are
260 if (AnyMaybeLiveArgs)
261 for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end();
263 CallSites.insert(std::make_pair(&Fn, CallSite::get(*I)));
267 // Now we loop over all of the MaybeLive arguments, promoting them to be live
268 // arguments if one of the calls that uses the arguments to the calls they are
269 // passed into requires them to be live. Of course this could make other
270 // arguments live, so process callers recursively.
272 // Because elements can be removed from the MaybeLiveArguments list, copy it
273 // to a temporary vector.
275 std::vector<Argument*> TmpArgList(MaybeLiveArguments.begin(),
276 MaybeLiveArguments.end());
277 for (unsigned i = 0, e = TmpArgList.size(); i != e; ++i) {
278 Argument *MLA = TmpArgList[i];
279 if (MaybeLiveArguments.count(MLA) &&
280 isMaybeLiveArgumentNowAlive(MLA, LiveArguments)) {
281 MarkArgumentLive(MLA, MaybeLiveArguments, LiveArguments, CallSites);
285 // Recover memory early...
288 // At this point, we know that all arguments in DeadArguments and
289 // MaybeLiveArguments are dead. If the two sets are empty, there is nothing
291 if (MaybeLiveArguments.empty() && DeadArguments.empty())
294 // Otherwise, compact into one set, and start eliminating the arguments from
296 DeadArguments.insert(MaybeLiveArguments.begin(), MaybeLiveArguments.end());
297 MaybeLiveArguments.clear();
299 NumArgumentsEliminated += DeadArguments.size();
300 while (!DeadArguments.empty())
301 RemoveDeadArgumentsFromFunction((*DeadArguments.begin())->getParent(),