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 #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 std::string((IsArg ? "Argument #" : "Return value #"))
00077                + utostr(Idx) + " 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 = 0);
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   if (F->getReturnType()->isVoidTy())
00391     return 0;
00392   else if (StructType *STy = dyn_cast<StructType>(F->getReturnType()))
00393     return STy->getNumElements();
00394   else
00395     return 1;
00396 }
00397 
00398 /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
00399 /// live, it adds Use to the MaybeLiveUses argument. Returns the determined
00400 /// liveness of Use.
00401 DAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
00402   // We're live if our use or its Function is already marked as live.
00403   if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
00404     return Live;
00405 
00406   // We're maybe live otherwise, but remember that we must become live if
00407   // Use becomes live.
00408   MaybeLiveUses.push_back(Use);
00409   return MaybeLive;
00410 }
00411 
00412 
00413 /// SurveyUse - This looks at a single use of an argument or return value
00414 /// and determines if it should be alive or not. Adds this use to MaybeLiveUses
00415 /// if it causes the used value to become MaybeLive.
00416 ///
00417 /// RetValNum is the return value number to use when this use is used in a
00418 /// return instruction. This is used in the recursion, you should always leave
00419 /// it at 0.
00420 DAE::Liveness DAE::SurveyUse(const Use *U,
00421                              UseVector &MaybeLiveUses, unsigned RetValNum) {
00422     const User *V = U->getUser();
00423     if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
00424       // The value is returned from a function. It's only live when the
00425       // function's return value is live. We use RetValNum here, for the case
00426       // that U is really a use of an insertvalue instruction that uses the
00427       // original Use.
00428       RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
00429       // We might be live, depending on the liveness of Use.
00430       return MarkIfNotLive(Use, MaybeLiveUses);
00431     }
00432     if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
00433       if (U->getOperandNo() != InsertValueInst::getAggregateOperandIndex()
00434           && IV->hasIndices())
00435         // The use we are examining is inserted into an aggregate. Our liveness
00436         // depends on all uses of that aggregate, but if it is used as a return
00437         // value, only index at which we were inserted counts.
00438         RetValNum = *IV->idx_begin();
00439 
00440       // Note that if we are used as the aggregate operand to the insertvalue,
00441       // we don't change RetValNum, but do survey all our uses.
00442 
00443       Liveness Result = MaybeLive;
00444       for (const Use &UU : IV->uses()) {
00445         Result = SurveyUse(&UU, MaybeLiveUses, RetValNum);
00446         if (Result == Live)
00447           break;
00448       }
00449       return Result;
00450     }
00451 
00452     if (ImmutableCallSite CS = V) {
00453       const Function *F = CS.getCalledFunction();
00454       if (F) {
00455         // Used in a direct call.
00456 
00457         // Find the argument number. We know for sure that this use is an
00458         // argument, since if it was the function argument this would be an
00459         // indirect call and the we know can't be looking at a value of the
00460         // label type (for the invoke instruction).
00461         unsigned ArgNo = CS.getArgumentNo(U);
00462 
00463         if (ArgNo >= F->getFunctionType()->getNumParams())
00464           // The value is passed in through a vararg! Must be live.
00465           return Live;
00466 
00467         assert(CS.getArgument(ArgNo)
00468                == CS->getOperand(U->getOperandNo())
00469                && "Argument is not where we expected it");
00470 
00471         // Value passed to a normal call. It's only live when the corresponding
00472         // argument to the called function turns out live.
00473         RetOrArg Use = CreateArg(F, ArgNo);
00474         return MarkIfNotLive(Use, MaybeLiveUses);
00475       }
00476     }
00477     // Used in any other way? Value must be live.
00478     return Live;
00479 }
00480 
00481 /// SurveyUses - This looks at all the uses of the given value
00482 /// Returns the Liveness deduced from the uses of this value.
00483 ///
00484 /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
00485 /// the result is Live, MaybeLiveUses might be modified but its content should
00486 /// be ignored (since it might not be complete).
00487 DAE::Liveness DAE::SurveyUses(const Value *V, UseVector &MaybeLiveUses) {
00488   // Assume it's dead (which will only hold if there are no uses at all..).
00489   Liveness Result = MaybeLive;
00490   // Check each use.
00491   for (const Use &U : V->uses()) {
00492     Result = SurveyUse(&U, MaybeLiveUses);
00493     if (Result == Live)
00494       break;
00495   }
00496   return Result;
00497 }
00498 
00499 // SurveyFunction - This performs the initial survey of the specified function,
00500 // checking out whether or not it uses any of its incoming arguments or whether
00501 // any callers use the return value.  This fills in the LiveValues set and Uses
00502 // map.
00503 //
00504 // We consider arguments of non-internal functions to be intrinsically alive as
00505 // well as arguments to functions which have their "address taken".
00506 //
00507 void DAE::SurveyFunction(const Function &F) {
00508   // Functions with inalloca parameters are expecting args in a particular
00509   // register and memory layout.
00510   if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca)) {
00511     MarkLive(F);
00512     return;
00513   }
00514 
00515   unsigned RetCount = NumRetVals(&F);
00516   // Assume all return values are dead
00517   typedef SmallVector<Liveness, 5> RetVals;
00518   RetVals RetValLiveness(RetCount, MaybeLive);
00519 
00520   typedef SmallVector<UseVector, 5> RetUses;
00521   // These vectors map each return value to the uses that make it MaybeLive, so
00522   // we can add those to the Uses map if the return value really turns out to be
00523   // MaybeLive. Initialized to a list of RetCount empty lists.
00524   RetUses MaybeLiveRetUses(RetCount);
00525 
00526   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00527     if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
00528       if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
00529           != F.getFunctionType()->getReturnType()) {
00530         // We don't support old style multiple return values.
00531         MarkLive(F);
00532         return;
00533       }
00534 
00535   if (!F.hasLocalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
00536     MarkLive(F);
00537     return;
00538   }
00539 
00540   DEBUG(dbgs() << "DAE - Inspecting callers for fn: " << F.getName() << "\n");
00541   // Keep track of the number of live retvals, so we can skip checks once all
00542   // of them turn out to be live.
00543   unsigned NumLiveRetVals = 0;
00544   Type *STy = dyn_cast<StructType>(F.getReturnType());
00545   // Loop all uses of the function.
00546   for (const Use &U : F.uses()) {
00547     // If the function is PASSED IN as an argument, its address has been
00548     // taken.
00549     ImmutableCallSite CS(U.getUser());
00550     if (!CS || !CS.isCallee(&U)) {
00551       MarkLive(F);
00552       return;
00553     }
00554 
00555     // If this use is anything other than a call site, the function is alive.
00556     const Instruction *TheCall = CS.getInstruction();
00557     if (!TheCall) {   // Not a direct call site?
00558       MarkLive(F);
00559       return;
00560     }
00561 
00562     // If we end up here, we are looking at a direct call to our function.
00563 
00564     // Now, check how our return value(s) is/are used in this caller. Don't
00565     // bother checking return values if all of them are live already.
00566     if (NumLiveRetVals != RetCount) {
00567       if (STy) {
00568         // Check all uses of the return value.
00569         for (const User *U : TheCall->users()) {
00570           const ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(U);
00571           if (Ext && Ext->hasIndices()) {
00572             // This use uses a part of our return value, survey the uses of
00573             // that part and store the results for this index only.
00574             unsigned Idx = *Ext->idx_begin();
00575             if (RetValLiveness[Idx] != Live) {
00576               RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
00577               if (RetValLiveness[Idx] == Live)
00578                 NumLiveRetVals++;
00579             }
00580           } else {
00581             // Used by something else than extractvalue. Mark all return
00582             // values as live.
00583             for (unsigned i = 0; i != RetCount; ++i )
00584               RetValLiveness[i] = Live;
00585             NumLiveRetVals = RetCount;
00586             break;
00587           }
00588         }
00589       } else {
00590         // Single return value
00591         RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]);
00592         if (RetValLiveness[0] == Live)
00593           NumLiveRetVals = RetCount;
00594       }
00595     }
00596   }
00597 
00598   // Now we've inspected all callers, record the liveness of our return values.
00599   for (unsigned i = 0; i != RetCount; ++i)
00600     MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
00601 
00602   DEBUG(dbgs() << "DAE - Inspecting args for fn: " << F.getName() << "\n");
00603 
00604   // Now, check all of our arguments.
00605   unsigned i = 0;
00606   UseVector MaybeLiveArgUses;
00607   for (Function::const_arg_iterator AI = F.arg_begin(),
00608        E = F.arg_end(); AI != E; ++AI, ++i) {
00609     Liveness Result;
00610     if (F.getFunctionType()->isVarArg()) {
00611       // Variadic functions will already have a va_arg function expanded inside
00612       // them, making them potentially very sensitive to ABI changes resulting
00613       // from removing arguments entirely, so don't. For example AArch64 handles
00614       // register and stack HFAs very differently, and this is reflected in the
00615       // IR which has already been generated.
00616       Result = Live;
00617     } else {
00618       // See what the effect of this use is (recording any uses that cause
00619       // MaybeLive in MaybeLiveArgUses). 
00620       Result = SurveyUses(AI, MaybeLiveArgUses);
00621     }
00622 
00623     // Mark the result.
00624     MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
00625     // Clear the vector again for the next iteration.
00626     MaybeLiveArgUses.clear();
00627   }
00628 }
00629 
00630 /// MarkValue - This function marks the liveness of RA depending on L. If L is
00631 /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
00632 /// such that RA will be marked live if any use in MaybeLiveUses gets marked
00633 /// live later on.
00634 void DAE::MarkValue(const RetOrArg &RA, Liveness L,
00635                     const UseVector &MaybeLiveUses) {
00636   switch (L) {
00637     case Live: MarkLive(RA); break;
00638     case MaybeLive:
00639     {
00640       // Note any uses of this value, so this return value can be
00641       // marked live whenever one of the uses becomes live.
00642       for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
00643            UE = MaybeLiveUses.end(); UI != UE; ++UI)
00644         Uses.insert(std::make_pair(*UI, RA));
00645       break;
00646     }
00647   }
00648 }
00649 
00650 /// MarkLive - Mark the given Function as alive, meaning that it cannot be
00651 /// changed in any way. Additionally,
00652 /// mark any values that are used as this function's parameters or by its return
00653 /// values (according to Uses) live as well.
00654 void DAE::MarkLive(const Function &F) {
00655   DEBUG(dbgs() << "DAE - Intrinsically live fn: " << F.getName() << "\n");
00656   // Mark the function as live.
00657   LiveFunctions.insert(&F);
00658   // Mark all arguments as live.
00659   for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
00660     PropagateLiveness(CreateArg(&F, i));
00661   // Mark all return values as live.
00662   for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
00663     PropagateLiveness(CreateRet(&F, i));
00664 }
00665 
00666 /// MarkLive - Mark the given return value or argument as live. Additionally,
00667 /// mark any values that are used by this value (according to Uses) live as
00668 /// well.
00669 void DAE::MarkLive(const RetOrArg &RA) {
00670   if (LiveFunctions.count(RA.F))
00671     return; // Function was already marked Live.
00672 
00673   if (!LiveValues.insert(RA).second)
00674     return; // We were already marked Live.
00675 
00676   DEBUG(dbgs() << "DAE - Marking " << RA.getDescription() << " live\n");
00677   PropagateLiveness(RA);
00678 }
00679 
00680 /// PropagateLiveness - Given that RA is a live value, propagate it's liveness
00681 /// to any other values it uses (according to Uses).
00682 void DAE::PropagateLiveness(const RetOrArg &RA) {
00683   // We don't use upper_bound (or equal_range) here, because our recursive call
00684   // to ourselves is likely to cause the upper_bound (which is the first value
00685   // not belonging to RA) to become erased and the iterator invalidated.
00686   UseMap::iterator Begin = Uses.lower_bound(RA);
00687   UseMap::iterator E = Uses.end();
00688   UseMap::iterator I;
00689   for (I = Begin; I != E && I->first == RA; ++I)
00690     MarkLive(I->second);
00691 
00692   // Erase RA from the Uses map (from the lower bound to wherever we ended up
00693   // after the loop).
00694   Uses.erase(Begin, I);
00695 }
00696 
00697 // RemoveDeadStuffFromFunction - Remove any arguments and return values from F
00698 // that are not in LiveValues. Transform the function and all of the callees of
00699 // the function to not have these arguments and return values.
00700 //
00701 bool DAE::RemoveDeadStuffFromFunction(Function *F) {
00702   // Don't modify fully live functions
00703   if (LiveFunctions.count(F))
00704     return false;
00705 
00706   // Start by computing a new prototype for the function, which is the same as
00707   // the old function, but has fewer arguments and a different return type.
00708   FunctionType *FTy = F->getFunctionType();
00709   std::vector<Type*> Params;
00710 
00711   // Keep track of if we have a live 'returned' argument
00712   bool HasLiveReturnedArg = false;
00713 
00714   // Set up to build a new list of parameter attributes.
00715   SmallVector<AttributeSet, 8> AttributesVec;
00716   const AttributeSet &PAL = F->getAttributes();
00717 
00718   // Remember which arguments are still alive.
00719   SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
00720   // Construct the new parameter list from non-dead arguments. Also construct
00721   // a new set of parameter attributes to correspond. Skip the first parameter
00722   // attribute, since that belongs to the return value.
00723   unsigned i = 0;
00724   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
00725        I != E; ++I, ++i) {
00726     RetOrArg Arg = CreateArg(F, i);
00727     if (LiveValues.erase(Arg)) {
00728       Params.push_back(I->getType());
00729       ArgAlive[i] = true;
00730 
00731       // Get the original parameter attributes (skipping the first one, that is
00732       // for the return value.
00733       if (PAL.hasAttributes(i + 1)) {
00734         AttrBuilder B(PAL, i + 1);
00735         if (B.contains(Attribute::Returned))
00736           HasLiveReturnedArg = true;
00737         AttributesVec.
00738           push_back(AttributeSet::get(F->getContext(), Params.size(), B));
00739       }
00740     } else {
00741       ++NumArgumentsEliminated;
00742       DEBUG(dbgs() << "DAE - Removing argument " << i << " (" << I->getName()
00743             << ") from " << F->getName() << "\n");
00744     }
00745   }
00746 
00747   // Find out the new return value.
00748   Type *RetTy = FTy->getReturnType();
00749   Type *NRetTy = nullptr;
00750   unsigned RetCount = NumRetVals(F);
00751 
00752   // -1 means unused, other numbers are the new index
00753   SmallVector<int, 5> NewRetIdxs(RetCount, -1);
00754   std::vector<Type*> RetTypes;
00755 
00756   // If there is a function with a live 'returned' argument but a dead return
00757   // value, then there are two possible actions:
00758   // 1) Eliminate the return value and take off the 'returned' attribute on the
00759   //    argument.
00760   // 2) Retain the 'returned' attribute and treat the return value (but not the
00761   //    entire function) as live so that it is not eliminated.
00762   // 
00763   // It's not clear in the general case which option is more profitable because,
00764   // even in the absence of explicit uses of the return value, code generation
00765   // is free to use the 'returned' attribute to do things like eliding
00766   // save/restores of registers across calls. Whether or not this happens is
00767   // target and ABI-specific as well as depending on the amount of register
00768   // pressure, so there's no good way for an IR-level pass to figure this out.
00769   //
00770   // Fortunately, the only places where 'returned' is currently generated by
00771   // the FE are places where 'returned' is basically free and almost always a
00772   // performance win, so the second option can just be used always for now.
00773   //
00774   // This should be revisited if 'returned' is ever applied more liberally.
00775   if (RetTy->isVoidTy() || HasLiveReturnedArg) {
00776     NRetTy = RetTy;
00777   } else {
00778     StructType *STy = dyn_cast<StructType>(RetTy);
00779     if (STy)
00780       // Look at each of the original return values individually.
00781       for (unsigned i = 0; i != RetCount; ++i) {
00782         RetOrArg Ret = CreateRet(F, i);
00783         if (LiveValues.erase(Ret)) {
00784           RetTypes.push_back(STy->getElementType(i));
00785           NewRetIdxs[i] = RetTypes.size() - 1;
00786         } else {
00787           ++NumRetValsEliminated;
00788           DEBUG(dbgs() << "DAE - Removing return value " << i << " from "
00789                 << F->getName() << "\n");
00790         }
00791       }
00792     else
00793       // We used to return a single value.
00794       if (LiveValues.erase(CreateRet(F, 0))) {
00795         RetTypes.push_back(RetTy);
00796         NewRetIdxs[0] = 0;
00797       } else {
00798         DEBUG(dbgs() << "DAE - Removing return value from " << F->getName()
00799               << "\n");
00800         ++NumRetValsEliminated;
00801       }
00802     if (RetTypes.size() > 1)
00803       // More than one return type? Return a struct with them. Also, if we used
00804       // to return a struct and didn't change the number of return values,
00805       // return a struct again. This prevents changing {something} into
00806       // something and {} into void.
00807       // Make the new struct packed if we used to return a packed struct
00808       // already.
00809       NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked());
00810     else if (RetTypes.size() == 1)
00811       // One return type? Just a simple value then, but only if we didn't use to
00812       // return a struct with that simple value before.
00813       NRetTy = RetTypes.front();
00814     else if (RetTypes.size() == 0)
00815       // No return types? Make it void, but only if we didn't use to return {}.
00816       NRetTy = Type::getVoidTy(F->getContext());
00817   }
00818 
00819   assert(NRetTy && "No new return type found?");
00820 
00821   // The existing function return attributes.
00822   AttributeSet RAttrs = PAL.getRetAttributes();
00823 
00824   // Remove any incompatible attributes, but only if we removed all return
00825   // values. Otherwise, ensure that we don't have any conflicting attributes
00826   // here. Currently, this should not be possible, but special handling might be
00827   // required when new return value attributes are added.
00828   if (NRetTy->isVoidTy())
00829     RAttrs =
00830       AttributeSet::get(NRetTy->getContext(), AttributeSet::ReturnIndex,
00831                         AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
00832          removeAttributes(AttributeFuncs::
00833                           typeIncompatible(NRetTy, AttributeSet::ReturnIndex),
00834                           AttributeSet::ReturnIndex));
00835   else
00836     assert(!AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
00837              hasAttributes(AttributeFuncs::
00838                            typeIncompatible(NRetTy, AttributeSet::ReturnIndex),
00839                            AttributeSet::ReturnIndex) &&
00840            "Return attributes no longer compatible?");
00841 
00842   if (RAttrs.hasAttributes(AttributeSet::ReturnIndex))
00843     AttributesVec.push_back(AttributeSet::get(NRetTy->getContext(), RAttrs));
00844 
00845   if (PAL.hasAttributes(AttributeSet::FunctionIndex))
00846     AttributesVec.push_back(AttributeSet::get(F->getContext(),
00847                                               PAL.getFnAttributes()));
00848 
00849   // Reconstruct the AttributesList based on the vector we constructed.
00850   AttributeSet NewPAL = AttributeSet::get(F->getContext(), AttributesVec);
00851 
00852   // Create the new function type based on the recomputed parameters.
00853   FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
00854 
00855   // No change?
00856   if (NFTy == FTy)
00857     return false;
00858 
00859   // Create the new function body and insert it into the module...
00860   Function *NF = Function::Create(NFTy, F->getLinkage());
00861   NF->copyAttributesFrom(F);
00862   NF->setAttributes(NewPAL);
00863   // Insert the new function before the old function, so we won't be processing
00864   // it again.
00865   F->getParent()->getFunctionList().insert(F, NF);
00866   NF->takeName(F);
00867 
00868   // Loop over all of the callers of the function, transforming the call sites
00869   // to pass in a smaller number of arguments into the new function.
00870   //
00871   std::vector<Value*> Args;
00872   while (!F->use_empty()) {
00873     CallSite CS(F->user_back());
00874     Instruction *Call = CS.getInstruction();
00875 
00876     AttributesVec.clear();
00877     const AttributeSet &CallPAL = CS.getAttributes();
00878 
00879     // The call return attributes.
00880     AttributeSet RAttrs = CallPAL.getRetAttributes();
00881 
00882     // Adjust in case the function was changed to return void.
00883     RAttrs =
00884       AttributeSet::get(NF->getContext(), AttributeSet::ReturnIndex,
00885                         AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
00886         removeAttributes(AttributeFuncs::
00887                          typeIncompatible(NF->getReturnType(),
00888                                           AttributeSet::ReturnIndex),
00889                          AttributeSet::ReturnIndex));
00890     if (RAttrs.hasAttributes(AttributeSet::ReturnIndex))
00891       AttributesVec.push_back(AttributeSet::get(NF->getContext(), RAttrs));
00892 
00893     // Declare these outside of the loops, so we can reuse them for the second
00894     // loop, which loops the varargs.
00895     CallSite::arg_iterator I = CS.arg_begin();
00896     unsigned i = 0;
00897     // Loop over those operands, corresponding to the normal arguments to the
00898     // original function, and add those that are still alive.
00899     for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
00900       if (ArgAlive[i]) {
00901         Args.push_back(*I);
00902         // Get original parameter attributes, but skip return attributes.
00903         if (CallPAL.hasAttributes(i + 1)) {
00904           AttrBuilder B(CallPAL, i + 1);
00905           // If the return type has changed, then get rid of 'returned' on the
00906           // call site. The alternative is to make all 'returned' attributes on
00907           // call sites keep the return value alive just like 'returned'
00908           // attributes on function declaration but it's less clearly a win
00909           // and this is not an expected case anyway
00910           if (NRetTy != RetTy && B.contains(Attribute::Returned))
00911             B.removeAttribute(Attribute::Returned);
00912           AttributesVec.
00913             push_back(AttributeSet::get(F->getContext(), Args.size(), B));
00914         }
00915       }
00916 
00917     // Push any varargs arguments on the list. Don't forget their attributes.
00918     for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
00919       Args.push_back(*I);
00920       if (CallPAL.hasAttributes(i + 1)) {
00921         AttrBuilder B(CallPAL, i + 1);
00922         AttributesVec.
00923           push_back(AttributeSet::get(F->getContext(), Args.size(), B));
00924       }
00925     }
00926 
00927     if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
00928       AttributesVec.push_back(AttributeSet::get(Call->getContext(),
00929                                                 CallPAL.getFnAttributes()));
00930 
00931     // Reconstruct the AttributesList based on the vector we constructed.
00932     AttributeSet NewCallPAL = AttributeSet::get(F->getContext(), AttributesVec);
00933 
00934     Instruction *New;
00935     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
00936       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
00937                                Args, "", Call);
00938       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
00939       cast<InvokeInst>(New)->setAttributes(NewCallPAL);
00940     } else {
00941       New = CallInst::Create(NF, Args, "", Call);
00942       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
00943       cast<CallInst>(New)->setAttributes(NewCallPAL);
00944       if (cast<CallInst>(Call)->isTailCall())
00945         cast<CallInst>(New)->setTailCall();
00946     }
00947     New->setDebugLoc(Call->getDebugLoc());
00948 
00949     Args.clear();
00950 
00951     if (!Call->use_empty()) {
00952       if (New->getType() == Call->getType()) {
00953         // Return type not changed? Just replace users then.
00954         Call->replaceAllUsesWith(New);
00955         New->takeName(Call);
00956       } else if (New->getType()->isVoidTy()) {
00957         // Our return value has uses, but they will get removed later on.
00958         // Replace by null for now.
00959         if (!Call->getType()->isX86_MMXTy())
00960           Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
00961       } else {
00962         assert(RetTy->isStructTy() &&
00963                "Return type changed, but not into a void. The old return type"
00964                " must have been a struct!");
00965         Instruction *InsertPt = Call;
00966         if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
00967           BasicBlock::iterator IP = II->getNormalDest()->begin();
00968           while (isa<PHINode>(IP)) ++IP;
00969           InsertPt = IP;
00970         }
00971 
00972         // We used to return a struct. Instead of doing smart stuff with all the
00973         // uses of this struct, we will just rebuild it using
00974         // extract/insertvalue chaining and let instcombine clean that up.
00975         //
00976         // Start out building up our return value from undef
00977         Value *RetVal = UndefValue::get(RetTy);
00978         for (unsigned i = 0; i != RetCount; ++i)
00979           if (NewRetIdxs[i] != -1) {
00980             Value *V;
00981             if (RetTypes.size() > 1)
00982               // We are still returning a struct, so extract the value from our
00983               // return value
00984               V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret",
00985                                            InsertPt);
00986             else
00987               // We are now returning a single element, so just insert that
00988               V = New;
00989             // Insert the value at the old position
00990             RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt);
00991           }
00992         // Now, replace all uses of the old call instruction with the return
00993         // struct we built
00994         Call->replaceAllUsesWith(RetVal);
00995         New->takeName(Call);
00996       }
00997     }
00998 
00999     // Finally, remove the old call from the program, reducing the use-count of
01000     // F.
01001     Call->eraseFromParent();
01002   }
01003 
01004   // Since we have now created the new function, splice the body of the old
01005   // function right into the new function, leaving the old rotting hulk of the
01006   // function empty.
01007   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
01008 
01009   // Loop over the argument list, transferring uses of the old arguments over to
01010   // the new arguments, also transferring over the names as well.
01011   i = 0;
01012   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
01013        I2 = NF->arg_begin(); I != E; ++I, ++i)
01014     if (ArgAlive[i]) {
01015       // If this is a live argument, move the name and users over to the new
01016       // version.
01017       I->replaceAllUsesWith(I2);
01018       I2->takeName(I);
01019       ++I2;
01020     } else {
01021       // If this argument is dead, replace any uses of it with null constants
01022       // (these are guaranteed to become unused later on).
01023       if (!I->getType()->isX86_MMXTy())
01024         I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
01025     }
01026 
01027   // If we change the return value of the function we must rewrite any return
01028   // instructions.  Check this now.
01029   if (F->getReturnType() != NF->getReturnType())
01030     for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
01031       if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
01032         Value *RetVal;
01033 
01034         if (NFTy->getReturnType()->isVoidTy()) {
01035           RetVal = nullptr;
01036         } else {
01037           assert (RetTy->isStructTy());
01038           // The original return value was a struct, insert
01039           // extractvalue/insertvalue chains to extract only the values we need
01040           // to return and insert them into our new result.
01041           // This does generate messy code, but we'll let it to instcombine to
01042           // clean that up.
01043           Value *OldRet = RI->getOperand(0);
01044           // Start out building up our return value from undef
01045           RetVal = UndefValue::get(NRetTy);
01046           for (unsigned i = 0; i != RetCount; ++i)
01047             if (NewRetIdxs[i] != -1) {
01048               ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
01049                                                               "oldret", RI);
01050               if (RetTypes.size() > 1) {
01051                 // We're still returning a struct, so reinsert the value into
01052                 // our new return value at the new index
01053 
01054                 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
01055                                                  "newret", RI);
01056               } else {
01057                 // We are now only returning a simple value, so just return the
01058                 // extracted value.
01059                 RetVal = EV;
01060               }
01061             }
01062         }
01063         // Replace the return instruction with one returning the new return
01064         // value (possibly 0 if we became void).
01065         ReturnInst::Create(F->getContext(), RetVal, RI);
01066         BB->getInstList().erase(RI);
01067       }
01068 
01069   // Patch the pointer to LLVM function in debug info descriptor.
01070   auto DI = FunctionDIs.find(F);
01071   if (DI != FunctionDIs.end())
01072     DI->second.replaceFunction(NF);
01073 
01074   // Now that the old function is dead, delete it.
01075   F->eraseFromParent();
01076 
01077   return true;
01078 }
01079 
01080 bool DAE::runOnModule(Module &M) {
01081   bool Changed = false;
01082 
01083   // Collect debug info descriptors for functions.
01084   FunctionDIs = makeSubprogramMap(M);
01085 
01086   // First pass: Do a simple check to see if any functions can have their "..."
01087   // removed.  We can do this if they never call va_start.  This loop cannot be
01088   // fused with the next loop, because deleting a function invalidates
01089   // information computed while surveying other functions.
01090   DEBUG(dbgs() << "DAE - Deleting dead varargs\n");
01091   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
01092     Function &F = *I++;
01093     if (F.getFunctionType()->isVarArg())
01094       Changed |= DeleteDeadVarargs(F);
01095   }
01096 
01097   // Second phase:loop through the module, determining which arguments are live.
01098   // We assume all arguments are dead unless proven otherwise (allowing us to
01099   // determine that dead arguments passed into recursive functions are dead).
01100   //
01101   DEBUG(dbgs() << "DAE - Determining liveness\n");
01102   for (auto &F : M)
01103     SurveyFunction(F);
01104 
01105   // Now, remove all dead arguments and return values from each function in
01106   // turn.
01107   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
01108     // Increment now, because the function will probably get removed (ie.
01109     // replaced by a new one).
01110     Function *F = I++;
01111     Changed |= RemoveDeadStuffFromFunction(F);
01112   }
01113 
01114   // Finally, look for any unused parameters in functions with non-local
01115   // linkage and replace the passed in parameters with undef.
01116   for (auto &F : M)
01117     Changed |= RemoveDeadArgumentsFromCallers(F);
01118 
01119   return Changed;
01120 }