LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

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 #define DEBUG_TYPE "deadargelim"
00021 #include "llvm/Transforms/IPO.h"
00022 #include "llvm/CallingConv.h"
00023 #include "llvm/Constant.h"
00024 #include "llvm/DerivedTypes.h"
00025 #include "llvm/Instructions.h"
00026 #include "llvm/IntrinsicInst.h"
00027 #include "llvm/Module.h"
00028 #include "llvm/Pass.h"
00029 #include "llvm/Support/CallSite.h"
00030 #include "llvm/Support/Debug.h"
00031 #include "llvm/ADT/SmallVector.h"
00032 #include "llvm/ADT/Statistic.h"
00033 #include "llvm/ADT/StringExtras.h"
00034 #include "llvm/Support/Compiler.h"
00035 #include <map>
00036 #include <set>
00037 using namespace llvm;
00038 
00039 STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
00040 STATISTIC(NumRetValsEliminated  , "Number of unused return values removed");
00041 
00042 namespace {
00043   /// DAE - The dead argument elimination pass.
00044   ///
00045   class VISIBILITY_HIDDEN DAE : public ModulePass {
00046   public:
00047 
00048     /// Struct that represents (part of) either a return value or a function
00049     /// argument.  Used so that arguments and return values can be used
00050     /// interchangably.
00051     struct RetOrArg {
00052       RetOrArg(const Function* F, unsigned Idx, bool IsArg) : F(F), Idx(Idx),
00053                IsArg(IsArg) {}
00054       const Function *F;
00055       unsigned Idx;
00056       bool IsArg;
00057 
00058       /// Make RetOrArg comparable, so we can put it into a map.
00059       bool operator<(const RetOrArg &O) const {
00060         if (F != O.F)
00061           return F < O.F;
00062         else if (Idx != O.Idx)
00063           return Idx < O.Idx;
00064         else
00065           return IsArg < O.IsArg;
00066       }
00067 
00068       /// Make RetOrArg comparable, so we can easily iterate the multimap.
00069       bool operator==(const RetOrArg &O) const {
00070         return F == O.F && Idx == O.Idx && IsArg == O.IsArg;
00071       }
00072 
00073       std::string getDescription() const {
00074         return std::string((IsArg ? "Argument #" : "Return value #")) 
00075                + utostr(Idx) + " of function " + F->getName();
00076       }
00077     };
00078 
00079     /// Liveness enum - During our initial pass over the program, we determine
00080     /// that things are either alive or maybe alive. We don't mark anything
00081     /// explicitly dead (even if we know they are), since anything not alive
00082     /// with no registered uses (in Uses) will never be marked alive and will
00083     /// thus become dead in the end.
00084     enum Liveness { Live, MaybeLive };
00085 
00086     /// Convenience wrapper
00087     RetOrArg CreateRet(const Function *F, unsigned Idx) {
00088       return RetOrArg(F, Idx, false);
00089     }
00090     /// Convenience wrapper
00091     RetOrArg CreateArg(const Function *F, unsigned Idx) {
00092       return RetOrArg(F, Idx, true);
00093     }
00094 
00095     typedef std::multimap<RetOrArg, RetOrArg> UseMap;
00096     /// This maps a return value or argument to any MaybeLive return values or
00097     /// arguments it uses. This allows the MaybeLive values to be marked live
00098     /// when any of its users is marked live.
00099     /// For example (indices are left out for clarity):
00100     ///  - Uses[ret F] = ret G
00101     ///    This means that F calls G, and F returns the value returned by G.
00102     ///  - Uses[arg F] = ret G
00103     ///    This means that some function calls G and passes its result as an
00104     ///    argument to F.
00105     ///  - Uses[ret F] = arg F
00106     ///    This means that F returns one of its own arguments.
00107     ///  - Uses[arg F] = arg G
00108     ///    This means that G calls F and passes one of its own (G's) arguments
00109     ///    directly to F.
00110     UseMap Uses;
00111 
00112     typedef std::set<RetOrArg> LiveSet;
00113     typedef std::set<const Function*> LiveFuncSet;
00114 
00115     /// This set contains all values that have been determined to be live.
00116     LiveSet LiveValues;
00117     /// This set contains all values that are cannot be changed in any way.
00118     LiveFuncSet LiveFunctions;
00119 
00120     typedef SmallVector<RetOrArg, 5> UseVector;
00121 
00122   public:
00123     static char ID; // Pass identification, replacement for typeid
00124     DAE() : ModulePass(&ID) {}
00125     bool runOnModule(Module &M);
00126 
00127     virtual bool ShouldHackArguments() const { return false; }
00128 
00129   private:
00130     Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
00131     Liveness SurveyUse(Value::use_iterator U, UseVector &MaybeLiveUses,
00132                        unsigned RetValNum = 0);
00133     Liveness SurveyUses(Value *V, UseVector &MaybeLiveUses);
00134 
00135     void SurveyFunction(Function &F);
00136     void MarkValue(const RetOrArg &RA, Liveness L,
00137                    const UseVector &MaybeLiveUses);
00138     void MarkLive(const RetOrArg &RA);
00139     void MarkLive(const Function &F);
00140     void PropagateLiveness(const RetOrArg &RA);
00141     bool RemoveDeadStuffFromFunction(Function *F);
00142     bool DeleteDeadVarargs(Function &Fn);
00143   };
00144 }
00145 
00146 
00147 char DAE::ID = 0;
00148 static RegisterPass<DAE>
00149 X("deadargelim", "Dead Argument Elimination");
00150 
00151 namespace {
00152   /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
00153   /// deletes arguments to functions which are external.  This is only for use
00154   /// by bugpoint.
00155   struct DAH : public DAE {
00156     static char ID;
00157     virtual bool ShouldHackArguments() const { return true; }
00158   };
00159 }
00160 
00161 char DAH::ID = 0;
00162 static RegisterPass<DAH>
00163 Y("deadarghaX0r", "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)");
00164 
00165 /// createDeadArgEliminationPass - This pass removes arguments from functions
00166 /// which are not used by the body of the function.
00167 ///
00168 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
00169 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
00170 
00171 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if
00172 /// llvm.vastart is never called, the varargs list is dead for the function.
00173 bool DAE::DeleteDeadVarargs(Function &Fn) {
00174   assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
00175   if (Fn.isDeclaration() || !Fn.hasInternalLinkage()) return false;
00176 
00177   // Ensure that the function is only directly called.
00178   for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end(); I != E; ++I) {
00179     // If this use is anything other than a call site, give up.
00180     CallSite CS = CallSite::get(*I);
00181     Instruction *TheCall = CS.getInstruction();
00182     if (!TheCall) return false;   // Not a direct call site?
00183 
00184     // The addr of this function is passed to the call.
00185     if (I.getOperandNo() != 0) return false;
00186   }
00187 
00188   // Okay, we know we can transform this function if safe.  Scan its body
00189   // looking for calls to llvm.vastart.
00190   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
00191     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00192       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00193         if (II->getIntrinsicID() == Intrinsic::vastart)
00194           return false;
00195       }
00196     }
00197   }
00198 
00199   // If we get here, there are no calls to llvm.vastart in the function body,
00200   // remove the "..." and adjust all the calls.
00201 
00202   // Start by computing a new prototype for the function, which is the same as
00203   // the old function, but doesn't have isVarArg set.
00204   const FunctionType *FTy = Fn.getFunctionType();
00205   std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
00206   FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), Params, false);
00207   unsigned NumArgs = Params.size();
00208 
00209   // Create the new function body and insert it into the module...
00210   Function *NF = Function::Create(NFTy, Fn.getLinkage());
00211   NF->copyAttributesFrom(&Fn);
00212   Fn.getParent()->getFunctionList().insert(&Fn, NF);
00213   NF->takeName(&Fn);
00214 
00215   // Loop over all of the callers of the function, transforming the call sites
00216   // to pass in a smaller number of arguments into the new function.
00217   //
00218   std::vector<Value*> Args;
00219   while (!Fn.use_empty()) {
00220     CallSite CS = CallSite::get(Fn.use_back());
00221     Instruction *Call = CS.getInstruction();
00222 
00223     // Pass all the same arguments.
00224     Args.assign(CS.arg_begin(), CS.arg_begin()+NumArgs);
00225 
00226     // Drop any attributes that were on the vararg arguments.
00227     PAListPtr PAL = CS.getParamAttrs();
00228     if (!PAL.isEmpty() && PAL.getSlot(PAL.getNumSlots() - 1).Index > NumArgs) {
00229       SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
00230       for (unsigned i = 0; PAL.getSlot(i).Index <= NumArgs; ++i)
00231         ParamAttrsVec.push_back(PAL.getSlot(i));
00232       PAL = PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end());
00233     }
00234 
00235     Instruction *New;
00236     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
00237       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
00238                                Args.begin(), Args.end(), "", Call);
00239       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
00240       cast<InvokeInst>(New)->setParamAttrs(PAL);
00241     } else {
00242       New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
00243       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
00244       cast<CallInst>(New)->setParamAttrs(PAL);
00245       if (cast<CallInst>(Call)->isTailCall())
00246         cast<CallInst>(New)->setTailCall();
00247     }
00248     Args.clear();
00249 
00250     if (!Call->use_empty())
00251       Call->replaceAllUsesWith(New);
00252 
00253     New->takeName(Call);
00254 
00255     // Finally, remove the old call from the program, reducing the use-count of
00256     // F.
00257     Call->eraseFromParent();
00258   }
00259 
00260   // Since we have now created the new function, splice the body of the old
00261   // function right into the new function, leaving the old rotting hulk of the
00262   // function empty.
00263   NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
00264 
00265   // Loop over the argument list, transfering uses of the old arguments over to
00266   // the new arguments, also transfering over the names as well.  While we're at
00267   // it, remove the dead arguments from the DeadArguments list.
00268   //
00269   for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
00270        I2 = NF->arg_begin(); I != E; ++I, ++I2) {
00271     // Move the name and users over to the new version.
00272     I->replaceAllUsesWith(I2);
00273     I2->takeName(I);
00274   }
00275 
00276   // Finally, nuke the old function.
00277   Fn.eraseFromParent();
00278   return true;
00279 }
00280 
00281 /// Convenience function that returns the number of return values. It returns 0
00282 /// for void functions and 1 for functions not returning a struct. It returns
00283 /// the number of struct elements for functions returning a struct.
00284 static unsigned NumRetVals(const Function *F) {
00285   if (F->getReturnType() == Type::VoidTy)
00286     return 0;
00287   else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType()))
00288     return STy->getNumElements();
00289   else
00290     return 1;
00291 }
00292 
00293 /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
00294 /// live, it adds Use to the MaybeLiveUses argument. Returns the determined
00295 /// liveness of Use.
00296 DAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
00297   // We're live if our use or its Function is already marked as live.
00298   if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
00299     return Live;
00300 
00301   // We're maybe live otherwise, but remember that we must become live if
00302   // Use becomes live.
00303   MaybeLiveUses.push_back(Use);
00304   return MaybeLive;
00305 }
00306 
00307 
00308 /// SurveyUse - This looks at a single use of an argument or return value
00309 /// and determines if it should be alive or not. Adds this use to MaybeLiveUses
00310 /// if it causes the used value to become MaybeAlive.
00311 ///
00312 /// RetValNum is the return value number to use when this use is used in a
00313 /// return instruction. This is used in the recursion, you should always leave
00314 /// it at 0.
00315 DAE::Liveness DAE::SurveyUse(Value::use_iterator U, UseVector &MaybeLiveUses,
00316                              unsigned RetValNum) {
00317     Value *V = *U;
00318     if (ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
00319       // The value is returned from a function. It's only live when the
00320       // function's return value is live. We use RetValNum here, for the case
00321       // that U is really a use of an insertvalue instruction that uses the
00322       // orginal Use.
00323       RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
00324       // We might be live, depending on the liveness of Use.
00325       return MarkIfNotLive(Use, MaybeLiveUses);
00326     }
00327     if (InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
00328       if (U.getOperandNo() != InsertValueInst::getAggregateOperandIndex()
00329           && IV->hasIndices())
00330         // The use we are examining is inserted into an aggregate. Our liveness
00331         // depends on all uses of that aggregate, but if it is used as a return
00332         // value, only index at which we were inserted counts.
00333         RetValNum = *IV->idx_begin();
00334 
00335       // Note that if we are used as the aggregate operand to the insertvalue,
00336       // we don't change RetValNum, but do survey all our uses.
00337 
00338       Liveness Result = MaybeLive;
00339       for (Value::use_iterator I = IV->use_begin(),
00340            E = V->use_end(); I != E; ++I) {
00341         Result = SurveyUse(I, MaybeLiveUses, RetValNum);
00342         if (Result == Live)
00343           break;
00344       }
00345       return Result;
00346     }
00347     CallSite CS = CallSite::get(V);
00348     if (CS.getInstruction()) {
00349       Function *F = CS.getCalledFunction();
00350       if (F) {
00351         // Used in a direct call.
00352   
00353         // Find the argument number. We know for sure that this use is an
00354         // argument, since if it was the function argument this would be an
00355         // indirect call and the we know can't be looking at a value of the
00356         // label type (for the invoke instruction).
00357         unsigned ArgNo = CS.getArgumentNo(U.getOperandNo());
00358 
00359         if (ArgNo >= F->getFunctionType()->getNumParams())
00360           // The value is passed in through a vararg! Must be live.
00361           return Live;
00362 
00363         assert(CS.getArgument(ArgNo) 
00364                == CS.getInstruction()->getOperand(U.getOperandNo()) 
00365                && "Argument is not where we expected it");
00366 
00367         // Value passed to a normal call. It's only live when the corresponding
00368         // argument to the called function turns out live.
00369         RetOrArg Use = CreateArg(F, ArgNo);
00370         return MarkIfNotLive(Use, MaybeLiveUses);
00371       }
00372     }
00373     // Used in any other way? Value must be live.
00374     return Live;
00375 }
00376 
00377 /// SurveyUses - This looks at all the uses of the given value
00378 /// Returns the Liveness deduced from the uses of this value.
00379 ///
00380 /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
00381 /// the result is Live, MaybeLiveUses might be modified but its content should
00382 /// be ignored (since it might not be complete).
00383 DAE::Liveness DAE::SurveyUses(Value *V, UseVector &MaybeLiveUses) {
00384   // Assume it's dead (which will only hold if there are no uses at all..).
00385   Liveness Result = MaybeLive;
00386   // Check each use.
00387   for (Value::use_iterator I = V->use_begin(),
00388        E = V->use_end(); I != E; ++I) {
00389     Result = SurveyUse(I, MaybeLiveUses);
00390     if (Result == Live)
00391       break;
00392   }
00393   return Result;
00394 }
00395 
00396 // SurveyFunction - This performs the initial survey of the specified function,
00397 // checking out whether or not it uses any of its incoming arguments or whether
00398 // any callers use the return value.  This fills in the LiveValues set and Uses
00399 // map.
00400 //
00401 // We consider arguments of non-internal functions to be intrinsically alive as
00402 // well as arguments to functions which have their "address taken".
00403 //
00404 void DAE::SurveyFunction(Function &F) {
00405   unsigned RetCount = NumRetVals(&F);
00406   // Assume all return values are dead
00407   typedef SmallVector<Liveness, 5> RetVals;
00408   RetVals RetValLiveness(RetCount, MaybeLive);
00409 
00410   typedef SmallVector<UseVector, 5> RetUses;
00411   // These vectors map each return value to the uses that make it MaybeLive, so
00412   // we can add those to the Uses map if the return value really turns out to be
00413   // MaybeLive. Initialized to a list of RetCount empty lists.
00414   RetUses MaybeLiveRetUses(RetCount);
00415 
00416   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00417     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
00418       if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
00419           != F.getFunctionType()->getReturnType()) {
00420         // We don't support old style multiple return values.
00421         MarkLive(F);
00422         return;
00423       }
00424 
00425   if (!F.hasInternalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
00426     MarkLive(F);
00427     return;
00428   }
00429 
00430   DOUT << "DAE - Inspecting callers for fn: " << F.getName() << "\n";
00431   // Keep track of the number of live retvals, so we can skip checks once all
00432   // of them turn out to be live.
00433   unsigned NumLiveRetVals = 0;
00434   const Type *STy = dyn_cast<StructType>(F.getReturnType());
00435   // Loop all uses of the function.
00436   for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
00437     // If the function is PASSED IN as an argument, its address has been
00438     // taken.
00439     if (I.getOperandNo() != 0) {
00440       MarkLive(F);
00441       return;
00442     }
00443 
00444     // If this use is anything other than a call site, the function is alive.
00445     CallSite CS = CallSite::get(*I);
00446     Instruction *TheCall = CS.getInstruction();
00447     if (!TheCall) {   // Not a direct call site?
00448       MarkLive(F);
00449       return;
00450     }
00451 
00452     // If we end up here, we are looking at a direct call to our function.
00453 
00454     // Now, check how our return value(s) is/are used in this caller. Don't
00455     // bother checking return values if all of them are live already.
00456     if (NumLiveRetVals != RetCount) {
00457       if (STy) {
00458         // Check all uses of the return value.
00459         for (Value::use_iterator I = TheCall->use_begin(),
00460              E = TheCall->use_end(); I != E; ++I) {
00461           ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(*I);
00462           if (Ext && Ext->hasIndices()) {
00463             // This use uses a part of our return value, survey the uses of
00464             // that part and store the results for this index only.
00465             unsigned Idx = *Ext->idx_begin();
00466             if (RetValLiveness[Idx] != Live) {
00467               RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
00468               if (RetValLiveness[Idx] == Live)
00469                 NumLiveRetVals++;
00470             }
00471           } else {
00472             // Used by something else than extractvalue. Mark all return
00473             // values as live.
00474             for (unsigned i = 0; i != RetCount; ++i )
00475               RetValLiveness[i] = Live;
00476             NumLiveRetVals = RetCount;
00477             break;
00478           }
00479         }
00480       } else {
00481         // Single return value
00482         RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]);
00483         if (RetValLiveness[0] == Live)
00484           NumLiveRetVals = RetCount;
00485       }
00486     }
00487   }
00488 
00489   // Now we've inspected all callers, record the liveness of our return values.
00490   for (unsigned i = 0; i != RetCount; ++i)
00491     MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
00492 
00493   DOUT << "DAE - Inspecting args for fn: " << F.getName() << "\n";
00494 
00495   // Now, check all of our arguments.
00496   unsigned i = 0;
00497   UseVector MaybeLiveArgUses;
00498   for (Function::arg_iterator AI = F.arg_begin(),
00499        E = F.arg_end(); AI != E; ++AI, ++i) {
00500     // See what the effect of this use is (recording any uses that cause
00501     // MaybeLive in MaybeLiveArgUses).
00502     Liveness Result = SurveyUses(AI, MaybeLiveArgUses);
00503     // Mark the result.
00504     MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
00505     // Clear the vector again for the next iteration.
00506     MaybeLiveArgUses.clear();
00507   }
00508 }
00509 
00510 /// MarkValue - This function marks the liveness of RA depending on L. If L is
00511 /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
00512 /// such that RA will be marked live if any use in MaybeLiveUses gets marked
00513 /// live later on.
00514 void DAE::MarkValue(const RetOrArg &RA, Liveness L,
00515                     const UseVector &MaybeLiveUses) {
00516   switch (L) {
00517     case Live: MarkLive(RA); break;
00518     case MaybeLive:
00519     {
00520       // Note any uses of this value, so this return value can be
00521       // marked live whenever one of the uses becomes live.
00522       for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
00523            UE = MaybeLiveUses.end(); UI != UE; ++UI)
00524         Uses.insert(std::make_pair(*UI, RA));
00525       break;
00526     }
00527   }
00528 }
00529 
00530 /// MarkLive - Mark the given Function as alive, meaning that it cannot be
00531 /// changed in any way. Additionally,
00532 /// mark any values that are used as this function's parameters or by its return
00533 /// values (according to Uses) live as well.
00534 void DAE::MarkLive(const Function &F) {
00535     DOUT << "DAE - Intrinsically live fn: " << F.getName() << "\n";
00536     // Mark the function as live.
00537     LiveFunctions.insert(&F);
00538     // Mark all arguments as live.
00539     for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
00540       PropagateLiveness(CreateArg(&F, i));
00541     // Mark all return values as live.
00542     for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
00543       PropagateLiveness(CreateRet(&F, i));
00544 }
00545 
00546 /// MarkLive - Mark the given return value or argument as live. Additionally,
00547 /// mark any values that are used by this value (according to Uses) live as
00548 /// well.
00549 void DAE::MarkLive(const RetOrArg &RA) {
00550   if (LiveFunctions.count(RA.F))
00551     return; // Function was already marked Live.
00552 
00553   if (!LiveValues.insert(RA).second)
00554     return; // We were already marked Live.
00555 
00556   DOUT << "DAE - Marking " << RA.getDescription() << " live\n";
00557   PropagateLiveness(RA);
00558 }
00559 
00560 /// PropagateLiveness - Given that RA is a live value, propagate it's liveness
00561 /// to any other values it uses (according to Uses).
00562 void DAE::PropagateLiveness(const RetOrArg &RA) {
00563   // We don't use upper_bound (or equal_range) here, because our recursive call
00564   // to ourselves is likely to cause the upper_bound (which is the first value
00565   // not belonging to RA) to become erased and the iterator invalidated.
00566   UseMap::iterator Begin = Uses.lower_bound(RA);
00567   UseMap::iterator E = Uses.end();
00568   UseMap::iterator I;
00569   for (I = Begin; I != E && I->first == RA; ++I)
00570     MarkLive(I->second);
00571 
00572   // Erase RA from the Uses map (from the lower bound to wherever we ended up
00573   // after the loop).
00574   Uses.erase(Begin, I);
00575 }
00576 
00577 // RemoveDeadStuffFromFunction - Remove any arguments and return values from F
00578 // that are not in LiveValues. Transform the function and all of the callees of
00579 // the function to not have these arguments and return values.
00580 //
00581 bool DAE::RemoveDeadStuffFromFunction(Function *F) {
00582   // Don't modify fully live functions
00583   if (LiveFunctions.count(F))
00584     return false;
00585 
00586   // Start by computing a new prototype for the function, which is the same as
00587   // the old function, but has fewer arguments and a different return type.
00588   const FunctionType *FTy = F->getFunctionType();
00589   std::vector<const Type*> Params;
00590 
00591   // Set up to build a new list of parameter attributes.
00592   SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
00593   const PAListPtr &PAL = F->getParamAttrs();
00594 
00595   // The existing function return attributes.
00596   ParameterAttributes RAttrs = PAL.getParamAttrs(0);
00597 
00598 
00599   // Find out the new return value.
00600 
00601   const Type *RetTy = FTy->getReturnType();
00602   const Type *NRetTy = NULL;
00603   unsigned RetCount = NumRetVals(F);
00604   // -1 means unused, other numbers are the new index
00605   SmallVector<int, 5> NewRetIdxs(RetCount, -1);
00606   std::vector<const Type*> RetTypes;
00607   if (RetTy == Type::VoidTy) {
00608     NRetTy = Type::VoidTy;
00609   } else {
00610     const StructType *STy = dyn_cast<StructType>(RetTy);
00611     if (STy)
00612       // Look at each of the original return values individually.
00613       for (unsigned i = 0; i != RetCount; ++i) {
00614         RetOrArg Ret = CreateRet(F, i);
00615         if (LiveValues.erase(Ret)) {
00616           RetTypes.push_back(STy->getElementType(i));
00617           NewRetIdxs[i] = RetTypes.size() - 1;
00618         } else {
00619           ++NumRetValsEliminated;
00620           DOUT << "DAE - Removing return value " << i << " from "
00621                << F->getNameStart() << "\n";
00622         }
00623       }
00624     else
00625       // We used to return a single value.
00626       if (LiveValues.erase(CreateRet(F, 0))) {
00627         RetTypes.push_back(RetTy);
00628         NewRetIdxs[0] = 0;
00629       } else {
00630         DOUT << "DAE - Removing return value from " << F->getNameStart()
00631              << "\n";
00632         ++NumRetValsEliminated;
00633       }
00634     if (RetTypes.size() > 1)
00635       // More than one return type? Return a struct with them. Also, if we used
00636       // to return a struct and didn't change the number of return values,
00637       // return a struct again. This prevents changing {something} into
00638       // something and {} into void.
00639       // Make the new struct packed if we used to return a packed struct
00640       // already.
00641       NRetTy = StructType::get(RetTypes, STy->isPacked());
00642     else if (RetTypes.size() == 1)
00643       // One return type? Just a simple value then, but only if we didn't use to
00644       // return a struct with that simple value before.
00645       NRetTy = RetTypes.front();
00646     else if (RetTypes.size() == 0)
00647       // No return types? Make it void, but only if we didn't use to return {}.
00648       NRetTy = Type::VoidTy;
00649   }
00650 
00651   assert(NRetTy && "No new return type found?");
00652 
00653   // Remove any incompatible attributes, but only if we removed all return
00654   // values. Otherwise, ensure that we don't have any conflicting attributes
00655   // here. Currently, this should not be possible, but special handling might be
00656   // required when new return value attributes are added.
00657   if (NRetTy == Type::VoidTy)
00658     RAttrs &= ~ParamAttr::typeIncompatible(NRetTy);
00659   else
00660     assert((RAttrs & ParamAttr::typeIncompatible(NRetTy)) == 0 
00661            && "Return attributes no longer compatible?");
00662 
00663   if (RAttrs)
00664     ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
00665 
00666   // Remember which arguments are still alive.
00667   SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
00668   // Construct the new parameter list from non-dead arguments. Also construct
00669   // a new set of parameter attributes to correspond. Skip the first parameter
00670   // attribute, since that belongs to the return value.
00671   unsigned i = 0;
00672   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
00673        I != E; ++I, ++i) {
00674     RetOrArg Arg = CreateArg(F, i);
00675     if (LiveValues.erase(Arg)) {
00676       Params.push_back(I->getType());
00677       ArgAlive[i] = true;
00678 
00679       // Get the original parameter attributes (skipping the first one, that is
00680       // for the return value.
00681       if (ParameterAttributes Attrs = PAL.getParamAttrs(i + 1))
00682         ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), Attrs));
00683     } else {
00684       ++NumArgumentsEliminated;
00685       DOUT << "DAE - Removing argument " << i << " (" << I->getNameStart()
00686            << ") from " << F->getNameStart() << "\n";
00687     }
00688   }
00689 
00690   // Reconstruct the ParamAttrsList based on the vector we constructed.
00691   PAListPtr NewPAL = PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end());
00692 
00693   // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
00694   // have zero fixed arguments.
00695   //
00696   // Note that we apply this hack for a vararg fuction that does not have any
00697   // arguments anymore, but did have them before (so don't bother fixing
00698   // functions that were already broken wrt CWriter).
00699   bool ExtraArgHack = false;
00700   if (Params.empty() && FTy->isVarArg() && FTy->getNumParams() != 0) {
00701     ExtraArgHack = true;
00702     Params.push_back(Type::Int32Ty);
00703   }
00704 
00705   // Create the new function type based on the recomputed parameters.
00706   FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
00707 
00708   // No change?
00709   if (NFTy == FTy)
00710     return false;
00711 
00712   // Create the new function body and insert it into the module...
00713   Function *NF = Function::Create(NFTy, F->getLinkage());
00714   NF->copyAttributesFrom(F);
00715   NF->setParamAttrs(NewPAL);
00716   // Insert the new function before the old function, so we won't be processing
00717   // it again.
00718   F->getParent()->getFunctionList().insert(F, NF);
00719   NF->takeName(F);
00720 
00721   // Loop over all of the callers of the function, transforming the call sites
00722   // to pass in a smaller number of arguments into the new function.
00723   //
00724   std::vector<Value*> Args;
00725   while (!F->use_empty()) {
00726     CallSite CS = CallSite::get(F->use_back());
00727     Instruction *Call = CS.getInstruction();
00728 
00729     ParamAttrsVec.clear();
00730     const PAListPtr &CallPAL = CS.getParamAttrs();
00731 
00732     // The call return attributes.
00733     ParameterAttributes RAttrs = CallPAL.getParamAttrs(0);
00734     // Adjust in case the function was changed to return void.
00735     RAttrs &= ~ParamAttr::typeIncompatible(NF->getReturnType());
00736     if (RAttrs)
00737       ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
00738 
00739     // Declare these outside of the loops, so we can reuse them for the second
00740     // loop, which loops the varargs.
00741     CallSite::arg_iterator I = CS.arg_begin();
00742     unsigned i = 0;
00743     // Loop over those operands, corresponding to the normal arguments to the
00744     // original function, and add those that are still alive.
00745     for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
00746       if (ArgAlive[i]) {
00747         Args.push_back(*I);
00748         // Get original parameter attributes, but skip return attributes.
00749         if (ParameterAttributes Attrs = CallPAL.getParamAttrs(i + 1))
00750           ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
00751       }
00752 
00753     if (ExtraArgHack)
00754       Args.push_back(UndefValue::get(Type::Int32Ty));
00755 
00756     // Push any varargs arguments on the list. Don't forget their attributes.
00757     for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
00758       Args.push_back(*I);
00759       if (ParameterAttributes Attrs = CallPAL.getParamAttrs(i + 1))
00760         ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
00761     }
00762 
00763     // Reconstruct the ParamAttrsList based on the vector we constructed.
00764     PAListPtr NewCallPAL = PAListPtr::get(ParamAttrsVec.begin(),
00765                                           ParamAttrsVec.end());
00766 
00767     Instruction *New;
00768     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
00769       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
00770                                Args.begin(), Args.end(), "", Call);
00771       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
00772       cast<InvokeInst>(New)->setParamAttrs(NewCallPAL);
00773     } else {
00774       New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
00775       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
00776       cast<CallInst>(New)->setParamAttrs(NewCallPAL);
00777       if (cast<CallInst>(Call)->isTailCall())
00778         cast<CallInst>(New)->setTailCall();
00779     }
00780     Args.clear();
00781 
00782     if (!Call->use_empty()) {
00783       if (New->getType() == Call->getType()) {
00784         // Return type not changed? Just replace users then.
00785         Call->replaceAllUsesWith(New);
00786         New->takeName(Call);
00787       } else if (New->getType() == Type::VoidTy) {
00788         // Our return value has uses, but they will get removed later on.
00789         // Replace by null for now.
00790         Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
00791       } else {
00792         assert(isa<StructType>(RetTy) && "Return type changed, but not into a"
00793                                          "void. The old return type must have"
00794                                          "been a struct!");
00795         // We used to return a struct. Instead of doing smart stuff with all the
00796         // uses of this struct, we will just rebuild it using
00797         // extract/insertvalue chaining and let instcombine clean that up.
00798         //
00799         // Start out building up our return value from undef
00800         Value *RetVal = llvm::UndefValue::get(RetTy);
00801         for (unsigned i = 0; i != RetCount; ++i)
00802           if (NewRetIdxs[i] != -1) {
00803             Value *V;
00804             if (RetTypes.size() > 1)
00805               // We are still returning a struct, so extract the value from our
00806               // return value
00807               V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret", Call);
00808             else
00809               // We are now returning a single element, so just insert that
00810               V = New;
00811             // Insert the value at the old position
00812             RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", Call);
00813           }
00814         // Now, replace all uses of the old call instruction with the return
00815         // struct we built
00816         Call->replaceAllUsesWith(RetVal);
00817         New->takeName(Call);
00818       }
00819     }
00820 
00821     // Finally, remove the old call from the program, reducing the use-count of
00822     // F.
00823     Call->eraseFromParent();
00824   }
00825 
00826   // Since we have now created the new function, splice the body of the old
00827   // function right into the new function, leaving the old rotting hulk of the
00828   // function empty.
00829   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
00830 
00831   // Loop over the argument list, transfering uses of the old arguments over to
00832   // the new arguments, also transfering over the names as well.
00833   i = 0;
00834   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
00835        I2 = NF->arg_begin(); I != E; ++I, ++i)
00836     if (ArgAlive[i]) {
00837       // If this is a live argument, move the name and users over to the new
00838       // version.
00839       I->replaceAllUsesWith(I2);
00840       I2->takeName(I);
00841       ++I2;
00842     } else {
00843       // If this argument is dead, replace any uses of it with null constants
00844       // (these are guaranteed to become unused later on).
00845       I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
00846     }
00847 
00848   // If we change the return value of the function we must rewrite any return
00849   // instructions.  Check this now.
00850   if (F->getReturnType() != NF->getReturnType())
00851     for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
00852       if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
00853         Value *RetVal;
00854 
00855         if (NFTy->getReturnType() == Type::VoidTy) {
00856           RetVal = 0;
00857         } else {
00858           assert (isa<StructType>(RetTy));
00859           // The original return value was a struct, insert
00860           // extractvalue/insertvalue chains to extract only the values we need
00861           // to return and insert them into our new result.
00862           // This does generate messy code, but we'll let it to instcombine to
00863           // clean that up.
00864           Value *OldRet = RI->getOperand(0);
00865           // Start out building up our return value from undef
00866           RetVal = llvm::UndefValue::get(NRetTy);
00867           for (unsigned i = 0; i != RetCount; ++i)
00868             if (NewRetIdxs[i] != -1) {
00869               ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
00870                                                               "oldret", RI);
00871               if (RetTypes.size() > 1) {
00872                 // We're still returning a struct, so reinsert the value into
00873                 // our new return value at the new index
00874 
00875                 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
00876                                                  "newret", RI);
00877               } else {
00878                 // We are now only returning a simple value, so just return the
00879                 // extracted value.
00880                 RetVal = EV;
00881               }
00882             }
00883         }
00884         // Replace the return instruction with one returning the new return
00885         // value (possibly 0 if we became void).
00886         ReturnInst::Create(RetVal, RI);
00887         BB->getInstList().erase(RI);
00888       }
00889 
00890   // Now that the old function is dead, delete it.
00891   F->eraseFromParent();
00892 
00893   return true;
00894 }
00895 
00896 bool DAE::runOnModule(Module &M) {
00897   bool Changed = false;
00898 
00899   // First pass: Do a simple check to see if any functions can have their "..."
00900   // removed.  We can do this if they never call va_start.  This loop cannot be
00901   // fused with the next loop, because deleting a function invalidates
00902   // information computed while surveying other functions.
00903   DOUT << "DAE - Deleting dead varargs\n";
00904   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
00905     Function &F = *I++;
00906     if (F.getFunctionType()->isVarArg())
00907       Changed |= DeleteDeadVarargs(F);
00908   }
00909 
00910   // Second phase:loop through the module, determining which arguments are live.
00911   // We assume all arguments are dead unless proven otherwise (allowing us to
00912   // determine that dead arguments passed into recursive functions are dead).
00913   //
00914   DOUT << "DAE - Determining liveness\n";
00915   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
00916     SurveyFunction(*I);
00917   
00918   // Now, remove all dead arguments and return values from each function in
00919   // turn
00920   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
00921     // Increment now, because the function will probably get removed (ie
00922     // replaced by a new one).
00923     Function *F = I++;
00924     Changed |= RemoveDeadStuffFromFunction(F);
00925   }
00926   return Changed;
00927 }



This web site is hosted by the Computer Science Department at the University of Illinois at Urbana-Champaign.