1 //===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass deletes dead arguments from internal functions. Dead argument
11 // elimination removes arguments which are directly dead, as well as arguments
12 // only passed into function calls as dead arguments of other functions. This
13 // pass also deletes dead return values in a similar way.
15 // This pass is often useful as a cleanup pass to run after aggressive
16 // interprocedural passes, which add possibly-dead arguments or return values.
18 //===----------------------------------------------------------------------===//
20 #define DEBUG_TYPE "deadargelim"
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constant.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/Module.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/CallSite.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Support/Compiler.h"
39 STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
40 STATISTIC(NumRetValsEliminated , "Number of unused return values removed");
43 /// DAE - The dead argument elimination pass.
45 class VISIBILITY_HIDDEN DAE : public ModulePass {
48 /// Struct that represents (part of) either a return value or a function
49 /// argument. Used so that arguments and return values can be used
50 /// interchangably. Idx == -1 means the entire return value, while other
51 /// indices mean the corresponding element in the struct return type (if
54 RetOrArg(const Function* F, signed Idx, bool IsArg) : F(F), Idx(Idx),
60 /// Make RetOrArg comparable, so we can put it into a map.
61 bool operator<(const RetOrArg &O) const {
64 else if (Idx != O.Idx)
67 return IsArg < O.IsArg;
70 /// Make RetOrArg comparable, so we can easily iterate the multimap.
71 bool operator==(const RetOrArg &O) const {
72 return F == O.F && Idx == O.Idx && IsArg == O.IsArg;
75 std::string getDescription() const {
76 return std::string((!IsArg && Idx != -1 ? "partial " : ""))
77 + (IsArg ? "argument #" : "return value")
78 + (!IsArg && Idx == -1 ? "" : " #" + utostr(Idx))
79 + " of function " + F->getName();
83 /// Liveness enum - During our initial pass over the program, we determine
84 /// that things are either alive or maybe alive. We don't mark anything
85 /// explicitly dead (even if we know they are), since anything not alive
86 /// with no registered uses (in Uses) will never be marked alive and will
87 /// thus become dead in the end.
88 enum Liveness { Live, MaybeLive };
90 /// Convenience wrapper
91 RetOrArg CreateRet(const Function *F, signed Idx) {
92 return RetOrArg(F, Idx, false);
94 /// Convenience wrapper
95 RetOrArg CreateArg(const Function *F, signed Idx) {
96 return RetOrArg(F, Idx, true);
99 typedef std::multimap<RetOrArg, RetOrArg> UseMap;
100 /// This maps a return value or argument to any MaybeLive return values or
101 /// arguments it uses. This allows the MaybeLive values to be marked live
102 /// when any of its users is marked live.
103 /// For example (indices are left out for clarity):
104 /// - Uses[ret F] = ret G
105 /// This means that F calls G, and F returns the value returned by G.
106 /// - Uses[arg F] = ret G
107 /// This means that some function calls G and passes its result as an
109 /// - Uses[ret F] = arg F
110 /// This means that F returns one of its own arguments.
111 /// - Uses[arg F] = arg G
112 /// This means that G calls F and passes one of its own (G's) arguments
116 typedef std::set<RetOrArg> LiveSet;
117 typedef std::set<const Function*> LiveFuncSet;
119 /// This set contains all values that have been determined to be live.
121 /// This set contains all values that are cannot be changed in any way.
122 LiveFuncSet LiveFunctions;
124 typedef SmallVector<RetOrArg, 5> UseVector;
127 static char ID; // Pass identification, replacement for typeid
128 DAE() : ModulePass((intptr_t)&ID) {}
129 bool runOnModule(Module &M);
131 virtual bool ShouldHackArguments() const { return false; }
134 Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
135 Liveness SurveyUse(Value::use_iterator U, UseVector &MaybeLiveUses,
136 signed RetValNum = -1);
137 Liveness SurveyUses(Value *V, UseVector &MaybeLiveUses);
139 void SurveyFunction(Function &F);
140 void MarkValue(const RetOrArg &RA, Liveness L,
141 const UseVector &MaybeLiveUses);
142 void MarkLive(const RetOrArg &RA);
143 void MarkLive(const Function &F);
144 void PropagateLiveness(const RetOrArg &RA);
145 bool RemoveDeadStuffFromFunction(Function *F);
146 bool DeleteDeadVarargs(Function &Fn);
152 static RegisterPass<DAE>
153 X("deadargelim", "Dead Argument Elimination");
156 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
157 /// deletes arguments to functions which are external. This is only for use
159 struct DAH : public DAE {
161 virtual bool ShouldHackArguments() const { return true; }
166 static RegisterPass<DAH>
167 Y("deadarghaX0r", "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)");
169 /// createDeadArgEliminationPass - This pass removes arguments from functions
170 /// which are not used by the body of the function.
172 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
173 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
175 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if
176 /// llvm.vastart is never called, the varargs list is dead for the function.
177 bool DAE::DeleteDeadVarargs(Function &Fn) {
178 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
179 if (Fn.isDeclaration() || !Fn.hasInternalLinkage()) return false;
181 // Ensure that the function is only directly called.
182 for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end(); I != E; ++I) {
183 // If this use is anything other than a call site, give up.
184 CallSite CS = CallSite::get(*I);
185 Instruction *TheCall = CS.getInstruction();
186 if (!TheCall) return false; // Not a direct call site?
188 // The addr of this function is passed to the call.
189 if (I.getOperandNo() != 0) return false;
192 // Okay, we know we can transform this function if safe. Scan its body
193 // looking for calls to llvm.vastart.
194 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
195 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
196 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
197 if (II->getIntrinsicID() == Intrinsic::vastart)
203 // If we get here, there are no calls to llvm.vastart in the function body,
204 // remove the "..." and adjust all the calls.
206 // Start by computing a new prototype for the function, which is the same as
207 // the old function, but doesn't have isVarArg set.
208 const FunctionType *FTy = Fn.getFunctionType();
209 std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
210 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), Params, false);
211 unsigned NumArgs = Params.size();
213 // Create the new function body and insert it into the module...
214 Function *NF = Function::Create(NFTy, Fn.getLinkage());
215 NF->copyAttributesFrom(&Fn);
216 Fn.getParent()->getFunctionList().insert(&Fn, NF);
219 // Loop over all of the callers of the function, transforming the call sites
220 // to pass in a smaller number of arguments into the new function.
222 std::vector<Value*> Args;
223 while (!Fn.use_empty()) {
224 CallSite CS = CallSite::get(Fn.use_back());
225 Instruction *Call = CS.getInstruction();
227 // Pass all the same arguments.
228 Args.assign(CS.arg_begin(), CS.arg_begin()+NumArgs);
230 // Drop any attributes that were on the vararg arguments.
231 PAListPtr PAL = CS.getParamAttrs();
232 if (!PAL.isEmpty() && PAL.getSlot(PAL.getNumSlots() - 1).Index > NumArgs) {
233 SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
234 for (unsigned i = 0; PAL.getSlot(i).Index <= NumArgs; ++i)
235 ParamAttrsVec.push_back(PAL.getSlot(i));
236 PAL = PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end());
240 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
241 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
242 Args.begin(), Args.end(), "", Call);
243 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
244 cast<InvokeInst>(New)->setParamAttrs(PAL);
246 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
247 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
248 cast<CallInst>(New)->setParamAttrs(PAL);
249 if (cast<CallInst>(Call)->isTailCall())
250 cast<CallInst>(New)->setTailCall();
254 if (!Call->use_empty())
255 Call->replaceAllUsesWith(New);
259 // Finally, remove the old call from the program, reducing the use-count of
261 Call->eraseFromParent();
264 // Since we have now created the new function, splice the body of the old
265 // function right into the new function, leaving the old rotting hulk of the
267 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
269 // Loop over the argument list, transfering uses of the old arguments over to
270 // the new arguments, also transfering over the names as well. While we're at
271 // it, remove the dead arguments from the DeadArguments list.
273 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
274 I2 = NF->arg_begin(); I != E; ++I, ++I2) {
275 // Move the name and users over to the new version.
276 I->replaceAllUsesWith(I2);
280 // Finally, nuke the old function.
281 Fn.eraseFromParent();
285 /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
286 /// live, it adds Use to the MaybeLiveUses argument. Returns the determined
288 DAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
289 // We're live if our use or its Function is already marked as live.
290 if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
293 // We're maybe live otherwise, but remember that we must become live if
295 MaybeLiveUses.push_back(Use);
299 /// SurveyUse - This looks at a single use of an argument or return value
300 /// and determines if it should be alive or not. Adds this use to MaybeLiveUses
301 /// if it causes the used value to become MaybeAlive.
303 /// RetValNum is the return value number to use when this use is used in a
304 /// return instruction. This is used in the recursion, you should always leave
306 DAE::Liveness DAE::SurveyUse(Value::use_iterator U, UseVector &MaybeLiveUses,
309 if (ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
310 // The value is returned from a function. It's only live when the
311 // function's return value is live. We use RetValNum here, for the case
312 // that U is really a use of an insertvalue instruction that uses the
314 RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
315 // We might be live, depending on the liveness of Use.
316 return MarkIfNotLive(Use, MaybeLiveUses);
318 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
319 if (U.getOperandNo() != InsertValueInst::getAggregateOperandIndex()
321 // The use we are examining is inserted into an aggregate. Our liveness
322 // depends on all uses of that aggregate, but if it is used as a return
323 // value, only index at which we were inserted counts.
324 RetValNum = *IV->idx_begin();
326 // Note that if we are used as the aggregate operand to the insertvalue,
327 // we don't change RetValNum, but do survey all our uses.
329 Liveness Result = MaybeLive;
330 for (Value::use_iterator I = IV->use_begin(),
331 E = V->use_end(); I != E; ++I) {
332 Result = SurveyUse(I, MaybeLiveUses, RetValNum);
338 CallSite CS = CallSite::get(V);
339 if (CS.getInstruction()) {
340 Function *F = CS.getCalledFunction();
342 // Used in a direct call.
344 // Find the argument number. We know for sure that this use is an
345 // argument, since if it was the function argument this would be an
346 // indirect call and the we know can't be looking at a value of the
347 // label type (for the invoke instruction).
348 unsigned ArgNo = CS.getArgumentNo(U.getOperandNo());
350 if (ArgNo >= F->getFunctionType()->getNumParams())
351 // The value is passed in through a vararg! Must be live.
354 assert(CS.getArgument(ArgNo)
355 == CS.getInstruction()->getOperand(U.getOperandNo())
356 && "Argument is not where we expected it");
358 // Value passed to a normal call. It's only live when the corresponding
359 // argument to the called function turns out live.
360 RetOrArg Use = CreateArg(F, ArgNo);
361 return MarkIfNotLive(Use, MaybeLiveUses);
364 // Used in any other way? Value must be live.
368 /// SurveyUses - This looks at all the uses of the given value
369 /// Returns the Liveness deduced from the uses of this value.
371 /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
372 /// the result is Live, MaybeLiveUses might be modified but its content should
373 /// be ignored (since it might not be complete).
374 DAE::Liveness DAE::SurveyUses(Value *V, UseVector &MaybeLiveUses) {
375 // Assume it's dead (which will only hold if there are no uses at all..).
376 Liveness Result = MaybeLive;
378 for (Value::use_iterator I = V->use_begin(),
379 E = V->use_end(); I != E; ++I) {
380 Result = SurveyUse(I, MaybeLiveUses);
387 // SurveyFunction - This performs the initial survey of the specified function,
388 // checking out whether or not it uses any of its incoming arguments or whether
389 // any callers use the return value. This fills in the LiveValues set and Uses
392 // We consider arguments of non-internal functions to be intrinsically alive as
393 // well as arguments to functions which have their "address taken".
395 void DAE::SurveyFunction(Function &F) {
396 const StructType *STy = dyn_cast<StructType>(F.getFunctionType()->getReturnType());
397 // Store the number of partial return values, which we only have if the return
399 unsigned PartialRetVals = (STy ? STy->getNumElements() : 0);
400 // Assume all return values are dead
401 typedef SmallVector<Liveness, 5> RetVals;
402 // Allocate one slot for the entire return value (index 0) and one for each
403 // partial return value.
404 RetVals RetValLiveness(PartialRetVals + 1, MaybeLive);
406 typedef SmallVector<UseVector, 5> RetUses;
407 // These vectors map each return value to the uses that make it MaybeLive, so
408 // we can add those to the Uses map if the return value really turns out to be
410 // Allocate one slot for the entire return value (index 0) and one for each
411 // partial return value.
412 RetUses MaybeLiveRetUses(PartialRetVals + 1);
414 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
415 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
416 if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
417 != F.getFunctionType()->getReturnType()) {
418 // We don't support old style multiple return values.
423 if (!F.hasInternalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
428 DOUT << "DAE - Inspecting callers for fn: " << F.getName() << "\n";
429 // Loop all uses of the function.
430 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
431 // If the function is PASSED IN as an argument, its address has been
433 if (I.getOperandNo() != 0) {
438 // If this use is anything other than a call site, the function is alive.
439 CallSite CS = CallSite::get(*I);
440 Instruction *TheCall = CS.getInstruction();
441 if (!TheCall) { // Not a direct call site?
446 // If we end up here, we are looking at a direct call to our function.
448 // Now, check how our return value(s) is/are used in this caller. Don't
449 // bother checking return values if the entire value is live already.
450 if (RetValLiveness[0] != Live) {
451 // Check all uses of the return value.
452 for (Value::use_iterator I = TheCall->use_begin(),
453 E = TheCall->use_end(); I != E; ++I) {
454 ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(*I);
455 if (Ext && Ext->hasIndices()) {
456 // This use uses a part of our return value, survey the uses of
457 // that part and store the results for this index only.
458 unsigned Idx = *Ext->idx_begin();
459 // + 1 to skip the "entire retval" index (0)
460 Liveness &IsLive = RetValLiveness[Idx + 1];
461 if (IsLive != Live) {
462 // Don't bother checking if this retval was already live
463 // Survey all uses of the extractvalue
464 // + 1 to skip the "entire retval" index (0)
465 IsLive = SurveyUses(Ext, MaybeLiveRetUses[Idx + 1]);
469 RetValLiveness[0] = SurveyUse(I, MaybeLiveRetUses[0]);
470 if (RetValLiveness[0] == Live)
477 // Now we've inspected all callers, record the liveness of our return values.
478 MarkValue(CreateRet(&F, -1), RetValLiveness[0], MaybeLiveRetUses[0]);
479 if (RetValLiveness[0] != Live)
480 // If the entire retval (0) is Live, MarkValue will have marked all other retvals live
481 // as well, so we can skip this.
482 for (unsigned i = 0; i != PartialRetVals; ++i)
483 // + 1 to skip the "entire retval" index (0)
484 MarkValue(CreateRet(&F, i), RetValLiveness[i + 1], MaybeLiveRetUses[i + 1]);
486 DOUT << "DAE - Inspecting args for fn: " << F.getName() << "\n";
488 // Now, check all of our arguments.
490 UseVector MaybeLiveArgUses;
491 for (Function::arg_iterator AI = F.arg_begin(),
492 E = F.arg_end(); AI != E; ++AI, ++i) {
493 // See what the effect of this use is (recording any uses that cause
494 // MaybeLive in MaybeLiveArgUses).
495 Liveness Result = SurveyUses(AI, MaybeLiveArgUses);
497 MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
498 // Clear the vector again for the next iteration.
499 MaybeLiveArgUses.clear();
503 /// MarkValue - This function marks the liveness of RA depending on L. If L is
504 /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
505 /// such that RA will be marked live if any use in MaybeLiveUses gets marked
507 void DAE::MarkValue(const RetOrArg &RA, Liveness L,
508 const UseVector &MaybeLiveUses) {
510 case Live: MarkLive(RA); break;
513 // Note any uses of this value, so this return value can be
514 // marked live whenever one of the uses becomes live.
515 for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
516 UE = MaybeLiveUses.end(); UI != UE; ++UI)
517 Uses.insert(std::make_pair(*UI, RA));
523 /// MarkLive - Mark the given Function as alive, meaning that it cannot be
524 /// changed in any way. Additionally,
525 /// mark any values that are used as this function's parameters or by its return
526 /// values (according to Uses) live as well.
527 void DAE::MarkLive(const Function &F) {
528 DOUT << "DAE - Intrinsically live fn: " << F.getName() << "\n";
529 // Mark the function as live.
530 LiveFunctions.insert(&F);
531 // Mark all arguments as live.
532 for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
533 PropagateLiveness(CreateArg(&F, i));
534 // Mark all return values as live.
535 const Type *RTy = F.getFunctionType()->getReturnType();
536 if (const StructType *STy = dyn_cast<StructType>(RTy))
537 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
538 PropagateLiveness(CreateRet(&F, i));
539 PropagateLiveness(CreateRet(&F, -1));
542 /// MarkLive - Mark the given return value or argument as live. Additionally,
543 /// mark any values that are used by this value (according to Uses) live as
545 void DAE::MarkLive(const RetOrArg &RA) {
546 if (LiveFunctions.count(RA.F))
547 return; // Function was already marked Live.
549 if (!LiveValues.insert(RA).second)
550 return; // We were already marked Live.
552 DOUT << "DAE - Marking " << RA.getDescription() << " live\n";
553 PropagateLiveness(RA);
555 if (!RA.IsArg && RA.Idx == -1) {
556 // Entire return value live?
557 const Type *RTy = RA.F->getFunctionType()->getReturnType();
558 if (const StructType *STy = dyn_cast<StructType>(RTy))
559 // And the function returns a struct?
560 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
561 // Mark all partial return values live as well then
562 MarkLive(CreateRet(RA.F, i));
566 /// PropagateLiveness - Given that RA is a live value, propagate it's liveness
567 /// to any other values it uses (according to Uses).
568 void DAE::PropagateLiveness(const RetOrArg &RA) {
569 // We don't use upper_bound (or equal_range) here, because our recursive call
570 // to ourselves is likely to cause the upper_bound (which is the first value
571 // not belonging to RA) to become erased and the iterator invalidated.
572 UseMap::iterator Begin = Uses.lower_bound(RA);
573 UseMap::iterator E = Uses.end();
575 for (I = Begin; I != E && I->first == RA; ++I)
578 // Erase RA from the Uses map (from the lower bound to wherever we ended up
580 Uses.erase(Begin, I);
583 // RemoveDeadStuffFromFunction - Remove any arguments and return values from F
584 // that are not in LiveValues. Transform the function and all of the callees of
585 // the function to not have these arguments and return values.
587 bool DAE::RemoveDeadStuffFromFunction(Function *F) {
588 // Don't modify fully live functions
589 if (LiveFunctions.count(F))
592 // Start by computing a new prototype for the function, which is the same as
593 // the old function, but has fewer arguments and a different return type.
594 const FunctionType *FTy = F->getFunctionType();
595 std::vector<const Type*> Params;
597 // Set up to build a new list of parameter attributes.
598 SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
599 const PAListPtr &PAL = F->getParamAttrs();
601 // The existing function return attributes.
602 ParameterAttributes RAttrs = PAL.getParamAttrs(0);
605 // Find out the new return value.
607 const Type *RetTy = FTy->getReturnType();
608 const StructType *STy = dyn_cast<StructType>(RetTy);
609 const unsigned PartialRetVals = (STy ? STy->getNumElements() : 0);
610 const Type *NRetTy = NULL;
611 // -1 means unused, other numbers are the new index. Initialized to -1 for
612 // every partial return value we have.
613 SmallVector<int, 5> NewRetIdxs(PartialRetVals, -1);
614 std::vector<const Type*> RetTypes;
615 if (LiveValues.count(CreateRet(F, -1))) {
616 // If the entire return value is live, leave it unchanged.
620 // Look at each of the partial return values individually.
621 for (unsigned i = 0; i != PartialRetVals; ++i) {
622 RetOrArg Ret = CreateRet(F, i);
623 if (LiveValues.erase(Ret)) {
624 RetTypes.push_back(STy->getElementType(i));
625 NewRetIdxs[i] = RetTypes.size() - 1;
627 ++NumRetValsEliminated;
628 DOUT << "DAE - Removing return value " << i << " from "
629 << F->getNameStart() << "\n";
630 // We remove the value by not adding anything to RetTypes.
633 } else if (RetTy != Type::VoidTy) {
634 // We used to return a single value, which is now dead (already checked in
636 DOUT << "DAE - Removing return value from " << F->getNameStart()
638 ++NumRetValsEliminated;
639 // We remove the value by not adding anything to RetTypes.
642 if (RetTypes.size() > 1)
643 // More than one return type? Return a struct with them.
644 // Make the new struct packed if we used to return a packed struct
646 NRetTy = StructType::get(RetTypes, STy->isPacked());
647 else if (RetTypes.size() == 1)
648 // One return type? Just a simple value then, but only if we didn't use to
649 // return a struct with that simple value before.
650 NRetTy = RetTypes.front();
651 else if (RetTypes.size() == 0)
652 // No return types? Make it void.
653 NRetTy = Type::VoidTy;
656 assert(NRetTy && "No new return type found?");
658 // Remove any incompatible attributes, but only if we removed all return
659 // values. Otherwise, ensure that we don't have any conflicting attributes
660 // here. Currently, this should not be possible, but special handling might be
661 // required when new return value attributes are added.
662 if (NRetTy == Type::VoidTy)
663 RAttrs &= ~ParamAttr::typeIncompatible(NRetTy);
665 assert((RAttrs & ParamAttr::typeIncompatible(NRetTy)) == 0
666 && "Return attributes no longer compatible?");
669 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
671 // Remember which arguments are still alive.
672 SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
673 // Construct the new parameter list from non-dead arguments. Also construct
674 // a new set of parameter attributes to correspond. Skip the first parameter
675 // attribute, since that belongs to the return value.
677 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
679 RetOrArg Arg = CreateArg(F, i);
680 if (LiveValues.erase(Arg)) {
681 Params.push_back(I->getType());
684 // Get the original parameter attributes (skipping the first one, that is
685 // for the return value.
686 if (ParameterAttributes Attrs = PAL.getParamAttrs(i + 1))
687 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), Attrs));
689 ++NumArgumentsEliminated;
690 DOUT << "DAE - Removing argument " << i << " (" << I->getNameStart()
691 << ") from " << F->getNameStart() << "\n";
695 // Reconstruct the ParamAttrsList based on the vector we constructed.
696 PAListPtr NewPAL = PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end());
698 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
699 // have zero fixed arguments.
701 // Note that we apply this hack for a vararg fuction that does not have any
702 // arguments anymore, but did have them before (so don't bother fixing
703 // functions that were already broken wrt CWriter).
704 bool ExtraArgHack = false;
705 if (Params.empty() && FTy->isVarArg() && FTy->getNumParams() != 0) {
707 Params.push_back(Type::Int32Ty);
710 // Create the new function type based on the recomputed parameters.
711 FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
717 // Create the new function body and insert it into the module...
718 Function *NF = Function::Create(NFTy, F->getLinkage());
719 NF->copyAttributesFrom(F);
720 NF->setParamAttrs(NewPAL);
721 // Insert the new function before the old function, so we won't be processing
723 F->getParent()->getFunctionList().insert(F, NF);
726 // Loop over all of the callers of the function, transforming the call sites
727 // to pass in a smaller number of arguments into the new function.
729 std::vector<Value*> Args;
730 while (!F->use_empty()) {
731 CallSite CS = CallSite::get(F->use_back());
732 Instruction *Call = CS.getInstruction();
734 ParamAttrsVec.clear();
735 const PAListPtr &CallPAL = CS.getParamAttrs();
737 // The call return attributes.
738 ParameterAttributes RAttrs = CallPAL.getParamAttrs(0);
739 // Adjust in case the function was changed to return void.
740 RAttrs &= ~ParamAttr::typeIncompatible(NF->getReturnType());
742 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
744 // Declare these outside of the loops, so we can reuse them for the second
745 // loop, which loops the varargs.
746 CallSite::arg_iterator I = CS.arg_begin();
748 // Loop over those operands, corresponding to the normal arguments to the
749 // original function, and add those that are still alive.
750 for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
753 // Get original parameter attributes, but skip return attributes.
754 if (ParameterAttributes Attrs = CallPAL.getParamAttrs(i + 1))
755 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
759 Args.push_back(UndefValue::get(Type::Int32Ty));
761 // Push any varargs arguments on the list. Don't forget their attributes.
762 for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
764 if (ParameterAttributes Attrs = CallPAL.getParamAttrs(i + 1))
765 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
768 // Reconstruct the ParamAttrsList based on the vector we constructed.
769 PAListPtr NewCallPAL = PAListPtr::get(ParamAttrsVec.begin(),
770 ParamAttrsVec.end());
773 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
774 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
775 Args.begin(), Args.end(), "", Call);
776 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
777 cast<InvokeInst>(New)->setParamAttrs(NewCallPAL);
779 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
780 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
781 cast<CallInst>(New)->setParamAttrs(NewCallPAL);
782 if (cast<CallInst>(Call)->isTailCall())
783 cast<CallInst>(New)->setTailCall();
787 if (!Call->use_empty()) {
788 if (New->getType() == Call->getType()) {
789 // Return type not changed? Just replace users then.
790 Call->replaceAllUsesWith(New);
792 } else if (New->getType() == Type::VoidTy) {
793 // Our return value has uses, but they will get removed later on.
794 // Replace by null for now.
795 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
797 assert(STy && "Return type changed, but not into a void. The old "
798 "return type must have been a struct!");
799 // We used to return a struct. Instead of doing smart stuff with all the
800 // uses of this struct, we will just rebuild it using
801 // extract/insertvalue chaining and let instcombine clean that up.
803 // Start out building up our return value from undef
804 Value *RetVal = llvm::UndefValue::get(RetTy);
805 for (unsigned i = 0; i != PartialRetVals; ++i)
806 if (NewRetIdxs[i] != -1) {
808 if (RetTypes.size() > 1)
809 // We are still returning a struct, so extract the value from our
811 V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret", Call);
813 // We are now returning a single element, so just insert that
815 // Insert the value at the old position
816 RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", Call);
818 // Now, replace all uses of the old call instruction with the return
820 Call->replaceAllUsesWith(RetVal);
825 // Finally, remove the old call from the program, reducing the use-count of
827 Call->eraseFromParent();
830 // Since we have now created the new function, splice the body of the old
831 // function right into the new function, leaving the old rotting hulk of the
833 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
835 // Loop over the argument list, transfering uses of the old arguments over to
836 // the new arguments, also transfering over the names as well.
838 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
839 I2 = NF->arg_begin(); I != E; ++I, ++i)
841 // If this is a live argument, move the name and users over to the new
843 I->replaceAllUsesWith(I2);
847 // If this argument is dead, replace any uses of it with null constants
848 // (these are guaranteed to become unused later on).
849 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
852 // If we change the return value of the function we must rewrite any return
853 // instructions. Check this now.
854 if (F->getReturnType() != NF->getReturnType())
855 for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
856 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
859 if (NFTy->getReturnType() == Type::VoidTy) {
862 assert (isa<StructType>(RetTy));
863 // The original return value was a struct, insert
864 // extractvalue/insertvalue chains to extract only the values we need
865 // to return and insert them into our new result.
866 // This does generate messy code, but we'll let it to instcombine to
868 Value *OldRet = RI->getOperand(0);
869 // Start out building up our return value from undef
870 RetVal = llvm::UndefValue::get(NRetTy);
871 for (unsigned i = 0; i != PartialRetVals; ++i)
872 if (NewRetIdxs[i] != -1) {
873 ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
875 if (RetTypes.size() > 1) {
876 // We're still returning a struct, so reinsert the value into
877 // our new return value at the new index
879 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
882 // We are now only returning a simple value, so just return the
888 // Replace the return instruction with one returning the new return
889 // value (possibly 0 if we became void).
890 ReturnInst::Create(RetVal, RI);
891 BB->getInstList().erase(RI);
894 // Now that the old function is dead, delete it.
895 F->eraseFromParent();
900 bool DAE::runOnModule(Module &M) {
901 bool Changed = false;
903 // First pass: Do a simple check to see if any functions can have their "..."
904 // removed. We can do this if they never call va_start. This loop cannot be
905 // fused with the next loop, because deleting a function invalidates
906 // information computed while surveying other functions.
907 DOUT << "DAE - Deleting dead varargs\n";
908 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
910 if (F.getFunctionType()->isVarArg())
911 Changed |= DeleteDeadVarargs(F);
914 // Second phase:loop through the module, determining which arguments are live.
915 // We assume all arguments are dead unless proven otherwise (allowing us to
916 // determine that dead arguments passed into recursive functions are dead).
918 DOUT << "DAE - Determining liveness\n";
919 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
922 // Now, remove all dead arguments and return values from each function in
924 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
925 // Increment now, because the function will probably get removed (ie
926 // replaced by a new one).
928 Changed |= RemoveDeadStuffFromFunction(F);