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