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/LLVMContext.h"
28 #include "llvm/Module.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/CallSite.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringExtras.h"
40 STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
41 STATISTIC(NumRetValsEliminated , "Number of unused return values removed");
42 STATISTIC(NumArgumentsReplacedWithUndef,
43 "Number of unread args replaced with undef");
45 /// DAE - The dead argument elimination pass.
47 class DAE : public ModulePass {
50 /// Struct that represents (part of) either a return value or a function
51 /// argument. Used so that arguments and return values can be used
54 RetOrArg(const Function *F, unsigned 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 ? "Argument #" : "Return value #"))
77 + utostr(Idx) + " of function " + F->getName().str();
81 /// Liveness enum - During our initial pass over the program, we determine
82 /// that things are either alive or maybe alive. We don't mark anything
83 /// explicitly dead (even if we know they are), since anything not alive
84 /// with no registered uses (in Uses) will never be marked alive and will
85 /// thus become dead in the end.
86 enum Liveness { Live, MaybeLive };
88 /// Convenience wrapper
89 RetOrArg CreateRet(const Function *F, unsigned Idx) {
90 return RetOrArg(F, Idx, false);
92 /// Convenience wrapper
93 RetOrArg CreateArg(const Function *F, unsigned Idx) {
94 return RetOrArg(F, Idx, true);
97 typedef std::multimap<RetOrArg, RetOrArg> UseMap;
98 /// This maps a return value or argument to any MaybeLive return values or
99 /// arguments it uses. This allows the MaybeLive values to be marked live
100 /// when any of its users is marked live.
101 /// For example (indices are left out for clarity):
102 /// - Uses[ret F] = ret G
103 /// This means that F calls G, and F returns the value returned by G.
104 /// - Uses[arg F] = ret G
105 /// This means that some function calls G and passes its result as an
107 /// - Uses[ret F] = arg F
108 /// This means that F returns one of its own arguments.
109 /// - Uses[arg F] = arg G
110 /// This means that G calls F and passes one of its own (G's) arguments
114 typedef std::set<RetOrArg> LiveSet;
115 typedef std::set<const Function*> LiveFuncSet;
117 /// This set contains all values that have been determined to be live.
119 /// This set contains all values that are cannot be changed in any way.
120 LiveFuncSet LiveFunctions;
122 typedef SmallVector<RetOrArg, 5> UseVector;
125 // DAH uses this to specify a different ID.
126 explicit DAE(char &ID) : ModulePass(ID) {}
129 static char ID; // Pass identification, replacement for typeid
130 DAE() : ModulePass(ID) {
131 initializeDAEPass(*PassRegistry::getPassRegistry());
134 bool runOnModule(Module &M);
136 virtual bool ShouldHackArguments() const { return false; }
139 Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
140 Liveness SurveyUse(Value::const_use_iterator U, UseVector &MaybeLiveUses,
141 unsigned RetValNum = 0);
142 Liveness SurveyUses(const Value *V, UseVector &MaybeLiveUses);
144 void SurveyFunction(const Function &F);
145 void MarkValue(const RetOrArg &RA, Liveness L,
146 const UseVector &MaybeLiveUses);
147 void MarkLive(const RetOrArg &RA);
148 void MarkLive(const Function &F);
149 void PropagateLiveness(const RetOrArg &RA);
150 bool RemoveDeadStuffFromFunction(Function *F);
151 bool DeleteDeadVarargs(Function &Fn);
152 bool RemoveDeadArgumentsFromCallers(Function &Fn);
158 INITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false)
161 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
162 /// deletes arguments to functions which are external. This is only for use
164 struct DAH : public DAE {
168 virtual bool ShouldHackArguments() const { return true; }
173 INITIALIZE_PASS(DAH, "deadarghaX0r",
174 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)",
177 /// createDeadArgEliminationPass - This pass removes arguments from functions
178 /// which are not used by the body of the function.
180 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
181 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
183 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if
184 /// llvm.vastart is never called, the varargs list is dead for the function.
185 bool DAE::DeleteDeadVarargs(Function &Fn) {
186 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
187 if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false;
189 // Ensure that the function is only directly called.
190 if (Fn.hasAddressTaken())
193 // Okay, we know we can transform this function if safe. Scan its body
194 // looking for calls to llvm.vastart.
195 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
196 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
197 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
198 if (II->getIntrinsicID() == Intrinsic::vastart)
204 // If we get here, there are no calls to llvm.vastart in the function body,
205 // remove the "..." and adjust all the calls.
207 // Start by computing a new prototype for the function, which is the same as
208 // the old function, but doesn't have isVarArg set.
209 FunctionType *FTy = Fn.getFunctionType();
211 std::vector<Type*> Params(FTy->param_begin(), FTy->param_end());
212 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(),
214 unsigned NumArgs = Params.size();
216 // Create the new function body and insert it into the module...
217 Function *NF = Function::Create(NFTy, Fn.getLinkage());
218 NF->copyAttributesFrom(&Fn);
219 Fn.getParent()->getFunctionList().insert(&Fn, NF);
222 // Loop over all of the callers of the function, transforming the call sites
223 // to pass in a smaller number of arguments into the new function.
225 std::vector<Value*> Args;
226 while (!Fn.use_empty()) {
227 CallSite CS(Fn.use_back());
228 Instruction *Call = CS.getInstruction();
230 // Pass all the same arguments.
231 Args.assign(CS.arg_begin(), CS.arg_begin() + NumArgs);
233 // Drop any attributes that were on the vararg arguments.
234 AttrListPtr PAL = CS.getAttributes();
235 if (!PAL.isEmpty() && PAL.getSlot(PAL.getNumSlots() - 1).Index > NumArgs) {
236 SmallVector<AttributeWithIndex, 8> AttributesVec;
237 for (unsigned i = 0; PAL.getSlot(i).Index <= NumArgs; ++i)
238 AttributesVec.push_back(PAL.getSlot(i));
239 if (Attributes FnAttrs = PAL.getFnAttributes())
240 AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
241 PAL = AttrListPtr::get(AttributesVec);
245 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
246 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
248 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
249 cast<InvokeInst>(New)->setAttributes(PAL);
251 New = CallInst::Create(NF, Args, "", Call);
252 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
253 cast<CallInst>(New)->setAttributes(PAL);
254 if (cast<CallInst>(Call)->isTailCall())
255 cast<CallInst>(New)->setTailCall();
257 New->setDebugLoc(Call->getDebugLoc());
261 if (!Call->use_empty())
262 Call->replaceAllUsesWith(New);
266 // Finally, remove the old call from the program, reducing the use-count of
268 Call->eraseFromParent();
271 // Since we have now created the new function, splice the body of the old
272 // function right into the new function, leaving the old rotting hulk of the
274 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
276 // Loop over the argument list, transferring uses of the old arguments over to
277 // the new arguments, also transferring over the names as well. While we're at
278 // it, remove the dead arguments from the DeadArguments list.
280 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
281 I2 = NF->arg_begin(); I != E; ++I, ++I2) {
282 // Move the name and users over to the new version.
283 I->replaceAllUsesWith(I2);
287 // Finally, nuke the old function.
288 Fn.eraseFromParent();
292 /// RemoveDeadArgumentsFromCallers - Checks if the given function has any
293 /// arguments that are unused, and changes the caller parameters to be undefined
295 bool DAE::RemoveDeadArgumentsFromCallers(Function &Fn)
297 if (Fn.isDeclaration() || Fn.mayBeOverridden())
300 // Functions with local linkage should already have been handled.
301 if (Fn.hasLocalLinkage())
307 llvm::SmallVector<unsigned, 8> UnusedArgs;
308 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
312 if (Arg->use_empty() && !Arg->hasByValAttr())
313 UnusedArgs.push_back(Arg->getArgNo());
316 if (UnusedArgs.empty())
319 bool Changed = false;
321 for (Function::use_iterator I = Fn.use_begin(), E = Fn.use_end();
324 if (!CS || !CS.isCallee(I))
327 // Now go through all unused args and replace them with "undef".
328 for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) {
329 unsigned ArgNo = UnusedArgs[I];
331 Value *Arg = CS.getArgument(ArgNo);
332 CS.setArgument(ArgNo, UndefValue::get(Arg->getType()));
333 ++NumArgumentsReplacedWithUndef;
341 /// Convenience function that returns the number of return values. It returns 0
342 /// for void functions and 1 for functions not returning a struct. It returns
343 /// the number of struct elements for functions returning a struct.
344 static unsigned NumRetVals(const Function *F) {
345 if (F->getReturnType()->isVoidTy())
347 else if (StructType *STy = dyn_cast<StructType>(F->getReturnType()))
348 return STy->getNumElements();
353 /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
354 /// live, it adds Use to the MaybeLiveUses argument. Returns the determined
356 DAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
357 // We're live if our use or its Function is already marked as live.
358 if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
361 // We're maybe live otherwise, but remember that we must become live if
363 MaybeLiveUses.push_back(Use);
368 /// SurveyUse - This looks at a single use of an argument or return value
369 /// and determines if it should be alive or not. Adds this use to MaybeLiveUses
370 /// if it causes the used value to become MaybeLive.
372 /// RetValNum is the return value number to use when this use is used in a
373 /// return instruction. This is used in the recursion, you should always leave
375 DAE::Liveness DAE::SurveyUse(Value::const_use_iterator U,
376 UseVector &MaybeLiveUses, unsigned RetValNum) {
378 if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
379 // The value is returned from a function. It's only live when the
380 // function's return value is live. We use RetValNum here, for the case
381 // that U is really a use of an insertvalue instruction that uses the
383 RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
384 // We might be live, depending on the liveness of Use.
385 return MarkIfNotLive(Use, MaybeLiveUses);
387 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
388 if (U.getOperandNo() != InsertValueInst::getAggregateOperandIndex()
390 // The use we are examining is inserted into an aggregate. Our liveness
391 // depends on all uses of that aggregate, but if it is used as a return
392 // value, only index at which we were inserted counts.
393 RetValNum = *IV->idx_begin();
395 // Note that if we are used as the aggregate operand to the insertvalue,
396 // we don't change RetValNum, but do survey all our uses.
398 Liveness Result = MaybeLive;
399 for (Value::const_use_iterator I = IV->use_begin(),
400 E = V->use_end(); I != E; ++I) {
401 Result = SurveyUse(I, MaybeLiveUses, RetValNum);
408 if (ImmutableCallSite CS = V) {
409 const Function *F = CS.getCalledFunction();
411 // Used in a direct call.
413 // Find the argument number. We know for sure that this use is an
414 // argument, since if it was the function argument this would be an
415 // indirect call and the we know can't be looking at a value of the
416 // label type (for the invoke instruction).
417 unsigned ArgNo = CS.getArgumentNo(U);
419 if (ArgNo >= F->getFunctionType()->getNumParams())
420 // The value is passed in through a vararg! Must be live.
423 assert(CS.getArgument(ArgNo)
424 == CS->getOperand(U.getOperandNo())
425 && "Argument is not where we expected it");
427 // Value passed to a normal call. It's only live when the corresponding
428 // argument to the called function turns out live.
429 RetOrArg Use = CreateArg(F, ArgNo);
430 return MarkIfNotLive(Use, MaybeLiveUses);
433 // Used in any other way? Value must be live.
437 /// SurveyUses - This looks at all the uses of the given value
438 /// Returns the Liveness deduced from the uses of this value.
440 /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
441 /// the result is Live, MaybeLiveUses might be modified but its content should
442 /// be ignored (since it might not be complete).
443 DAE::Liveness DAE::SurveyUses(const Value *V, UseVector &MaybeLiveUses) {
444 // Assume it's dead (which will only hold if there are no uses at all..).
445 Liveness Result = MaybeLive;
447 for (Value::const_use_iterator I = V->use_begin(),
448 E = V->use_end(); I != E; ++I) {
449 Result = SurveyUse(I, MaybeLiveUses);
456 // SurveyFunction - This performs the initial survey of the specified function,
457 // checking out whether or not it uses any of its incoming arguments or whether
458 // any callers use the return value. This fills in the LiveValues set and Uses
461 // We consider arguments of non-internal functions to be intrinsically alive as
462 // well as arguments to functions which have their "address taken".
464 void DAE::SurveyFunction(const Function &F) {
465 unsigned RetCount = NumRetVals(&F);
466 // Assume all return values are dead
467 typedef SmallVector<Liveness, 5> RetVals;
468 RetVals RetValLiveness(RetCount, MaybeLive);
470 typedef SmallVector<UseVector, 5> RetUses;
471 // These vectors map each return value to the uses that make it MaybeLive, so
472 // we can add those to the Uses map if the return value really turns out to be
473 // MaybeLive. Initialized to a list of RetCount empty lists.
474 RetUses MaybeLiveRetUses(RetCount);
476 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
477 if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
478 if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
479 != F.getFunctionType()->getReturnType()) {
480 // We don't support old style multiple return values.
485 if (!F.hasLocalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
490 DEBUG(dbgs() << "DAE - Inspecting callers for fn: " << F.getName() << "\n");
491 // Keep track of the number of live retvals, so we can skip checks once all
492 // of them turn out to be live.
493 unsigned NumLiveRetVals = 0;
494 Type *STy = dyn_cast<StructType>(F.getReturnType());
495 // Loop all uses of the function.
496 for (Value::const_use_iterator I = F.use_begin(), E = F.use_end();
498 // If the function is PASSED IN as an argument, its address has been
500 ImmutableCallSite CS(*I);
501 if (!CS || !CS.isCallee(I)) {
506 // If this use is anything other than a call site, the function is alive.
507 const Instruction *TheCall = CS.getInstruction();
508 if (!TheCall) { // Not a direct call site?
513 // If we end up here, we are looking at a direct call to our function.
515 // Now, check how our return value(s) is/are used in this caller. Don't
516 // bother checking return values if all of them are live already.
517 if (NumLiveRetVals != RetCount) {
519 // Check all uses of the return value.
520 for (Value::const_use_iterator I = TheCall->use_begin(),
521 E = TheCall->use_end(); I != E; ++I) {
522 const ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(*I);
523 if (Ext && Ext->hasIndices()) {
524 // This use uses a part of our return value, survey the uses of
525 // that part and store the results for this index only.
526 unsigned Idx = *Ext->idx_begin();
527 if (RetValLiveness[Idx] != Live) {
528 RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
529 if (RetValLiveness[Idx] == Live)
533 // Used by something else than extractvalue. Mark all return
535 for (unsigned i = 0; i != RetCount; ++i )
536 RetValLiveness[i] = Live;
537 NumLiveRetVals = RetCount;
542 // Single return value
543 RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]);
544 if (RetValLiveness[0] == Live)
545 NumLiveRetVals = RetCount;
550 // Now we've inspected all callers, record the liveness of our return values.
551 for (unsigned i = 0; i != RetCount; ++i)
552 MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
554 DEBUG(dbgs() << "DAE - Inspecting args for fn: " << F.getName() << "\n");
556 // Now, check all of our arguments.
558 UseVector MaybeLiveArgUses;
559 for (Function::const_arg_iterator AI = F.arg_begin(),
560 E = F.arg_end(); AI != E; ++AI, ++i) {
561 // See what the effect of this use is (recording any uses that cause
562 // MaybeLive in MaybeLiveArgUses).
563 Liveness Result = SurveyUses(AI, MaybeLiveArgUses);
565 MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
566 // Clear the vector again for the next iteration.
567 MaybeLiveArgUses.clear();
571 /// MarkValue - This function marks the liveness of RA depending on L. If L is
572 /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
573 /// such that RA will be marked live if any use in MaybeLiveUses gets marked
575 void DAE::MarkValue(const RetOrArg &RA, Liveness L,
576 const UseVector &MaybeLiveUses) {
578 case Live: MarkLive(RA); break;
581 // Note any uses of this value, so this return value can be
582 // marked live whenever one of the uses becomes live.
583 for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
584 UE = MaybeLiveUses.end(); UI != UE; ++UI)
585 Uses.insert(std::make_pair(*UI, RA));
591 /// MarkLive - Mark the given Function as alive, meaning that it cannot be
592 /// changed in any way. Additionally,
593 /// mark any values that are used as this function's parameters or by its return
594 /// values (according to Uses) live as well.
595 void DAE::MarkLive(const Function &F) {
596 DEBUG(dbgs() << "DAE - Intrinsically live fn: " << F.getName() << "\n");
597 // Mark the function as live.
598 LiveFunctions.insert(&F);
599 // Mark all arguments as live.
600 for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
601 PropagateLiveness(CreateArg(&F, i));
602 // Mark all return values as live.
603 for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
604 PropagateLiveness(CreateRet(&F, i));
607 /// MarkLive - Mark the given return value or argument as live. Additionally,
608 /// mark any values that are used by this value (according to Uses) live as
610 void DAE::MarkLive(const RetOrArg &RA) {
611 if (LiveFunctions.count(RA.F))
612 return; // Function was already marked Live.
614 if (!LiveValues.insert(RA).second)
615 return; // We were already marked Live.
617 DEBUG(dbgs() << "DAE - Marking " << RA.getDescription() << " live\n");
618 PropagateLiveness(RA);
621 /// PropagateLiveness - Given that RA is a live value, propagate it's liveness
622 /// to any other values it uses (according to Uses).
623 void DAE::PropagateLiveness(const RetOrArg &RA) {
624 // We don't use upper_bound (or equal_range) here, because our recursive call
625 // to ourselves is likely to cause the upper_bound (which is the first value
626 // not belonging to RA) to become erased and the iterator invalidated.
627 UseMap::iterator Begin = Uses.lower_bound(RA);
628 UseMap::iterator E = Uses.end();
630 for (I = Begin; I != E && I->first == RA; ++I)
633 // Erase RA from the Uses map (from the lower bound to wherever we ended up
635 Uses.erase(Begin, I);
638 // RemoveDeadStuffFromFunction - Remove any arguments and return values from F
639 // that are not in LiveValues. Transform the function and all of the callees of
640 // the function to not have these arguments and return values.
642 bool DAE::RemoveDeadStuffFromFunction(Function *F) {
643 // Don't modify fully live functions
644 if (LiveFunctions.count(F))
647 // Start by computing a new prototype for the function, which is the same as
648 // the old function, but has fewer arguments and a different return type.
649 FunctionType *FTy = F->getFunctionType();
650 std::vector<Type*> Params;
652 // Set up to build a new list of parameter attributes.
653 SmallVector<AttributeWithIndex, 8> AttributesVec;
654 const AttrListPtr &PAL = F->getAttributes();
656 // The existing function return attributes.
657 Attributes RAttrs = PAL.getRetAttributes();
658 Attributes FnAttrs = PAL.getFnAttributes();
660 // Find out the new return value.
662 Type *RetTy = FTy->getReturnType();
664 unsigned RetCount = NumRetVals(F);
666 // -1 means unused, other numbers are the new index
667 SmallVector<int, 5> NewRetIdxs(RetCount, -1);
668 std::vector<Type*> RetTypes;
669 if (RetTy->isVoidTy()) {
672 StructType *STy = dyn_cast<StructType>(RetTy);
674 // Look at each of the original return values individually.
675 for (unsigned i = 0; i != RetCount; ++i) {
676 RetOrArg Ret = CreateRet(F, i);
677 if (LiveValues.erase(Ret)) {
678 RetTypes.push_back(STy->getElementType(i));
679 NewRetIdxs[i] = RetTypes.size() - 1;
681 ++NumRetValsEliminated;
682 DEBUG(dbgs() << "DAE - Removing return value " << i << " from "
683 << F->getName() << "\n");
687 // We used to return a single value.
688 if (LiveValues.erase(CreateRet(F, 0))) {
689 RetTypes.push_back(RetTy);
692 DEBUG(dbgs() << "DAE - Removing return value from " << F->getName()
694 ++NumRetValsEliminated;
696 if (RetTypes.size() > 1)
697 // More than one return type? Return a struct with them. Also, if we used
698 // to return a struct and didn't change the number of return values,
699 // return a struct again. This prevents changing {something} into
700 // something and {} into void.
701 // Make the new struct packed if we used to return a packed struct
703 NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked());
704 else if (RetTypes.size() == 1)
705 // One return type? Just a simple value then, but only if we didn't use to
706 // return a struct with that simple value before.
707 NRetTy = RetTypes.front();
708 else if (RetTypes.size() == 0)
709 // No return types? Make it void, but only if we didn't use to return {}.
710 NRetTy = Type::getVoidTy(F->getContext());
713 assert(NRetTy && "No new return type found?");
715 // Remove any incompatible attributes, but only if we removed all return
716 // values. Otherwise, ensure that we don't have any conflicting attributes
717 // here. Currently, this should not be possible, but special handling might be
718 // required when new return value attributes are added.
719 if (NRetTy->isVoidTy())
720 RAttrs &= ~Attributes::typeIncompatible(NRetTy);
722 assert((RAttrs & Attributes::typeIncompatible(NRetTy)) == 0
723 && "Return attributes no longer compatible?");
726 AttributesVec.push_back(AttributeWithIndex::get(0, RAttrs));
728 // Remember which arguments are still alive.
729 SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
730 // Construct the new parameter list from non-dead arguments. Also construct
731 // a new set of parameter attributes to correspond. Skip the first parameter
732 // attribute, since that belongs to the return value.
734 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
736 RetOrArg Arg = CreateArg(F, i);
737 if (LiveValues.erase(Arg)) {
738 Params.push_back(I->getType());
741 // Get the original parameter attributes (skipping the first one, that is
742 // for the return value.
743 if (Attributes Attrs = PAL.getParamAttributes(i + 1))
744 AttributesVec.push_back(AttributeWithIndex::get(Params.size(), Attrs));
746 ++NumArgumentsEliminated;
747 DEBUG(dbgs() << "DAE - Removing argument " << i << " (" << I->getName()
748 << ") from " << F->getName() << "\n");
752 if (FnAttrs != Attribute::None)
753 AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
755 // Reconstruct the AttributesList based on the vector we constructed.
756 AttrListPtr NewPAL = AttrListPtr::get(AttributesVec);
758 // Create the new function type based on the recomputed parameters.
759 FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
765 // Create the new function body and insert it into the module...
766 Function *NF = Function::Create(NFTy, F->getLinkage());
767 NF->copyAttributesFrom(F);
768 NF->setAttributes(NewPAL);
769 // Insert the new function before the old function, so we won't be processing
771 F->getParent()->getFunctionList().insert(F, NF);
774 // Loop over all of the callers of the function, transforming the call sites
775 // to pass in a smaller number of arguments into the new function.
777 std::vector<Value*> Args;
778 while (!F->use_empty()) {
779 CallSite CS(F->use_back());
780 Instruction *Call = CS.getInstruction();
782 AttributesVec.clear();
783 const AttrListPtr &CallPAL = CS.getAttributes();
785 // The call return attributes.
786 Attributes RAttrs = CallPAL.getRetAttributes();
787 Attributes FnAttrs = CallPAL.getFnAttributes();
788 // Adjust in case the function was changed to return void.
789 RAttrs &= ~Attributes::typeIncompatible(NF->getReturnType());
791 AttributesVec.push_back(AttributeWithIndex::get(0, RAttrs));
793 // Declare these outside of the loops, so we can reuse them for the second
794 // loop, which loops the varargs.
795 CallSite::arg_iterator I = CS.arg_begin();
797 // Loop over those operands, corresponding to the normal arguments to the
798 // original function, and add those that are still alive.
799 for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
802 // Get original parameter attributes, but skip return attributes.
803 if (Attributes Attrs = CallPAL.getParamAttributes(i + 1))
804 AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
807 // Push any varargs arguments on the list. Don't forget their attributes.
808 for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
810 if (Attributes Attrs = CallPAL.getParamAttributes(i + 1))
811 AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
814 if (FnAttrs != Attribute::None)
815 AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
817 // Reconstruct the AttributesList based on the vector we constructed.
818 AttrListPtr NewCallPAL = AttrListPtr::get(AttributesVec);
821 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
822 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
824 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
825 cast<InvokeInst>(New)->setAttributes(NewCallPAL);
827 New = CallInst::Create(NF, Args, "", Call);
828 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
829 cast<CallInst>(New)->setAttributes(NewCallPAL);
830 if (cast<CallInst>(Call)->isTailCall())
831 cast<CallInst>(New)->setTailCall();
833 New->setDebugLoc(Call->getDebugLoc());
837 if (!Call->use_empty()) {
838 if (New->getType() == Call->getType()) {
839 // Return type not changed? Just replace users then.
840 Call->replaceAllUsesWith(New);
842 } else if (New->getType()->isVoidTy()) {
843 // Our return value has uses, but they will get removed later on.
844 // Replace by null for now.
845 if (!Call->getType()->isX86_MMXTy())
846 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
848 assert(RetTy->isStructTy() &&
849 "Return type changed, but not into a void. The old return type"
850 " must have been a struct!");
851 Instruction *InsertPt = Call;
852 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
853 BasicBlock::iterator IP = II->getNormalDest()->begin();
854 while (isa<PHINode>(IP)) ++IP;
858 // We used to return a struct. Instead of doing smart stuff with all the
859 // uses of this struct, we will just rebuild it using
860 // extract/insertvalue chaining and let instcombine clean that up.
862 // Start out building up our return value from undef
863 Value *RetVal = UndefValue::get(RetTy);
864 for (unsigned i = 0; i != RetCount; ++i)
865 if (NewRetIdxs[i] != -1) {
867 if (RetTypes.size() > 1)
868 // We are still returning a struct, so extract the value from our
870 V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret",
873 // We are now returning a single element, so just insert that
875 // Insert the value at the old position
876 RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt);
878 // Now, replace all uses of the old call instruction with the return
880 Call->replaceAllUsesWith(RetVal);
885 // Finally, remove the old call from the program, reducing the use-count of
887 Call->eraseFromParent();
890 // Since we have now created the new function, splice the body of the old
891 // function right into the new function, leaving the old rotting hulk of the
893 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
895 // Loop over the argument list, transferring uses of the old arguments over to
896 // the new arguments, also transferring over the names as well.
898 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
899 I2 = NF->arg_begin(); I != E; ++I, ++i)
901 // If this is a live argument, move the name and users over to the new
903 I->replaceAllUsesWith(I2);
907 // If this argument is dead, replace any uses of it with null constants
908 // (these are guaranteed to become unused later on).
909 if (!I->getType()->isX86_MMXTy())
910 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
913 // If we change the return value of the function we must rewrite any return
914 // instructions. Check this now.
915 if (F->getReturnType() != NF->getReturnType())
916 for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
917 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
920 if (NFTy->getReturnType()->isVoidTy()) {
923 assert (RetTy->isStructTy());
924 // The original return value was a struct, insert
925 // extractvalue/insertvalue chains to extract only the values we need
926 // to return and insert them into our new result.
927 // This does generate messy code, but we'll let it to instcombine to
929 Value *OldRet = RI->getOperand(0);
930 // Start out building up our return value from undef
931 RetVal = UndefValue::get(NRetTy);
932 for (unsigned i = 0; i != RetCount; ++i)
933 if (NewRetIdxs[i] != -1) {
934 ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
936 if (RetTypes.size() > 1) {
937 // We're still returning a struct, so reinsert the value into
938 // our new return value at the new index
940 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
943 // We are now only returning a simple value, so just return the
949 // Replace the return instruction with one returning the new return
950 // value (possibly 0 if we became void).
951 ReturnInst::Create(F->getContext(), RetVal, RI);
952 BB->getInstList().erase(RI);
955 // Now that the old function is dead, delete it.
956 F->eraseFromParent();
961 bool DAE::runOnModule(Module &M) {
962 bool Changed = false;
964 // First pass: Do a simple check to see if any functions can have their "..."
965 // removed. We can do this if they never call va_start. This loop cannot be
966 // fused with the next loop, because deleting a function invalidates
967 // information computed while surveying other functions.
968 DEBUG(dbgs() << "DAE - Deleting dead varargs\n");
969 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
971 if (F.getFunctionType()->isVarArg())
972 Changed |= DeleteDeadVarargs(F);
975 // Second phase:loop through the module, determining which arguments are live.
976 // We assume all arguments are dead unless proven otherwise (allowing us to
977 // determine that dead arguments passed into recursive functions are dead).
979 DEBUG(dbgs() << "DAE - Determining liveness\n");
980 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
983 // Now, remove all dead arguments and return values from each function in
985 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
986 // Increment now, because the function will probably get removed (ie.
987 // replaced by a new one).
989 Changed |= RemoveDeadStuffFromFunction(F);
992 // Finally, look for any unused parameters in functions with non-local
993 // linkage and replace the passed in parameters with undef.
994 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
997 Changed |= RemoveDeadArgumentsFromCallers(F);