LLVM API Documentation

DeadArgumentElimination.cpp
Go to the documentation of this file.
00001 //===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass deletes dead arguments from internal functions.  Dead argument
00011 // elimination removes arguments which are directly dead, as well as arguments
00012 // only passed into function calls as dead arguments of other functions.  This
00013 // pass also deletes dead return values in a similar way.
00014 //
00015 // This pass is often useful as a cleanup pass to run after aggressive
00016 // interprocedural passes, which add possibly-dead arguments or return values.
00017 //
00018 //===----------------------------------------------------------------------===//
00019 
00020 #include "llvm/Transforms/IPO.h"
00021 #include "llvm/ADT/DenseMap.h"
00022 #include "llvm/ADT/SmallVector.h"
00023 #include "llvm/ADT/Statistic.h"
00024 #include "llvm/ADT/StringExtras.h"
00025 #include "llvm/IR/CallSite.h"
00026 #include "llvm/IR/CallingConv.h"
00027 #include "llvm/IR/Constant.h"
00028 #include "llvm/IR/DIBuilder.h"
00029 #include "llvm/IR/DebugInfo.h"
00030 #include "llvm/IR/DerivedTypes.h"
00031 #include "llvm/IR/Instructions.h"
00032 #include "llvm/IR/IntrinsicInst.h"
00033 #include "llvm/IR/LLVMContext.h"
00034 #include "llvm/IR/Module.h"
00035 #include "llvm/Pass.h"
00036 #include "llvm/Support/Debug.h"
00037 #include "llvm/Support/raw_ostream.h"
00038 #include <map>
00039 #include <set>
00040 using namespace llvm;
00041 
00042 #define DEBUG_TYPE "deadargelim"
00043 
00044 STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
00045 STATISTIC(NumRetValsEliminated  , "Number of unused return values removed");
00046 STATISTIC(NumArgumentsReplacedWithUndef, 
00047           "Number of unread args replaced with undef");
00048 namespace {
00049   /// DAE - The dead argument elimination pass.
00050   ///
00051   class DAE : public ModulePass {
00052   public:
00053 
00054     /// Struct that represents (part of) either a return value or a function
00055     /// argument.  Used so that arguments and return values can be used
00056     /// interchangeably.
00057     struct RetOrArg {
00058       RetOrArg(const Function *F, unsigned Idx, bool IsArg) : F(F), Idx(Idx),
00059                IsArg(IsArg) {}
00060       const Function *F;
00061       unsigned Idx;
00062       bool IsArg;
00063 
00064       /// Make RetOrArg comparable, so we can put it into a map.
00065       bool operator<(const RetOrArg &O) const {
00066         return std::tie(F, Idx, IsArg) < std::tie(O.F, O.Idx, O.IsArg);
00067       }
00068 
00069       /// Make RetOrArg comparable, so we can easily iterate the multimap.
00070       bool operator==(const RetOrArg &O) const {
00071         return F == O.F && Idx == O.Idx && IsArg == O.IsArg;
00072       }
00073 
00074       std::string getDescription() const {
00075         return std::string((IsArg ? "Argument #" : "Return value #"))
00076                + utostr(Idx) + " of function " + F->getName().str();
00077       }
00078     };
00079 
00080     /// Liveness enum - During our initial pass over the program, we determine
00081     /// that things are either alive or maybe alive. We don't mark anything
00082     /// explicitly dead (even if we know they are), since anything not alive
00083     /// with no registered uses (in Uses) will never be marked alive and will
00084     /// thus become dead in the end.
00085     enum Liveness { Live, MaybeLive };
00086 
00087     /// Convenience wrapper
00088     RetOrArg CreateRet(const Function *F, unsigned Idx) {
00089       return RetOrArg(F, Idx, false);
00090     }
00091     /// Convenience wrapper
00092     RetOrArg CreateArg(const Function *F, unsigned Idx) {
00093       return RetOrArg(F, Idx, true);
00094     }
00095 
00096     typedef std::multimap<RetOrArg, RetOrArg> UseMap;
00097     /// This maps a return value or argument to any MaybeLive return values or
00098     /// arguments it uses. This allows the MaybeLive values to be marked live
00099     /// when any of its users is marked live.
00100     /// For example (indices are left out for clarity):
00101     ///  - Uses[ret F] = ret G
00102     ///    This means that F calls G, and F returns the value returned by G.
00103     ///  - Uses[arg F] = ret G
00104     ///    This means that some function calls G and passes its result as an
00105     ///    argument to F.
00106     ///  - Uses[ret F] = arg F
00107     ///    This means that F returns one of its own arguments.
00108     ///  - Uses[arg F] = arg G
00109     ///    This means that G calls F and passes one of its own (G's) arguments
00110     ///    directly to F.
00111     UseMap Uses;
00112 
00113     typedef std::set<RetOrArg> LiveSet;
00114     typedef std::set<const Function*> LiveFuncSet;
00115 
00116     /// This set contains all values that have been determined to be live.
00117     LiveSet LiveValues;
00118     /// This set contains all values that are cannot be changed in any way.
00119     LiveFuncSet LiveFunctions;
00120 
00121     typedef SmallVector<RetOrArg, 5> UseVector;
00122 
00123     // Map each LLVM function to corresponding metadata with debug info. If
00124     // the function is replaced with another one, we should patch the pointer
00125     // to LLVM function in metadata.
00126     // As the code generation for module is finished (and DIBuilder is
00127     // finalized) we assume that subprogram descriptors won't be changed, and
00128     // they are stored in map for short duration anyway.
00129     typedef DenseMap<Function*, DISubprogram> FunctionDIMap;
00130     FunctionDIMap FunctionDIs;
00131 
00132   protected:
00133     // DAH uses this to specify a different ID.
00134     explicit DAE(char &ID) : ModulePass(ID) {}
00135 
00136   public:
00137     static char ID; // Pass identification, replacement for typeid
00138     DAE() : ModulePass(ID) {
00139       initializeDAEPass(*PassRegistry::getPassRegistry());
00140     }
00141 
00142     bool runOnModule(Module &M) override;
00143 
00144     virtual bool ShouldHackArguments() const { return false; }
00145 
00146   private:
00147     Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
00148     Liveness SurveyUse(const Use *U, UseVector &MaybeLiveUses,
00149                        unsigned RetValNum = 0);
00150     Liveness SurveyUses(const Value *V, UseVector &MaybeLiveUses);
00151 
00152     void CollectFunctionDIs(Module &M);
00153     void SurveyFunction(const Function &F);
00154     void MarkValue(const RetOrArg &RA, Liveness L,
00155                    const UseVector &MaybeLiveUses);
00156     void MarkLive(const RetOrArg &RA);
00157     void MarkLive(const Function &F);
00158     void PropagateLiveness(const RetOrArg &RA);
00159     bool RemoveDeadStuffFromFunction(Function *F);
00160     bool DeleteDeadVarargs(Function &Fn);
00161     bool RemoveDeadArgumentsFromCallers(Function &Fn);
00162   };
00163 }
00164 
00165 
00166 char DAE::ID = 0;
00167 INITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false)
00168 
00169 namespace {
00170   /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
00171   /// deletes arguments to functions which are external.  This is only for use
00172   /// by bugpoint.
00173   struct DAH : public DAE {
00174     static char ID;
00175     DAH() : DAE(ID) {}
00176 
00177     bool ShouldHackArguments() const override { return true; }
00178   };
00179 }
00180 
00181 char DAH::ID = 0;
00182 INITIALIZE_PASS(DAH, "deadarghaX0r", 
00183                 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)",
00184                 false, false)
00185 
00186 /// createDeadArgEliminationPass - This pass removes arguments from functions
00187 /// which are not used by the body of the function.
00188 ///
00189 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
00190 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
00191 
00192 /// CollectFunctionDIs - Map each function in the module to its debug info
00193 /// descriptor.
00194 void DAE::CollectFunctionDIs(Module &M) {
00195   FunctionDIs.clear();
00196 
00197   for (Module::named_metadata_iterator I = M.named_metadata_begin(),
00198        E = M.named_metadata_end(); I != E; ++I) {
00199     NamedMDNode &NMD = *I;
00200     for (unsigned MDIndex = 0, MDNum = NMD.getNumOperands();
00201          MDIndex < MDNum; ++MDIndex) {
00202       MDNode *Node = NMD.getOperand(MDIndex);
00203       if (!DIDescriptor(Node).isCompileUnit())
00204         continue;
00205       DICompileUnit CU(Node);
00206       const DIArray &SPs = CU.getSubprograms();
00207       for (unsigned SPIndex = 0, SPNum = SPs.getNumElements();
00208            SPIndex < SPNum; ++SPIndex) {
00209         DISubprogram SP(SPs.getElement(SPIndex));
00210         assert((!SP || SP.isSubprogram()) &&
00211           "A MDNode in subprograms of a CU should be null or a DISubprogram.");
00212         if (!SP)
00213           continue;
00214         if (Function *F = SP.getFunction())
00215           FunctionDIs[F] = SP;
00216       }
00217     }
00218   }
00219 }
00220 
00221 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if
00222 /// llvm.vastart is never called, the varargs list is dead for the function.
00223 bool DAE::DeleteDeadVarargs(Function &Fn) {
00224   assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
00225   if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false;
00226 
00227   // Ensure that the function is only directly called.
00228   if (Fn.hasAddressTaken())
00229     return false;
00230 
00231   // Okay, we know we can transform this function if safe.  Scan its body
00232   // looking for calls to llvm.vastart.
00233   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
00234     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00235       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00236         if (II->getIntrinsicID() == Intrinsic::vastart)
00237           return false;
00238       }
00239     }
00240   }
00241 
00242   // If we get here, there are no calls to llvm.vastart in the function body,
00243   // remove the "..." and adjust all the calls.
00244 
00245   // Start by computing a new prototype for the function, which is the same as
00246   // the old function, but doesn't have isVarArg set.
00247   FunctionType *FTy = Fn.getFunctionType();
00248 
00249   std::vector<Type*> Params(FTy->param_begin(), FTy->param_end());
00250   FunctionType *NFTy = FunctionType::get(FTy->getReturnType(),
00251                                                 Params, false);
00252   unsigned NumArgs = Params.size();
00253 
00254   // Create the new function body and insert it into the module...
00255   Function *NF = Function::Create(NFTy, Fn.getLinkage());
00256   NF->copyAttributesFrom(&Fn);
00257   Fn.getParent()->getFunctionList().insert(&Fn, NF);
00258   NF->takeName(&Fn);
00259 
00260   // Loop over all of the callers of the function, transforming the call sites
00261   // to pass in a smaller number of arguments into the new function.
00262   //
00263   std::vector<Value*> Args;
00264   for (Value::user_iterator I = Fn.user_begin(), E = Fn.user_end(); I != E; ) {
00265     CallSite CS(*I++);
00266     if (!CS)
00267       continue;
00268     Instruction *Call = CS.getInstruction();
00269 
00270     // Pass all the same arguments.
00271     Args.assign(CS.arg_begin(), CS.arg_begin() + NumArgs);
00272 
00273     // Drop any attributes that were on the vararg arguments.
00274     AttributeSet PAL = CS.getAttributes();
00275     if (!PAL.isEmpty() && PAL.getSlotIndex(PAL.getNumSlots() - 1) > NumArgs) {
00276       SmallVector<AttributeSet, 8> AttributesVec;
00277       for (unsigned i = 0; PAL.getSlotIndex(i) <= NumArgs; ++i)
00278         AttributesVec.push_back(PAL.getSlotAttributes(i));
00279       if (PAL.hasAttributes(AttributeSet::FunctionIndex))
00280         AttributesVec.push_back(AttributeSet::get(Fn.getContext(),
00281                                                   PAL.getFnAttributes()));
00282       PAL = AttributeSet::get(Fn.getContext(), AttributesVec);
00283     }
00284 
00285     Instruction *New;
00286     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
00287       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
00288                                Args, "", Call);
00289       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
00290       cast<InvokeInst>(New)->setAttributes(PAL);
00291     } else {
00292       New = CallInst::Create(NF, Args, "", Call);
00293       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
00294       cast<CallInst>(New)->setAttributes(PAL);
00295       if (cast<CallInst>(Call)->isTailCall())
00296         cast<CallInst>(New)->setTailCall();
00297     }
00298     New->setDebugLoc(Call->getDebugLoc());
00299 
00300     Args.clear();
00301 
00302     if (!Call->use_empty())
00303       Call->replaceAllUsesWith(New);
00304 
00305     New->takeName(Call);
00306 
00307     // Finally, remove the old call from the program, reducing the use-count of
00308     // F.
00309     Call->eraseFromParent();
00310   }
00311 
00312   // Since we have now created the new function, splice the body of the old
00313   // function right into the new function, leaving the old rotting hulk of the
00314   // function empty.
00315   NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
00316 
00317   // Loop over the argument list, transferring uses of the old arguments over to
00318   // the new arguments, also transferring over the names as well.  While we're at
00319   // it, remove the dead arguments from the DeadArguments list.
00320   //
00321   for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
00322        I2 = NF->arg_begin(); I != E; ++I, ++I2) {
00323     // Move the name and users over to the new version.
00324     I->replaceAllUsesWith(I2);
00325     I2->takeName(I);
00326   }
00327 
00328   // Patch the pointer to LLVM function in debug info descriptor.
00329   FunctionDIMap::iterator DI = FunctionDIs.find(&Fn);
00330   if (DI != FunctionDIs.end())
00331     DI->second.replaceFunction(NF);
00332 
00333   // Fix up any BlockAddresses that refer to the function.
00334   Fn.replaceAllUsesWith(ConstantExpr::getBitCast(NF, Fn.getType()));
00335   // Delete the bitcast that we just created, so that NF does not
00336   // appear to be address-taken.
00337   NF->removeDeadConstantUsers();
00338   // Finally, nuke the old function.
00339   Fn.eraseFromParent();
00340   return true;
00341 }
00342 
00343 /// RemoveDeadArgumentsFromCallers - Checks if the given function has any 
00344 /// arguments that are unused, and changes the caller parameters to be undefined
00345 /// instead.
00346 bool DAE::RemoveDeadArgumentsFromCallers(Function &Fn)
00347 {
00348   if (Fn.isDeclaration() || Fn.mayBeOverridden())
00349     return false;
00350 
00351   // Functions with local linkage should already have been handled, except the
00352   // fragile (variadic) ones which we can improve here.
00353   if (Fn.hasLocalLinkage() && !Fn.getFunctionType()->isVarArg())
00354     return false;
00355 
00356   // If a function seen at compile time is not necessarily the one linked to
00357   // the binary being built, it is illegal to change the actual arguments
00358   // passed to it. These functions can be captured by isWeakForLinker().
00359   // *NOTE* that mayBeOverridden() is insufficient for this purpose as it
00360   // doesn't include linkage types like AvailableExternallyLinkage and
00361   // LinkOnceODRLinkage. Take link_odr* as an example, it indicates a set of
00362   // *EQUIVALENT* globals that can be merged at link-time. However, the
00363   // semantic of *EQUIVALENT*-functions includes parameters. Changing
00364   // parameters breaks this assumption.
00365   //
00366   if (Fn.isWeakForLinker())
00367     return false;
00368 
00369   if (Fn.use_empty())
00370     return false;
00371 
00372   SmallVector<unsigned, 8> UnusedArgs;
00373   for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(); 
00374        I != E; ++I) {
00375     Argument *Arg = I;
00376 
00377     if (Arg->use_empty() && !Arg->hasByValOrInAllocaAttr())
00378       UnusedArgs.push_back(Arg->getArgNo());
00379   }
00380 
00381   if (UnusedArgs.empty())
00382     return false;
00383 
00384   bool Changed = false;
00385 
00386   for (Use &U : Fn.uses()) {
00387     CallSite CS(U.getUser());
00388     if (!CS || !CS.isCallee(&U))
00389       continue;
00390 
00391     // Now go through all unused args and replace them with "undef".
00392     for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) {
00393       unsigned ArgNo = UnusedArgs[I];
00394 
00395       Value *Arg = CS.getArgument(ArgNo);
00396       CS.setArgument(ArgNo, UndefValue::get(Arg->getType()));
00397       ++NumArgumentsReplacedWithUndef;
00398       Changed = true;
00399     }
00400   }
00401 
00402   return Changed;
00403 }
00404 
00405 /// Convenience function that returns the number of return values. It returns 0
00406 /// for void functions and 1 for functions not returning a struct. It returns
00407 /// the number of struct elements for functions returning a struct.
00408 static unsigned NumRetVals(const Function *F) {
00409   if (F->getReturnType()->isVoidTy())
00410     return 0;
00411   else if (StructType *STy = dyn_cast<StructType>(F->getReturnType()))
00412     return STy->getNumElements();
00413   else
00414     return 1;
00415 }
00416 
00417 /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
00418 /// live, it adds Use to the MaybeLiveUses argument. Returns the determined
00419 /// liveness of Use.
00420 DAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
00421   // We're live if our use or its Function is already marked as live.
00422   if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
00423     return Live;
00424 
00425   // We're maybe live otherwise, but remember that we must become live if
00426   // Use becomes live.
00427   MaybeLiveUses.push_back(Use);
00428   return MaybeLive;
00429 }
00430 
00431 
00432 /// SurveyUse - This looks at a single use of an argument or return value
00433 /// and determines if it should be alive or not. Adds this use to MaybeLiveUses
00434 /// if it causes the used value to become MaybeLive.
00435 ///
00436 /// RetValNum is the return value number to use when this use is used in a
00437 /// return instruction. This is used in the recursion, you should always leave
00438 /// it at 0.
00439 DAE::Liveness DAE::SurveyUse(const Use *U,
00440                              UseVector &MaybeLiveUses, unsigned RetValNum) {
00441     const User *V = U->getUser();
00442     if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
00443       // The value is returned from a function. It's only live when the
00444       // function's return value is live. We use RetValNum here, for the case
00445       // that U is really a use of an insertvalue instruction that uses the
00446       // original Use.
00447       RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
00448       // We might be live, depending on the liveness of Use.
00449       return MarkIfNotLive(Use, MaybeLiveUses);
00450     }
00451     if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
00452       if (U->getOperandNo() != InsertValueInst::getAggregateOperandIndex()
00453           && IV->hasIndices())
00454         // The use we are examining is inserted into an aggregate. Our liveness
00455         // depends on all uses of that aggregate, but if it is used as a return
00456         // value, only index at which we were inserted counts.
00457         RetValNum = *IV->idx_begin();
00458 
00459       // Note that if we are used as the aggregate operand to the insertvalue,
00460       // we don't change RetValNum, but do survey all our uses.
00461 
00462       Liveness Result = MaybeLive;
00463       for (const Use &UU : IV->uses()) {
00464         Result = SurveyUse(&UU, MaybeLiveUses, RetValNum);
00465         if (Result == Live)
00466           break;
00467       }
00468       return Result;
00469     }
00470 
00471     if (ImmutableCallSite CS = V) {
00472       const Function *F = CS.getCalledFunction();
00473       if (F) {
00474         // Used in a direct call.
00475 
00476         // Find the argument number. We know for sure that this use is an
00477         // argument, since if it was the function argument this would be an
00478         // indirect call and the we know can't be looking at a value of the
00479         // label type (for the invoke instruction).
00480         unsigned ArgNo = CS.getArgumentNo(U);
00481 
00482         if (ArgNo >= F->getFunctionType()->getNumParams())
00483           // The value is passed in through a vararg! Must be live.
00484           return Live;
00485 
00486         assert(CS.getArgument(ArgNo)
00487                == CS->getOperand(U->getOperandNo())
00488                && "Argument is not where we expected it");
00489 
00490         // Value passed to a normal call. It's only live when the corresponding
00491         // argument to the called function turns out live.
00492         RetOrArg Use = CreateArg(F, ArgNo);
00493         return MarkIfNotLive(Use, MaybeLiveUses);
00494       }
00495     }
00496     // Used in any other way? Value must be live.
00497     return Live;
00498 }
00499 
00500 /// SurveyUses - This looks at all the uses of the given value
00501 /// Returns the Liveness deduced from the uses of this value.
00502 ///
00503 /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
00504 /// the result is Live, MaybeLiveUses might be modified but its content should
00505 /// be ignored (since it might not be complete).
00506 DAE::Liveness DAE::SurveyUses(const Value *V, UseVector &MaybeLiveUses) {
00507   // Assume it's dead (which will only hold if there are no uses at all..).
00508   Liveness Result = MaybeLive;
00509   // Check each use.
00510   for (const Use &U : V->uses()) {
00511     Result = SurveyUse(&U, MaybeLiveUses);
00512     if (Result == Live)
00513       break;
00514   }
00515   return Result;
00516 }
00517 
00518 // SurveyFunction - This performs the initial survey of the specified function,
00519 // checking out whether or not it uses any of its incoming arguments or whether
00520 // any callers use the return value.  This fills in the LiveValues set and Uses
00521 // map.
00522 //
00523 // We consider arguments of non-internal functions to be intrinsically alive as
00524 // well as arguments to functions which have their "address taken".
00525 //
00526 void DAE::SurveyFunction(const Function &F) {
00527   // Functions with inalloca parameters are expecting args in a particular
00528   // register and memory layout.
00529   if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca)) {
00530     MarkLive(F);
00531     return;
00532   }
00533 
00534   unsigned RetCount = NumRetVals(&F);
00535   // Assume all return values are dead
00536   typedef SmallVector<Liveness, 5> RetVals;
00537   RetVals RetValLiveness(RetCount, MaybeLive);
00538 
00539   typedef SmallVector<UseVector, 5> RetUses;
00540   // These vectors map each return value to the uses that make it MaybeLive, so
00541   // we can add those to the Uses map if the return value really turns out to be
00542   // MaybeLive. Initialized to a list of RetCount empty lists.
00543   RetUses MaybeLiveRetUses(RetCount);
00544 
00545   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00546     if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
00547       if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
00548           != F.getFunctionType()->getReturnType()) {
00549         // We don't support old style multiple return values.
00550         MarkLive(F);
00551         return;
00552       }
00553 
00554   if (!F.hasLocalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
00555     MarkLive(F);
00556     return;
00557   }
00558 
00559   DEBUG(dbgs() << "DAE - Inspecting callers for fn: " << F.getName() << "\n");
00560   // Keep track of the number of live retvals, so we can skip checks once all
00561   // of them turn out to be live.
00562   unsigned NumLiveRetVals = 0;
00563   Type *STy = dyn_cast<StructType>(F.getReturnType());
00564   // Loop all uses of the function.
00565   for (const Use &U : F.uses()) {
00566     // If the function is PASSED IN as an argument, its address has been
00567     // taken.
00568     ImmutableCallSite CS(U.getUser());
00569     if (!CS || !CS.isCallee(&U)) {
00570       MarkLive(F);
00571       return;
00572     }
00573 
00574     // If this use is anything other than a call site, the function is alive.
00575     const Instruction *TheCall = CS.getInstruction();
00576     if (!TheCall) {   // Not a direct call site?
00577       MarkLive(F);
00578       return;
00579     }
00580 
00581     // If we end up here, we are looking at a direct call to our function.
00582 
00583     // Now, check how our return value(s) is/are used in this caller. Don't
00584     // bother checking return values if all of them are live already.
00585     if (NumLiveRetVals != RetCount) {
00586       if (STy) {
00587         // Check all uses of the return value.
00588         for (const User *U : TheCall->users()) {
00589           const ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(U);
00590           if (Ext && Ext->hasIndices()) {
00591             // This use uses a part of our return value, survey the uses of
00592             // that part and store the results for this index only.
00593             unsigned Idx = *Ext->idx_begin();
00594             if (RetValLiveness[Idx] != Live) {
00595               RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
00596               if (RetValLiveness[Idx] == Live)
00597                 NumLiveRetVals++;
00598             }
00599           } else {
00600             // Used by something else than extractvalue. Mark all return
00601             // values as live.
00602             for (unsigned i = 0; i != RetCount; ++i )
00603               RetValLiveness[i] = Live;
00604             NumLiveRetVals = RetCount;
00605             break;
00606           }
00607         }
00608       } else {
00609         // Single return value
00610         RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]);
00611         if (RetValLiveness[0] == Live)
00612           NumLiveRetVals = RetCount;
00613       }
00614     }
00615   }
00616 
00617   // Now we've inspected all callers, record the liveness of our return values.
00618   for (unsigned i = 0; i != RetCount; ++i)
00619     MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
00620 
00621   DEBUG(dbgs() << "DAE - Inspecting args for fn: " << F.getName() << "\n");
00622 
00623   // Now, check all of our arguments.
00624   unsigned i = 0;
00625   UseVector MaybeLiveArgUses;
00626   for (Function::const_arg_iterator AI = F.arg_begin(),
00627        E = F.arg_end(); AI != E; ++AI, ++i) {
00628     Liveness Result;
00629     if (F.getFunctionType()->isVarArg()) {
00630       // Variadic functions will already have a va_arg function expanded inside
00631       // them, making them potentially very sensitive to ABI changes resulting
00632       // from removing arguments entirely, so don't. For example AArch64 handles
00633       // register and stack HFAs very differently, and this is reflected in the
00634       // IR which has already been generated.
00635       Result = Live;
00636     } else {
00637       // See what the effect of this use is (recording any uses that cause
00638       // MaybeLive in MaybeLiveArgUses). 
00639       Result = SurveyUses(AI, MaybeLiveArgUses);
00640     }
00641 
00642     // Mark the result.
00643     MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
00644     // Clear the vector again for the next iteration.
00645     MaybeLiveArgUses.clear();
00646   }
00647 }
00648 
00649 /// MarkValue - This function marks the liveness of RA depending on L. If L is
00650 /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
00651 /// such that RA will be marked live if any use in MaybeLiveUses gets marked
00652 /// live later on.
00653 void DAE::MarkValue(const RetOrArg &RA, Liveness L,
00654                     const UseVector &MaybeLiveUses) {
00655   switch (L) {
00656     case Live: MarkLive(RA); break;
00657     case MaybeLive:
00658     {
00659       // Note any uses of this value, so this return value can be
00660       // marked live whenever one of the uses becomes live.
00661       for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
00662            UE = MaybeLiveUses.end(); UI != UE; ++UI)
00663         Uses.insert(std::make_pair(*UI, RA));
00664       break;
00665     }
00666   }
00667 }
00668 
00669 /// MarkLive - Mark the given Function as alive, meaning that it cannot be
00670 /// changed in any way. Additionally,
00671 /// mark any values that are used as this function's parameters or by its return
00672 /// values (according to Uses) live as well.
00673 void DAE::MarkLive(const Function &F) {
00674   DEBUG(dbgs() << "DAE - Intrinsically live fn: " << F.getName() << "\n");
00675   // Mark the function as live.
00676   LiveFunctions.insert(&F);
00677   // Mark all arguments as live.
00678   for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
00679     PropagateLiveness(CreateArg(&F, i));
00680   // Mark all return values as live.
00681   for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
00682     PropagateLiveness(CreateRet(&F, i));
00683 }
00684 
00685 /// MarkLive - Mark the given return value or argument as live. Additionally,
00686 /// mark any values that are used by this value (according to Uses) live as
00687 /// well.
00688 void DAE::MarkLive(const RetOrArg &RA) {
00689   if (LiveFunctions.count(RA.F))
00690     return; // Function was already marked Live.
00691 
00692   if (!LiveValues.insert(RA).second)
00693     return; // We were already marked Live.
00694 
00695   DEBUG(dbgs() << "DAE - Marking " << RA.getDescription() << " live\n");
00696   PropagateLiveness(RA);
00697 }
00698 
00699 /// PropagateLiveness - Given that RA is a live value, propagate it's liveness
00700 /// to any other values it uses (according to Uses).
00701 void DAE::PropagateLiveness(const RetOrArg &RA) {
00702   // We don't use upper_bound (or equal_range) here, because our recursive call
00703   // to ourselves is likely to cause the upper_bound (which is the first value
00704   // not belonging to RA) to become erased and the iterator invalidated.
00705   UseMap::iterator Begin = Uses.lower_bound(RA);
00706   UseMap::iterator E = Uses.end();
00707   UseMap::iterator I;
00708   for (I = Begin; I != E && I->first == RA; ++I)
00709     MarkLive(I->second);
00710 
00711   // Erase RA from the Uses map (from the lower bound to wherever we ended up
00712   // after the loop).
00713   Uses.erase(Begin, I);
00714 }
00715 
00716 // RemoveDeadStuffFromFunction - Remove any arguments and return values from F
00717 // that are not in LiveValues. Transform the function and all of the callees of
00718 // the function to not have these arguments and return values.
00719 //
00720 bool DAE::RemoveDeadStuffFromFunction(Function *F) {
00721   // Don't modify fully live functions
00722   if (LiveFunctions.count(F))
00723     return false;
00724 
00725   // Start by computing a new prototype for the function, which is the same as
00726   // the old function, but has fewer arguments and a different return type.
00727   FunctionType *FTy = F->getFunctionType();
00728   std::vector<Type*> Params;
00729 
00730   // Keep track of if we have a live 'returned' argument
00731   bool HasLiveReturnedArg = false;
00732 
00733   // Set up to build a new list of parameter attributes.
00734   SmallVector<AttributeSet, 8> AttributesVec;
00735   const AttributeSet &PAL = F->getAttributes();
00736 
00737   // Remember which arguments are still alive.
00738   SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
00739   // Construct the new parameter list from non-dead arguments. Also construct
00740   // a new set of parameter attributes to correspond. Skip the first parameter
00741   // attribute, since that belongs to the return value.
00742   unsigned i = 0;
00743   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
00744        I != E; ++I, ++i) {
00745     RetOrArg Arg = CreateArg(F, i);
00746     if (LiveValues.erase(Arg)) {
00747       Params.push_back(I->getType());
00748       ArgAlive[i] = true;
00749 
00750       // Get the original parameter attributes (skipping the first one, that is
00751       // for the return value.
00752       if (PAL.hasAttributes(i + 1)) {
00753         AttrBuilder B(PAL, i + 1);
00754         if (B.contains(Attribute::Returned))
00755           HasLiveReturnedArg = true;
00756         AttributesVec.
00757           push_back(AttributeSet::get(F->getContext(), Params.size(), B));
00758       }
00759     } else {
00760       ++NumArgumentsEliminated;
00761       DEBUG(dbgs() << "DAE - Removing argument " << i << " (" << I->getName()
00762             << ") from " << F->getName() << "\n");
00763     }
00764   }
00765 
00766   // Find out the new return value.
00767   Type *RetTy = FTy->getReturnType();
00768   Type *NRetTy = NULL;
00769   unsigned RetCount = NumRetVals(F);
00770 
00771   // -1 means unused, other numbers are the new index
00772   SmallVector<int, 5> NewRetIdxs(RetCount, -1);
00773   std::vector<Type*> RetTypes;
00774 
00775   // If there is a function with a live 'returned' argument but a dead return
00776   // value, then there are two possible actions:
00777   // 1) Eliminate the return value and take off the 'returned' attribute on the
00778   //    argument.
00779   // 2) Retain the 'returned' attribute and treat the return value (but not the
00780   //    entire function) as live so that it is not eliminated.
00781   // 
00782   // It's not clear in the general case which option is more profitable because,
00783   // even in the absence of explicit uses of the return value, code generation
00784   // is free to use the 'returned' attribute to do things like eliding
00785   // save/restores of registers across calls. Whether or not this happens is
00786   // target and ABI-specific as well as depending on the amount of register
00787   // pressure, so there's no good way for an IR-level pass to figure this out.
00788   //
00789   // Fortunately, the only places where 'returned' is currently generated by
00790   // the FE are places where 'returned' is basically free and almost always a
00791   // performance win, so the second option can just be used always for now.
00792   //
00793   // This should be revisited if 'returned' is ever applied more liberally.
00794   if (RetTy->isVoidTy() || HasLiveReturnedArg) {
00795     NRetTy = RetTy;
00796   } else {
00797     StructType *STy = dyn_cast<StructType>(RetTy);
00798     if (STy)
00799       // Look at each of the original return values individually.
00800       for (unsigned i = 0; i != RetCount; ++i) {
00801         RetOrArg Ret = CreateRet(F, i);
00802         if (LiveValues.erase(Ret)) {
00803           RetTypes.push_back(STy->getElementType(i));
00804           NewRetIdxs[i] = RetTypes.size() - 1;
00805         } else {
00806           ++NumRetValsEliminated;
00807           DEBUG(dbgs() << "DAE - Removing return value " << i << " from "
00808                 << F->getName() << "\n");
00809         }
00810       }
00811     else
00812       // We used to return a single value.
00813       if (LiveValues.erase(CreateRet(F, 0))) {
00814         RetTypes.push_back(RetTy);
00815         NewRetIdxs[0] = 0;
00816       } else {
00817         DEBUG(dbgs() << "DAE - Removing return value from " << F->getName()
00818               << "\n");
00819         ++NumRetValsEliminated;
00820       }
00821     if (RetTypes.size() > 1)
00822       // More than one return type? Return a struct with them. Also, if we used
00823       // to return a struct and didn't change the number of return values,
00824       // return a struct again. This prevents changing {something} into
00825       // something and {} into void.
00826       // Make the new struct packed if we used to return a packed struct
00827       // already.
00828       NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked());
00829     else if (RetTypes.size() == 1)
00830       // One return type? Just a simple value then, but only if we didn't use to
00831       // return a struct with that simple value before.
00832       NRetTy = RetTypes.front();
00833     else if (RetTypes.size() == 0)
00834       // No return types? Make it void, but only if we didn't use to return {}.
00835       NRetTy = Type::getVoidTy(F->getContext());
00836   }
00837 
00838   assert(NRetTy && "No new return type found?");
00839 
00840   // The existing function return attributes.
00841   AttributeSet RAttrs = PAL.getRetAttributes();
00842 
00843   // Remove any incompatible attributes, but only if we removed all return
00844   // values. Otherwise, ensure that we don't have any conflicting attributes
00845   // here. Currently, this should not be possible, but special handling might be
00846   // required when new return value attributes are added.
00847   if (NRetTy->isVoidTy())
00848     RAttrs =
00849       AttributeSet::get(NRetTy->getContext(), AttributeSet::ReturnIndex,
00850                         AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
00851          removeAttributes(AttributeFuncs::
00852                           typeIncompatible(NRetTy, AttributeSet::ReturnIndex),
00853                           AttributeSet::ReturnIndex));
00854   else
00855     assert(!AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
00856              hasAttributes(AttributeFuncs::
00857                            typeIncompatible(NRetTy, AttributeSet::ReturnIndex),
00858                            AttributeSet::ReturnIndex) &&
00859            "Return attributes no longer compatible?");
00860 
00861   if (RAttrs.hasAttributes(AttributeSet::ReturnIndex))
00862     AttributesVec.push_back(AttributeSet::get(NRetTy->getContext(), RAttrs));
00863 
00864   if (PAL.hasAttributes(AttributeSet::FunctionIndex))
00865     AttributesVec.push_back(AttributeSet::get(F->getContext(),
00866                                               PAL.getFnAttributes()));
00867 
00868   // Reconstruct the AttributesList based on the vector we constructed.
00869   AttributeSet NewPAL = AttributeSet::get(F->getContext(), AttributesVec);
00870 
00871   // Create the new function type based on the recomputed parameters.
00872   FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
00873 
00874   // No change?
00875   if (NFTy == FTy)
00876     return false;
00877 
00878   // Create the new function body and insert it into the module...
00879   Function *NF = Function::Create(NFTy, F->getLinkage());
00880   NF->copyAttributesFrom(F);
00881   NF->setAttributes(NewPAL);
00882   // Insert the new function before the old function, so we won't be processing
00883   // it again.
00884   F->getParent()->getFunctionList().insert(F, NF);
00885   NF->takeName(F);
00886 
00887   // Loop over all of the callers of the function, transforming the call sites
00888   // to pass in a smaller number of arguments into the new function.
00889   //
00890   std::vector<Value*> Args;
00891   while (!F->use_empty()) {
00892     CallSite CS(F->user_back());
00893     Instruction *Call = CS.getInstruction();
00894 
00895     AttributesVec.clear();
00896     const AttributeSet &CallPAL = CS.getAttributes();
00897 
00898     // The call return attributes.
00899     AttributeSet RAttrs = CallPAL.getRetAttributes();
00900 
00901     // Adjust in case the function was changed to return void.
00902     RAttrs =
00903       AttributeSet::get(NF->getContext(), AttributeSet::ReturnIndex,
00904                         AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
00905         removeAttributes(AttributeFuncs::
00906                          typeIncompatible(NF->getReturnType(),
00907                                           AttributeSet::ReturnIndex),
00908                          AttributeSet::ReturnIndex));
00909     if (RAttrs.hasAttributes(AttributeSet::ReturnIndex))
00910       AttributesVec.push_back(AttributeSet::get(NF->getContext(), RAttrs));
00911 
00912     // Declare these outside of the loops, so we can reuse them for the second
00913     // loop, which loops the varargs.
00914     CallSite::arg_iterator I = CS.arg_begin();
00915     unsigned i = 0;
00916     // Loop over those operands, corresponding to the normal arguments to the
00917     // original function, and add those that are still alive.
00918     for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
00919       if (ArgAlive[i]) {
00920         Args.push_back(*I);
00921         // Get original parameter attributes, but skip return attributes.
00922         if (CallPAL.hasAttributes(i + 1)) {
00923           AttrBuilder B(CallPAL, i + 1);
00924           // If the return type has changed, then get rid of 'returned' on the
00925           // call site. The alternative is to make all 'returned' attributes on
00926           // call sites keep the return value alive just like 'returned'
00927           // attributes on function declaration but it's less clearly a win
00928           // and this is not an expected case anyway
00929           if (NRetTy != RetTy && B.contains(Attribute::Returned))
00930             B.removeAttribute(Attribute::Returned);
00931           AttributesVec.
00932             push_back(AttributeSet::get(F->getContext(), Args.size(), B));
00933         }
00934       }
00935 
00936     // Push any varargs arguments on the list. Don't forget their attributes.
00937     for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
00938       Args.push_back(*I);
00939       if (CallPAL.hasAttributes(i + 1)) {
00940         AttrBuilder B(CallPAL, i + 1);
00941         AttributesVec.
00942           push_back(AttributeSet::get(F->getContext(), Args.size(), B));
00943       }
00944     }
00945 
00946     if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
00947       AttributesVec.push_back(AttributeSet::get(Call->getContext(),
00948                                                 CallPAL.getFnAttributes()));
00949 
00950     // Reconstruct the AttributesList based on the vector we constructed.
00951     AttributeSet NewCallPAL = AttributeSet::get(F->getContext(), AttributesVec);
00952 
00953     Instruction *New;
00954     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
00955       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
00956                                Args, "", Call);
00957       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
00958       cast<InvokeInst>(New)->setAttributes(NewCallPAL);
00959     } else {
00960       New = CallInst::Create(NF, Args, "", Call);
00961       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
00962       cast<CallInst>(New)->setAttributes(NewCallPAL);
00963       if (cast<CallInst>(Call)->isTailCall())
00964         cast<CallInst>(New)->setTailCall();
00965     }
00966     New->setDebugLoc(Call->getDebugLoc());
00967 
00968     Args.clear();
00969 
00970     if (!Call->use_empty()) {
00971       if (New->getType() == Call->getType()) {
00972         // Return type not changed? Just replace users then.
00973         Call->replaceAllUsesWith(New);
00974         New->takeName(Call);
00975       } else if (New->getType()->isVoidTy()) {
00976         // Our return value has uses, but they will get removed later on.
00977         // Replace by null for now.
00978         if (!Call->getType()->isX86_MMXTy())
00979           Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
00980       } else {
00981         assert(RetTy->isStructTy() &&
00982                "Return type changed, but not into a void. The old return type"
00983                " must have been a struct!");
00984         Instruction *InsertPt = Call;
00985         if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
00986           BasicBlock::iterator IP = II->getNormalDest()->begin();
00987           while (isa<PHINode>(IP)) ++IP;
00988           InsertPt = IP;
00989         }
00990 
00991         // We used to return a struct. Instead of doing smart stuff with all the
00992         // uses of this struct, we will just rebuild it using
00993         // extract/insertvalue chaining and let instcombine clean that up.
00994         //
00995         // Start out building up our return value from undef
00996         Value *RetVal = UndefValue::get(RetTy);
00997         for (unsigned i = 0; i != RetCount; ++i)
00998           if (NewRetIdxs[i] != -1) {
00999             Value *V;
01000             if (RetTypes.size() > 1)
01001               // We are still returning a struct, so extract the value from our
01002               // return value
01003               V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret",
01004                                            InsertPt);
01005             else
01006               // We are now returning a single element, so just insert that
01007               V = New;
01008             // Insert the value at the old position
01009             RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt);
01010           }
01011         // Now, replace all uses of the old call instruction with the return
01012         // struct we built
01013         Call->replaceAllUsesWith(RetVal);
01014         New->takeName(Call);
01015       }
01016     }
01017 
01018     // Finally, remove the old call from the program, reducing the use-count of
01019     // F.
01020     Call->eraseFromParent();
01021   }
01022 
01023   // Since we have now created the new function, splice the body of the old
01024   // function right into the new function, leaving the old rotting hulk of the
01025   // function empty.
01026   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
01027 
01028   // Loop over the argument list, transferring uses of the old arguments over to
01029   // the new arguments, also transferring over the names as well.
01030   i = 0;
01031   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
01032        I2 = NF->arg_begin(); I != E; ++I, ++i)
01033     if (ArgAlive[i]) {
01034       // If this is a live argument, move the name and users over to the new
01035       // version.
01036       I->replaceAllUsesWith(I2);
01037       I2->takeName(I);
01038       ++I2;
01039     } else {
01040       // If this argument is dead, replace any uses of it with null constants
01041       // (these are guaranteed to become unused later on).
01042       if (!I->getType()->isX86_MMXTy())
01043         I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
01044     }
01045 
01046   // If we change the return value of the function we must rewrite any return
01047   // instructions.  Check this now.
01048   if (F->getReturnType() != NF->getReturnType())
01049     for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
01050       if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
01051         Value *RetVal;
01052 
01053         if (NFTy->getReturnType()->isVoidTy()) {
01054           RetVal = 0;
01055         } else {
01056           assert (RetTy->isStructTy());
01057           // The original return value was a struct, insert
01058           // extractvalue/insertvalue chains to extract only the values we need
01059           // to return and insert them into our new result.
01060           // This does generate messy code, but we'll let it to instcombine to
01061           // clean that up.
01062           Value *OldRet = RI->getOperand(0);
01063           // Start out building up our return value from undef
01064           RetVal = UndefValue::get(NRetTy);
01065           for (unsigned i = 0; i != RetCount; ++i)
01066             if (NewRetIdxs[i] != -1) {
01067               ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
01068                                                               "oldret", RI);
01069               if (RetTypes.size() > 1) {
01070                 // We're still returning a struct, so reinsert the value into
01071                 // our new return value at the new index
01072 
01073                 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
01074                                                  "newret", RI);
01075               } else {
01076                 // We are now only returning a simple value, so just return the
01077                 // extracted value.
01078                 RetVal = EV;
01079               }
01080             }
01081         }
01082         // Replace the return instruction with one returning the new return
01083         // value (possibly 0 if we became void).
01084         ReturnInst::Create(F->getContext(), RetVal, RI);
01085         BB->getInstList().erase(RI);
01086       }
01087 
01088   // Patch the pointer to LLVM function in debug info descriptor.
01089   FunctionDIMap::iterator DI = FunctionDIs.find(F);
01090   if (DI != FunctionDIs.end())
01091     DI->second.replaceFunction(NF);
01092 
01093   // Now that the old function is dead, delete it.
01094   F->eraseFromParent();
01095 
01096   return true;
01097 }
01098 
01099 bool DAE::runOnModule(Module &M) {
01100   bool Changed = false;
01101 
01102   // Collect debug info descriptors for functions.
01103   CollectFunctionDIs(M);
01104 
01105   // First pass: Do a simple check to see if any functions can have their "..."
01106   // removed.  We can do this if they never call va_start.  This loop cannot be
01107   // fused with the next loop, because deleting a function invalidates
01108   // information computed while surveying other functions.
01109   DEBUG(dbgs() << "DAE - Deleting dead varargs\n");
01110   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
01111     Function &F = *I++;
01112     if (F.getFunctionType()->isVarArg())
01113       Changed |= DeleteDeadVarargs(F);
01114   }
01115 
01116   // Second phase:loop through the module, determining which arguments are live.
01117   // We assume all arguments are dead unless proven otherwise (allowing us to
01118   // determine that dead arguments passed into recursive functions are dead).
01119   //
01120   DEBUG(dbgs() << "DAE - Determining liveness\n");
01121   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
01122     SurveyFunction(*I);
01123 
01124   // Now, remove all dead arguments and return values from each function in
01125   // turn.
01126   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
01127     // Increment now, because the function will probably get removed (ie.
01128     // replaced by a new one).
01129     Function *F = I++;
01130     Changed |= RemoveDeadStuffFromFunction(F);
01131   }
01132 
01133   // Finally, look for any unused parameters in functions with non-local
01134   // linkage and replace the passed in parameters with undef.
01135   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
01136     Function& F = *I;
01137 
01138     Changed |= RemoveDeadArgumentsFromCallers(F);
01139   }
01140 
01141   return Changed;
01142 }