DeadArgumentElimination.cpp revision 249423
1193323Sed//===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===// 2193323Sed// 3193323Sed// The LLVM Compiler Infrastructure 4193323Sed// 5193323Sed// This file is distributed under the University of Illinois Open Source 6193323Sed// License. See LICENSE.TXT for details. 7193323Sed// 8193323Sed//===----------------------------------------------------------------------===// 9193323Sed// 10193323Sed// This pass deletes dead arguments from internal functions. Dead argument 11193323Sed// elimination removes arguments which are directly dead, as well as arguments 12193323Sed// only passed into function calls as dead arguments of other functions. This 13193323Sed// pass also deletes dead return values in a similar way. 14193323Sed// 15193323Sed// This pass is often useful as a cleanup pass to run after aggressive 16193323Sed// interprocedural passes, which add possibly-dead arguments or return values. 17193323Sed// 18193323Sed//===----------------------------------------------------------------------===// 19193323Sed 20193323Sed#define DEBUG_TYPE "deadargelim" 21193323Sed#include "llvm/Transforms/IPO.h" 22249423Sdim#include "llvm/ADT/DenseMap.h" 23249423Sdim#include "llvm/ADT/SmallVector.h" 24249423Sdim#include "llvm/ADT/Statistic.h" 25249423Sdim#include "llvm/ADT/StringExtras.h" 26249423Sdim#include "llvm/DIBuilder.h" 27243830Sdim#include "llvm/DebugInfo.h" 28249423Sdim#include "llvm/IR/CallingConv.h" 29249423Sdim#include "llvm/IR/Constant.h" 30249423Sdim#include "llvm/IR/DerivedTypes.h" 31249423Sdim#include "llvm/IR/Instructions.h" 32249423Sdim#include "llvm/IR/IntrinsicInst.h" 33249423Sdim#include "llvm/IR/LLVMContext.h" 34249423Sdim#include "llvm/IR/Module.h" 35193323Sed#include "llvm/Pass.h" 36193323Sed#include "llvm/Support/CallSite.h" 37193323Sed#include "llvm/Support/Debug.h" 38198090Srdivacky#include "llvm/Support/raw_ostream.h" 39193323Sed#include <map> 40193323Sed#include <set> 41193323Sedusing namespace llvm; 42193323Sed 43193323SedSTATISTIC(NumArgumentsEliminated, "Number of unread args removed"); 44193323SedSTATISTIC(NumRetValsEliminated , "Number of unused return values removed"); 45218893SdimSTATISTIC(NumArgumentsReplacedWithUndef, 46218893Sdim "Number of unread args replaced with undef"); 47193323Sednamespace { 48193323Sed /// DAE - The dead argument elimination pass. 49193323Sed /// 50198892Srdivacky class DAE : public ModulePass { 51193323Sed public: 52193323Sed 53193323Sed /// Struct that represents (part of) either a return value or a function 54193323Sed /// argument. Used so that arguments and return values can be used 55221345Sdim /// interchangeably. 56193323Sed struct RetOrArg { 57206083Srdivacky RetOrArg(const Function *F, unsigned Idx, bool IsArg) : F(F), Idx(Idx), 58193323Sed IsArg(IsArg) {} 59193323Sed const Function *F; 60193323Sed unsigned Idx; 61193323Sed bool IsArg; 62193323Sed 63193323Sed /// Make RetOrArg comparable, so we can put it into a map. 64193323Sed bool operator<(const RetOrArg &O) const { 65193323Sed if (F != O.F) 66193323Sed return F < O.F; 67193323Sed else if (Idx != O.Idx) 68193323Sed return Idx < O.Idx; 69193323Sed else 70193323Sed return IsArg < O.IsArg; 71193323Sed } 72193323Sed 73193323Sed /// Make RetOrArg comparable, so we can easily iterate the multimap. 74193323Sed bool operator==(const RetOrArg &O) const { 75193323Sed return F == O.F && Idx == O.Idx && IsArg == O.IsArg; 76193323Sed } 77193323Sed 78193323Sed std::string getDescription() const { 79206083Srdivacky return std::string((IsArg ? "Argument #" : "Return value #")) 80234353Sdim + utostr(Idx) + " of function " + F->getName().str(); 81193323Sed } 82193323Sed }; 83193323Sed 84193323Sed /// Liveness enum - During our initial pass over the program, we determine 85193323Sed /// that things are either alive or maybe alive. We don't mark anything 86193323Sed /// explicitly dead (even if we know they are), since anything not alive 87193323Sed /// with no registered uses (in Uses) will never be marked alive and will 88193323Sed /// thus become dead in the end. 89193323Sed enum Liveness { Live, MaybeLive }; 90193323Sed 91193323Sed /// Convenience wrapper 92193323Sed RetOrArg CreateRet(const Function *F, unsigned Idx) { 93193323Sed return RetOrArg(F, Idx, false); 94193323Sed } 95193323Sed /// Convenience wrapper 96193323Sed RetOrArg CreateArg(const Function *F, unsigned Idx) { 97193323Sed return RetOrArg(F, Idx, true); 98193323Sed } 99193323Sed 100193323Sed typedef std::multimap<RetOrArg, RetOrArg> UseMap; 101193323Sed /// This maps a return value or argument to any MaybeLive return values or 102193323Sed /// arguments it uses. This allows the MaybeLive values to be marked live 103193323Sed /// when any of its users is marked live. 104193323Sed /// For example (indices are left out for clarity): 105193323Sed /// - Uses[ret F] = ret G 106193323Sed /// This means that F calls G, and F returns the value returned by G. 107193323Sed /// - Uses[arg F] = ret G 108193323Sed /// This means that some function calls G and passes its result as an 109193323Sed /// argument to F. 110193323Sed /// - Uses[ret F] = arg F 111193323Sed /// This means that F returns one of its own arguments. 112193323Sed /// - Uses[arg F] = arg G 113193323Sed /// This means that G calls F and passes one of its own (G's) arguments 114193323Sed /// directly to F. 115193323Sed UseMap Uses; 116193323Sed 117193323Sed typedef std::set<RetOrArg> LiveSet; 118193323Sed typedef std::set<const Function*> LiveFuncSet; 119193323Sed 120193323Sed /// This set contains all values that have been determined to be live. 121193323Sed LiveSet LiveValues; 122193323Sed /// This set contains all values that are cannot be changed in any way. 123193323Sed LiveFuncSet LiveFunctions; 124193323Sed 125193323Sed typedef SmallVector<RetOrArg, 5> UseVector; 126193323Sed 127243830Sdim // Map each LLVM function to corresponding metadata with debug info. If 128243830Sdim // the function is replaced with another one, we should patch the pointer 129243830Sdim // to LLVM function in metadata. 130243830Sdim // As the code generation for module is finished (and DIBuilder is 131243830Sdim // finalized) we assume that subprogram descriptors won't be changed, and 132243830Sdim // they are stored in map for short duration anyway. 133243830Sdim typedef DenseMap<Function*, DISubprogram> FunctionDIMap; 134243830Sdim FunctionDIMap FunctionDIs; 135243830Sdim 136210299Sed protected: 137210299Sed // DAH uses this to specify a different ID. 138212904Sdim explicit DAE(char &ID) : ModulePass(ID) {} 139210299Sed 140193323Sed public: 141193323Sed static char ID; // Pass identification, replacement for typeid 142218893Sdim DAE() : ModulePass(ID) { 143218893Sdim initializeDAEPass(*PassRegistry::getPassRegistry()); 144218893Sdim } 145210299Sed 146193323Sed bool runOnModule(Module &M); 147193323Sed 148193323Sed virtual bool ShouldHackArguments() const { return false; } 149193323Sed 150193323Sed private: 151193323Sed Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses); 152206083Srdivacky Liveness SurveyUse(Value::const_use_iterator U, UseVector &MaybeLiveUses, 153193323Sed unsigned RetValNum = 0); 154206083Srdivacky Liveness SurveyUses(const Value *V, UseVector &MaybeLiveUses); 155193323Sed 156243830Sdim void CollectFunctionDIs(Module &M); 157206083Srdivacky void SurveyFunction(const Function &F); 158193323Sed void MarkValue(const RetOrArg &RA, Liveness L, 159193323Sed const UseVector &MaybeLiveUses); 160193323Sed void MarkLive(const RetOrArg &RA); 161193323Sed void MarkLive(const Function &F); 162193323Sed void PropagateLiveness(const RetOrArg &RA); 163193323Sed bool RemoveDeadStuffFromFunction(Function *F); 164193323Sed bool DeleteDeadVarargs(Function &Fn); 165218893Sdim bool RemoveDeadArgumentsFromCallers(Function &Fn); 166193323Sed }; 167193323Sed} 168193323Sed 169193323Sed 170193323Sedchar DAE::ID = 0; 171218893SdimINITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false) 172193323Sed 173193323Sednamespace { 174193323Sed /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but 175193323Sed /// deletes arguments to functions which are external. This is only for use 176193323Sed /// by bugpoint. 177193323Sed struct DAH : public DAE { 178193323Sed static char ID; 179212904Sdim DAH() : DAE(ID) {} 180210299Sed 181193323Sed virtual bool ShouldHackArguments() const { return true; } 182193323Sed }; 183193323Sed} 184193323Sed 185193323Sedchar DAH::ID = 0; 186212904SdimINITIALIZE_PASS(DAH, "deadarghaX0r", 187212904Sdim "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)", 188218893Sdim false, false) 189193323Sed 190193323Sed/// createDeadArgEliminationPass - This pass removes arguments from functions 191193323Sed/// which are not used by the body of the function. 192193323Sed/// 193193323SedModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); } 194193323SedModulePass *llvm::createDeadArgHackingPass() { return new DAH(); } 195193323Sed 196243830Sdim/// CollectFunctionDIs - Map each function in the module to its debug info 197243830Sdim/// descriptor. 198243830Sdimvoid DAE::CollectFunctionDIs(Module &M) { 199243830Sdim FunctionDIs.clear(); 200243830Sdim 201243830Sdim for (Module::named_metadata_iterator I = M.named_metadata_begin(), 202243830Sdim E = M.named_metadata_end(); I != E; ++I) { 203243830Sdim NamedMDNode &NMD = *I; 204243830Sdim for (unsigned MDIndex = 0, MDNum = NMD.getNumOperands(); 205243830Sdim MDIndex < MDNum; ++MDIndex) { 206243830Sdim MDNode *Node = NMD.getOperand(MDIndex); 207243830Sdim if (!DIDescriptor(Node).isCompileUnit()) 208243830Sdim continue; 209243830Sdim DICompileUnit CU(Node); 210243830Sdim const DIArray &SPs = CU.getSubprograms(); 211243830Sdim for (unsigned SPIndex = 0, SPNum = SPs.getNumElements(); 212243830Sdim SPIndex < SPNum; ++SPIndex) { 213243830Sdim DISubprogram SP(SPs.getElement(SPIndex)); 214243830Sdim if (!SP.Verify()) 215243830Sdim continue; 216243830Sdim if (Function *F = SP.getFunction()) 217243830Sdim FunctionDIs[F] = SP; 218243830Sdim } 219243830Sdim } 220243830Sdim } 221243830Sdim} 222243830Sdim 223193323Sed/// DeleteDeadVarargs - If this is an function that takes a ... list, and if 224193323Sed/// llvm.vastart is never called, the varargs list is dead for the function. 225193323Sedbool DAE::DeleteDeadVarargs(Function &Fn) { 226193323Sed assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!"); 227193323Sed if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false; 228193323Sed 229193323Sed // Ensure that the function is only directly called. 230194178Sed if (Fn.hasAddressTaken()) 231194178Sed return false; 232193323Sed 233193323Sed // Okay, we know we can transform this function if safe. Scan its body 234193323Sed // looking for calls to llvm.vastart. 235193323Sed for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) { 236193323Sed for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 237193323Sed if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 238193323Sed if (II->getIntrinsicID() == Intrinsic::vastart) 239193323Sed return false; 240193323Sed } 241193323Sed } 242193323Sed } 243193323Sed 244193323Sed // If we get here, there are no calls to llvm.vastart in the function body, 245193323Sed // remove the "..." and adjust all the calls. 246193323Sed 247193323Sed // Start by computing a new prototype for the function, which is the same as 248193323Sed // the old function, but doesn't have isVarArg set. 249226633Sdim FunctionType *FTy = Fn.getFunctionType(); 250206083Srdivacky 251224145Sdim std::vector<Type*> Params(FTy->param_begin(), FTy->param_end()); 252198090Srdivacky FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), 253198090Srdivacky Params, false); 254193323Sed unsigned NumArgs = Params.size(); 255193323Sed 256193323Sed // Create the new function body and insert it into the module... 257193323Sed Function *NF = Function::Create(NFTy, Fn.getLinkage()); 258193323Sed NF->copyAttributesFrom(&Fn); 259193323Sed Fn.getParent()->getFunctionList().insert(&Fn, NF); 260193323Sed NF->takeName(&Fn); 261193323Sed 262193323Sed // Loop over all of the callers of the function, transforming the call sites 263193323Sed // to pass in a smaller number of arguments into the new function. 264193323Sed // 265193323Sed std::vector<Value*> Args; 266193323Sed while (!Fn.use_empty()) { 267212904Sdim CallSite CS(Fn.use_back()); 268193323Sed Instruction *Call = CS.getInstruction(); 269193323Sed 270193323Sed // Pass all the same arguments. 271212904Sdim Args.assign(CS.arg_begin(), CS.arg_begin() + NumArgs); 272193323Sed 273193323Sed // Drop any attributes that were on the vararg arguments. 274249423Sdim AttributeSet PAL = CS.getAttributes(); 275249423Sdim if (!PAL.isEmpty() && PAL.getSlotIndex(PAL.getNumSlots() - 1) > NumArgs) { 276249423Sdim SmallVector<AttributeSet, 8> AttributesVec; 277249423Sdim for (unsigned i = 0; PAL.getSlotIndex(i) <= NumArgs; ++i) 278249423Sdim AttributesVec.push_back(PAL.getSlotAttributes(i)); 279249423Sdim if (PAL.hasAttributes(AttributeSet::FunctionIndex)) 280249423Sdim AttributesVec.push_back(AttributeSet::get(Fn.getContext(), 281249423Sdim PAL.getFnAttributes())); 282249423Sdim PAL = AttributeSet::get(Fn.getContext(), AttributesVec); 283193323Sed } 284193323Sed 285193323Sed Instruction *New; 286193323Sed if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 287193323Sed New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(), 288224145Sdim Args, "", Call); 289193323Sed cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv()); 290193323Sed cast<InvokeInst>(New)->setAttributes(PAL); 291193323Sed } else { 292224145Sdim New = CallInst::Create(NF, Args, "", Call); 293193323Sed cast<CallInst>(New)->setCallingConv(CS.getCallingConv()); 294193323Sed cast<CallInst>(New)->setAttributes(PAL); 295193323Sed if (cast<CallInst>(Call)->isTailCall()) 296193323Sed cast<CallInst>(New)->setTailCall(); 297193323Sed } 298212904Sdim New->setDebugLoc(Call->getDebugLoc()); 299207618Srdivacky 300193323Sed Args.clear(); 301193323Sed 302193323Sed if (!Call->use_empty()) 303193323Sed Call->replaceAllUsesWith(New); 304193323Sed 305193323Sed New->takeName(Call); 306193323Sed 307193323Sed // Finally, remove the old call from the program, reducing the use-count of 308193323Sed // F. 309193323Sed Call->eraseFromParent(); 310193323Sed } 311193323Sed 312193323Sed // Since we have now created the new function, splice the body of the old 313193323Sed // function right into the new function, leaving the old rotting hulk of the 314193323Sed // function empty. 315193323Sed NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList()); 316193323Sed 317221345Sdim // Loop over the argument list, transferring uses of the old arguments over to 318221345Sdim // the new arguments, also transferring over the names as well. While we're at 319193323Sed // it, remove the dead arguments from the DeadArguments list. 320193323Sed // 321193323Sed for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(), 322193323Sed I2 = NF->arg_begin(); I != E; ++I, ++I2) { 323193323Sed // Move the name and users over to the new version. 324193323Sed I->replaceAllUsesWith(I2); 325193323Sed I2->takeName(I); 326193323Sed } 327193323Sed 328243830Sdim // Patch the pointer to LLVM function in debug info descriptor. 329243830Sdim FunctionDIMap::iterator DI = FunctionDIs.find(&Fn); 330243830Sdim if (DI != FunctionDIs.end()) 331243830Sdim DI->second.replaceFunction(NF); 332243830Sdim 333193323Sed // Finally, nuke the old function. 334193323Sed Fn.eraseFromParent(); 335193323Sed return true; 336193323Sed} 337193323Sed 338218893Sdim/// RemoveDeadArgumentsFromCallers - Checks if the given function has any 339218893Sdim/// arguments that are unused, and changes the caller parameters to be undefined 340218893Sdim/// instead. 341218893Sdimbool DAE::RemoveDeadArgumentsFromCallers(Function &Fn) 342218893Sdim{ 343221345Sdim if (Fn.isDeclaration() || Fn.mayBeOverridden()) 344218893Sdim return false; 345218893Sdim 346218893Sdim // Functions with local linkage should already have been handled. 347218893Sdim if (Fn.hasLocalLinkage()) 348218893Sdim return false; 349218893Sdim 350218893Sdim if (Fn.use_empty()) 351218893Sdim return false; 352218893Sdim 353249423Sdim SmallVector<unsigned, 8> UnusedArgs; 354218893Sdim for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(); 355218893Sdim I != E; ++I) { 356218893Sdim Argument *Arg = I; 357218893Sdim 358218893Sdim if (Arg->use_empty() && !Arg->hasByValAttr()) 359218893Sdim UnusedArgs.push_back(Arg->getArgNo()); 360218893Sdim } 361218893Sdim 362218893Sdim if (UnusedArgs.empty()) 363218893Sdim return false; 364218893Sdim 365218893Sdim bool Changed = false; 366218893Sdim 367218893Sdim for (Function::use_iterator I = Fn.use_begin(), E = Fn.use_end(); 368218893Sdim I != E; ++I) { 369218893Sdim CallSite CS(*I); 370218893Sdim if (!CS || !CS.isCallee(I)) 371218893Sdim continue; 372218893Sdim 373218893Sdim // Now go through all unused args and replace them with "undef". 374218893Sdim for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) { 375218893Sdim unsigned ArgNo = UnusedArgs[I]; 376218893Sdim 377218893Sdim Value *Arg = CS.getArgument(ArgNo); 378218893Sdim CS.setArgument(ArgNo, UndefValue::get(Arg->getType())); 379218893Sdim ++NumArgumentsReplacedWithUndef; 380218893Sdim Changed = true; 381218893Sdim } 382218893Sdim } 383218893Sdim 384218893Sdim return Changed; 385218893Sdim} 386218893Sdim 387193323Sed/// Convenience function that returns the number of return values. It returns 0 388193323Sed/// for void functions and 1 for functions not returning a struct. It returns 389193323Sed/// the number of struct elements for functions returning a struct. 390193323Sedstatic unsigned NumRetVals(const Function *F) { 391206083Srdivacky if (F->getReturnType()->isVoidTy()) 392193323Sed return 0; 393226633Sdim else if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) 394193323Sed return STy->getNumElements(); 395193323Sed else 396193323Sed return 1; 397193323Sed} 398193323Sed 399193323Sed/// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not 400193323Sed/// live, it adds Use to the MaybeLiveUses argument. Returns the determined 401193323Sed/// liveness of Use. 402193323SedDAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) { 403193323Sed // We're live if our use or its Function is already marked as live. 404193323Sed if (LiveFunctions.count(Use.F) || LiveValues.count(Use)) 405193323Sed return Live; 406193323Sed 407193323Sed // We're maybe live otherwise, but remember that we must become live if 408193323Sed // Use becomes live. 409193323Sed MaybeLiveUses.push_back(Use); 410193323Sed return MaybeLive; 411193323Sed} 412193323Sed 413193323Sed 414193323Sed/// SurveyUse - This looks at a single use of an argument or return value 415193323Sed/// and determines if it should be alive or not. Adds this use to MaybeLiveUses 416206083Srdivacky/// if it causes the used value to become MaybeLive. 417193323Sed/// 418193323Sed/// RetValNum is the return value number to use when this use is used in a 419193323Sed/// return instruction. This is used in the recursion, you should always leave 420193323Sed/// it at 0. 421206083SrdivackyDAE::Liveness DAE::SurveyUse(Value::const_use_iterator U, 422206083Srdivacky UseVector &MaybeLiveUses, unsigned RetValNum) { 423206083Srdivacky const User *V = *U; 424206083Srdivacky if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) { 425193323Sed // The value is returned from a function. It's only live when the 426193323Sed // function's return value is live. We use RetValNum here, for the case 427193323Sed // that U is really a use of an insertvalue instruction that uses the 428221345Sdim // original Use. 429193323Sed RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum); 430193323Sed // We might be live, depending on the liveness of Use. 431193323Sed return MarkIfNotLive(Use, MaybeLiveUses); 432193323Sed } 433206083Srdivacky if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) { 434193323Sed if (U.getOperandNo() != InsertValueInst::getAggregateOperandIndex() 435193323Sed && IV->hasIndices()) 436193323Sed // The use we are examining is inserted into an aggregate. Our liveness 437193323Sed // depends on all uses of that aggregate, but if it is used as a return 438193323Sed // value, only index at which we were inserted counts. 439193323Sed RetValNum = *IV->idx_begin(); 440193323Sed 441193323Sed // Note that if we are used as the aggregate operand to the insertvalue, 442193323Sed // we don't change RetValNum, but do survey all our uses. 443193323Sed 444193323Sed Liveness Result = MaybeLive; 445206083Srdivacky for (Value::const_use_iterator I = IV->use_begin(), 446193323Sed E = V->use_end(); I != E; ++I) { 447193323Sed Result = SurveyUse(I, MaybeLiveUses, RetValNum); 448193323Sed if (Result == Live) 449193323Sed break; 450193323Sed } 451193323Sed return Result; 452193323Sed } 453206083Srdivacky 454206083Srdivacky if (ImmutableCallSite CS = V) { 455206083Srdivacky const Function *F = CS.getCalledFunction(); 456193323Sed if (F) { 457193323Sed // Used in a direct call. 458206083Srdivacky 459193323Sed // Find the argument number. We know for sure that this use is an 460193323Sed // argument, since if it was the function argument this would be an 461193323Sed // indirect call and the we know can't be looking at a value of the 462193323Sed // label type (for the invoke instruction). 463206083Srdivacky unsigned ArgNo = CS.getArgumentNo(U); 464193323Sed 465193323Sed if (ArgNo >= F->getFunctionType()->getNumParams()) 466193323Sed // The value is passed in through a vararg! Must be live. 467193323Sed return Live; 468193323Sed 469206083Srdivacky assert(CS.getArgument(ArgNo) 470206083Srdivacky == CS->getOperand(U.getOperandNo()) 471193323Sed && "Argument is not where we expected it"); 472193323Sed 473193323Sed // Value passed to a normal call. It's only live when the corresponding 474193323Sed // argument to the called function turns out live. 475193323Sed RetOrArg Use = CreateArg(F, ArgNo); 476193323Sed return MarkIfNotLive(Use, MaybeLiveUses); 477193323Sed } 478193323Sed } 479193323Sed // Used in any other way? Value must be live. 480193323Sed return Live; 481193323Sed} 482193323Sed 483193323Sed/// SurveyUses - This looks at all the uses of the given value 484193323Sed/// Returns the Liveness deduced from the uses of this value. 485193323Sed/// 486193323Sed/// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If 487193323Sed/// the result is Live, MaybeLiveUses might be modified but its content should 488193323Sed/// be ignored (since it might not be complete). 489206083SrdivackyDAE::Liveness DAE::SurveyUses(const Value *V, UseVector &MaybeLiveUses) { 490193323Sed // Assume it's dead (which will only hold if there are no uses at all..). 491193323Sed Liveness Result = MaybeLive; 492193323Sed // Check each use. 493206083Srdivacky for (Value::const_use_iterator I = V->use_begin(), 494193323Sed E = V->use_end(); I != E; ++I) { 495193323Sed Result = SurveyUse(I, MaybeLiveUses); 496193323Sed if (Result == Live) 497193323Sed break; 498193323Sed } 499193323Sed return Result; 500193323Sed} 501193323Sed 502193323Sed// SurveyFunction - This performs the initial survey of the specified function, 503193323Sed// checking out whether or not it uses any of its incoming arguments or whether 504193323Sed// any callers use the return value. This fills in the LiveValues set and Uses 505193323Sed// map. 506193323Sed// 507193323Sed// We consider arguments of non-internal functions to be intrinsically alive as 508193323Sed// well as arguments to functions which have their "address taken". 509193323Sed// 510206083Srdivackyvoid DAE::SurveyFunction(const Function &F) { 511193323Sed unsigned RetCount = NumRetVals(&F); 512193323Sed // Assume all return values are dead 513193323Sed typedef SmallVector<Liveness, 5> RetVals; 514193323Sed RetVals RetValLiveness(RetCount, MaybeLive); 515193323Sed 516193323Sed typedef SmallVector<UseVector, 5> RetUses; 517193323Sed // These vectors map each return value to the uses that make it MaybeLive, so 518193323Sed // we can add those to the Uses map if the return value really turns out to be 519193323Sed // MaybeLive. Initialized to a list of RetCount empty lists. 520193323Sed RetUses MaybeLiveRetUses(RetCount); 521193323Sed 522206083Srdivacky for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 523206083Srdivacky if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) 524193323Sed if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType() 525193323Sed != F.getFunctionType()->getReturnType()) { 526193323Sed // We don't support old style multiple return values. 527193323Sed MarkLive(F); 528193323Sed return; 529193323Sed } 530193323Sed 531193323Sed if (!F.hasLocalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) { 532193323Sed MarkLive(F); 533193323Sed return; 534193323Sed } 535193323Sed 536202375Srdivacky DEBUG(dbgs() << "DAE - Inspecting callers for fn: " << F.getName() << "\n"); 537193323Sed // Keep track of the number of live retvals, so we can skip checks once all 538193323Sed // of them turn out to be live. 539193323Sed unsigned NumLiveRetVals = 0; 540226633Sdim Type *STy = dyn_cast<StructType>(F.getReturnType()); 541193323Sed // Loop all uses of the function. 542206083Srdivacky for (Value::const_use_iterator I = F.use_begin(), E = F.use_end(); 543206083Srdivacky I != E; ++I) { 544193323Sed // If the function is PASSED IN as an argument, its address has been 545193323Sed // taken. 546206083Srdivacky ImmutableCallSite CS(*I); 547206083Srdivacky if (!CS || !CS.isCallee(I)) { 548193323Sed MarkLive(F); 549193323Sed return; 550193323Sed } 551193323Sed 552193323Sed // If this use is anything other than a call site, the function is alive. 553206083Srdivacky const Instruction *TheCall = CS.getInstruction(); 554193323Sed if (!TheCall) { // Not a direct call site? 555193323Sed MarkLive(F); 556193323Sed return; 557193323Sed } 558193323Sed 559193323Sed // If we end up here, we are looking at a direct call to our function. 560193323Sed 561193323Sed // Now, check how our return value(s) is/are used in this caller. Don't 562193323Sed // bother checking return values if all of them are live already. 563193323Sed if (NumLiveRetVals != RetCount) { 564193323Sed if (STy) { 565193323Sed // Check all uses of the return value. 566206083Srdivacky for (Value::const_use_iterator I = TheCall->use_begin(), 567193323Sed E = TheCall->use_end(); I != E; ++I) { 568206083Srdivacky const ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(*I); 569193323Sed if (Ext && Ext->hasIndices()) { 570193323Sed // This use uses a part of our return value, survey the uses of 571193323Sed // that part and store the results for this index only. 572193323Sed unsigned Idx = *Ext->idx_begin(); 573193323Sed if (RetValLiveness[Idx] != Live) { 574193323Sed RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]); 575193323Sed if (RetValLiveness[Idx] == Live) 576193323Sed NumLiveRetVals++; 577193323Sed } 578193323Sed } else { 579193323Sed // Used by something else than extractvalue. Mark all return 580193323Sed // values as live. 581193323Sed for (unsigned i = 0; i != RetCount; ++i ) 582193323Sed RetValLiveness[i] = Live; 583193323Sed NumLiveRetVals = RetCount; 584193323Sed break; 585193323Sed } 586193323Sed } 587193323Sed } else { 588193323Sed // Single return value 589193323Sed RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]); 590193323Sed if (RetValLiveness[0] == Live) 591193323Sed NumLiveRetVals = RetCount; 592193323Sed } 593193323Sed } 594193323Sed } 595193323Sed 596193323Sed // Now we've inspected all callers, record the liveness of our return values. 597193323Sed for (unsigned i = 0; i != RetCount; ++i) 598193323Sed MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]); 599193323Sed 600202375Srdivacky DEBUG(dbgs() << "DAE - Inspecting args for fn: " << F.getName() << "\n"); 601193323Sed 602193323Sed // Now, check all of our arguments. 603193323Sed unsigned i = 0; 604193323Sed UseVector MaybeLiveArgUses; 605206083Srdivacky for (Function::const_arg_iterator AI = F.arg_begin(), 606193323Sed E = F.arg_end(); AI != E; ++AI, ++i) { 607193323Sed // See what the effect of this use is (recording any uses that cause 608193323Sed // MaybeLive in MaybeLiveArgUses). 609193323Sed Liveness Result = SurveyUses(AI, MaybeLiveArgUses); 610193323Sed // Mark the result. 611193323Sed MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses); 612193323Sed // Clear the vector again for the next iteration. 613193323Sed MaybeLiveArgUses.clear(); 614193323Sed } 615193323Sed} 616193323Sed 617193323Sed/// MarkValue - This function marks the liveness of RA depending on L. If L is 618193323Sed/// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses, 619193323Sed/// such that RA will be marked live if any use in MaybeLiveUses gets marked 620193323Sed/// live later on. 621193323Sedvoid DAE::MarkValue(const RetOrArg &RA, Liveness L, 622193323Sed const UseVector &MaybeLiveUses) { 623193323Sed switch (L) { 624193323Sed case Live: MarkLive(RA); break; 625193323Sed case MaybeLive: 626193323Sed { 627193323Sed // Note any uses of this value, so this return value can be 628193323Sed // marked live whenever one of the uses becomes live. 629193323Sed for (UseVector::const_iterator UI = MaybeLiveUses.begin(), 630193323Sed UE = MaybeLiveUses.end(); UI != UE; ++UI) 631193323Sed Uses.insert(std::make_pair(*UI, RA)); 632193323Sed break; 633193323Sed } 634193323Sed } 635193323Sed} 636193323Sed 637193323Sed/// MarkLive - Mark the given Function as alive, meaning that it cannot be 638193323Sed/// changed in any way. Additionally, 639193323Sed/// mark any values that are used as this function's parameters or by its return 640193323Sed/// values (according to Uses) live as well. 641193323Sedvoid DAE::MarkLive(const Function &F) { 642202375Srdivacky DEBUG(dbgs() << "DAE - Intrinsically live fn: " << F.getName() << "\n"); 643208599Srdivacky // Mark the function as live. 644208599Srdivacky LiveFunctions.insert(&F); 645208599Srdivacky // Mark all arguments as live. 646208599Srdivacky for (unsigned i = 0, e = F.arg_size(); i != e; ++i) 647208599Srdivacky PropagateLiveness(CreateArg(&F, i)); 648208599Srdivacky // Mark all return values as live. 649208599Srdivacky for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i) 650208599Srdivacky PropagateLiveness(CreateRet(&F, i)); 651193323Sed} 652193323Sed 653193323Sed/// MarkLive - Mark the given return value or argument as live. Additionally, 654193323Sed/// mark any values that are used by this value (according to Uses) live as 655193323Sed/// well. 656193323Sedvoid DAE::MarkLive(const RetOrArg &RA) { 657193323Sed if (LiveFunctions.count(RA.F)) 658193323Sed return; // Function was already marked Live. 659193323Sed 660193323Sed if (!LiveValues.insert(RA).second) 661193323Sed return; // We were already marked Live. 662193323Sed 663202375Srdivacky DEBUG(dbgs() << "DAE - Marking " << RA.getDescription() << " live\n"); 664193323Sed PropagateLiveness(RA); 665193323Sed} 666193323Sed 667193323Sed/// PropagateLiveness - Given that RA is a live value, propagate it's liveness 668193323Sed/// to any other values it uses (according to Uses). 669193323Sedvoid DAE::PropagateLiveness(const RetOrArg &RA) { 670193323Sed // We don't use upper_bound (or equal_range) here, because our recursive call 671193323Sed // to ourselves is likely to cause the upper_bound (which is the first value 672193323Sed // not belonging to RA) to become erased and the iterator invalidated. 673193323Sed UseMap::iterator Begin = Uses.lower_bound(RA); 674193323Sed UseMap::iterator E = Uses.end(); 675193323Sed UseMap::iterator I; 676193323Sed for (I = Begin; I != E && I->first == RA; ++I) 677193323Sed MarkLive(I->second); 678193323Sed 679193323Sed // Erase RA from the Uses map (from the lower bound to wherever we ended up 680193323Sed // after the loop). 681193323Sed Uses.erase(Begin, I); 682193323Sed} 683193323Sed 684193323Sed// RemoveDeadStuffFromFunction - Remove any arguments and return values from F 685193323Sed// that are not in LiveValues. Transform the function and all of the callees of 686193323Sed// the function to not have these arguments and return values. 687193323Sed// 688193323Sedbool DAE::RemoveDeadStuffFromFunction(Function *F) { 689193323Sed // Don't modify fully live functions 690193323Sed if (LiveFunctions.count(F)) 691193323Sed return false; 692193323Sed 693193323Sed // Start by computing a new prototype for the function, which is the same as 694193323Sed // the old function, but has fewer arguments and a different return type. 695226633Sdim FunctionType *FTy = F->getFunctionType(); 696224145Sdim std::vector<Type*> Params; 697193323Sed 698193323Sed // Set up to build a new list of parameter attributes. 699249423Sdim SmallVector<AttributeSet, 8> AttributesVec; 700249423Sdim const AttributeSet &PAL = F->getAttributes(); 701193323Sed 702193323Sed // Find out the new return value. 703224145Sdim Type *RetTy = FTy->getReturnType(); 704226633Sdim Type *NRetTy = NULL; 705193323Sed unsigned RetCount = NumRetVals(F); 706206083Srdivacky 707193323Sed // -1 means unused, other numbers are the new index 708193323Sed SmallVector<int, 5> NewRetIdxs(RetCount, -1); 709224145Sdim std::vector<Type*> RetTypes; 710206083Srdivacky if (RetTy->isVoidTy()) { 711206083Srdivacky NRetTy = RetTy; 712193323Sed } else { 713226633Sdim StructType *STy = dyn_cast<StructType>(RetTy); 714193323Sed if (STy) 715193323Sed // Look at each of the original return values individually. 716193323Sed for (unsigned i = 0; i != RetCount; ++i) { 717193323Sed RetOrArg Ret = CreateRet(F, i); 718193323Sed if (LiveValues.erase(Ret)) { 719193323Sed RetTypes.push_back(STy->getElementType(i)); 720193323Sed NewRetIdxs[i] = RetTypes.size() - 1; 721193323Sed } else { 722193323Sed ++NumRetValsEliminated; 723202375Srdivacky DEBUG(dbgs() << "DAE - Removing return value " << i << " from " 724198090Srdivacky << F->getName() << "\n"); 725193323Sed } 726193323Sed } 727193323Sed else 728193323Sed // We used to return a single value. 729193323Sed if (LiveValues.erase(CreateRet(F, 0))) { 730193323Sed RetTypes.push_back(RetTy); 731193323Sed NewRetIdxs[0] = 0; 732193323Sed } else { 733202375Srdivacky DEBUG(dbgs() << "DAE - Removing return value from " << F->getName() 734198090Srdivacky << "\n"); 735193323Sed ++NumRetValsEliminated; 736193323Sed } 737193323Sed if (RetTypes.size() > 1) 738193323Sed // More than one return type? Return a struct with them. Also, if we used 739193323Sed // to return a struct and didn't change the number of return values, 740193323Sed // return a struct again. This prevents changing {something} into 741193323Sed // something and {} into void. 742193323Sed // Make the new struct packed if we used to return a packed struct 743193323Sed // already. 744198090Srdivacky NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked()); 745193323Sed else if (RetTypes.size() == 1) 746193323Sed // One return type? Just a simple value then, but only if we didn't use to 747193323Sed // return a struct with that simple value before. 748193323Sed NRetTy = RetTypes.front(); 749193323Sed else if (RetTypes.size() == 0) 750193323Sed // No return types? Make it void, but only if we didn't use to return {}. 751198090Srdivacky NRetTy = Type::getVoidTy(F->getContext()); 752193323Sed } 753193323Sed 754193323Sed assert(NRetTy && "No new return type found?"); 755193323Sed 756249423Sdim // The existing function return attributes. 757249423Sdim AttributeSet RAttrs = PAL.getRetAttributes(); 758249423Sdim 759193323Sed // Remove any incompatible attributes, but only if we removed all return 760193323Sed // values. Otherwise, ensure that we don't have any conflicting attributes 761193323Sed // here. Currently, this should not be possible, but special handling might be 762193323Sed // required when new return value attributes are added. 763206083Srdivacky if (NRetTy->isVoidTy()) 764243830Sdim RAttrs = 765249423Sdim AttributeSet::get(NRetTy->getContext(), AttributeSet::ReturnIndex, 766249423Sdim AttrBuilder(RAttrs, AttributeSet::ReturnIndex). 767249423Sdim removeAttributes(AttributeFuncs:: 768249423Sdim typeIncompatible(NRetTy, AttributeSet::ReturnIndex), 769249423Sdim AttributeSet::ReturnIndex)); 770193323Sed else 771249423Sdim assert(!AttrBuilder(RAttrs, AttributeSet::ReturnIndex). 772249423Sdim hasAttributes(AttributeFuncs:: 773249423Sdim typeIncompatible(NRetTy, AttributeSet::ReturnIndex), 774249423Sdim AttributeSet::ReturnIndex) && 775243830Sdim "Return attributes no longer compatible?"); 776193323Sed 777249423Sdim if (RAttrs.hasAttributes(AttributeSet::ReturnIndex)) 778249423Sdim AttributesVec.push_back(AttributeSet::get(NRetTy->getContext(), RAttrs)); 779193323Sed 780193323Sed // Remember which arguments are still alive. 781193323Sed SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false); 782193323Sed // Construct the new parameter list from non-dead arguments. Also construct 783193323Sed // a new set of parameter attributes to correspond. Skip the first parameter 784193323Sed // attribute, since that belongs to the return value. 785193323Sed unsigned i = 0; 786193323Sed for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); 787193323Sed I != E; ++I, ++i) { 788193323Sed RetOrArg Arg = CreateArg(F, i); 789193323Sed if (LiveValues.erase(Arg)) { 790193323Sed Params.push_back(I->getType()); 791193323Sed ArgAlive[i] = true; 792193323Sed 793193323Sed // Get the original parameter attributes (skipping the first one, that is 794193323Sed // for the return value. 795249423Sdim if (PAL.hasAttributes(i + 1)) { 796249423Sdim AttrBuilder B(PAL, i + 1); 797249423Sdim AttributesVec. 798249423Sdim push_back(AttributeSet::get(F->getContext(), Params.size(), B)); 799249423Sdim } 800193323Sed } else { 801193323Sed ++NumArgumentsEliminated; 802202375Srdivacky DEBUG(dbgs() << "DAE - Removing argument " << i << " (" << I->getName() 803198090Srdivacky << ") from " << F->getName() << "\n"); 804193323Sed } 805193323Sed } 806193323Sed 807249423Sdim if (PAL.hasAttributes(AttributeSet::FunctionIndex)) 808249423Sdim AttributesVec.push_back(AttributeSet::get(F->getContext(), 809249423Sdim PAL.getFnAttributes())); 810193323Sed 811193323Sed // Reconstruct the AttributesList based on the vector we constructed. 812249423Sdim AttributeSet NewPAL = AttributeSet::get(F->getContext(), AttributesVec); 813193323Sed 814193323Sed // Create the new function type based on the recomputed parameters. 815206083Srdivacky FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg()); 816193323Sed 817193323Sed // No change? 818193323Sed if (NFTy == FTy) 819193323Sed return false; 820193323Sed 821193323Sed // Create the new function body and insert it into the module... 822193323Sed Function *NF = Function::Create(NFTy, F->getLinkage()); 823193323Sed NF->copyAttributesFrom(F); 824193323Sed NF->setAttributes(NewPAL); 825193323Sed // Insert the new function before the old function, so we won't be processing 826193323Sed // it again. 827193323Sed F->getParent()->getFunctionList().insert(F, NF); 828193323Sed NF->takeName(F); 829193323Sed 830193323Sed // Loop over all of the callers of the function, transforming the call sites 831193323Sed // to pass in a smaller number of arguments into the new function. 832193323Sed // 833193323Sed std::vector<Value*> Args; 834193323Sed while (!F->use_empty()) { 835212904Sdim CallSite CS(F->use_back()); 836193323Sed Instruction *Call = CS.getInstruction(); 837193323Sed 838193323Sed AttributesVec.clear(); 839249423Sdim const AttributeSet &CallPAL = CS.getAttributes(); 840193323Sed 841193323Sed // The call return attributes. 842249423Sdim AttributeSet RAttrs = CallPAL.getRetAttributes(); 843249423Sdim 844193323Sed // Adjust in case the function was changed to return void. 845243830Sdim RAttrs = 846249423Sdim AttributeSet::get(NF->getContext(), AttributeSet::ReturnIndex, 847249423Sdim AttrBuilder(RAttrs, AttributeSet::ReturnIndex). 848249423Sdim removeAttributes(AttributeFuncs:: 849249423Sdim typeIncompatible(NF->getReturnType(), 850249423Sdim AttributeSet::ReturnIndex), 851249423Sdim AttributeSet::ReturnIndex)); 852249423Sdim if (RAttrs.hasAttributes(AttributeSet::ReturnIndex)) 853249423Sdim AttributesVec.push_back(AttributeSet::get(NF->getContext(), RAttrs)); 854193323Sed 855193323Sed // Declare these outside of the loops, so we can reuse them for the second 856193323Sed // loop, which loops the varargs. 857193323Sed CallSite::arg_iterator I = CS.arg_begin(); 858193323Sed unsigned i = 0; 859193323Sed // Loop over those operands, corresponding to the normal arguments to the 860193323Sed // original function, and add those that are still alive. 861193323Sed for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i) 862193323Sed if (ArgAlive[i]) { 863193323Sed Args.push_back(*I); 864193323Sed // Get original parameter attributes, but skip return attributes. 865249423Sdim if (CallPAL.hasAttributes(i + 1)) { 866249423Sdim AttrBuilder B(CallPAL, i + 1); 867249423Sdim AttributesVec. 868249423Sdim push_back(AttributeSet::get(F->getContext(), Args.size(), B)); 869249423Sdim } 870193323Sed } 871193323Sed 872193323Sed // Push any varargs arguments on the list. Don't forget their attributes. 873193323Sed for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) { 874193323Sed Args.push_back(*I); 875249423Sdim if (CallPAL.hasAttributes(i + 1)) { 876249423Sdim AttrBuilder B(CallPAL, i + 1); 877249423Sdim AttributesVec. 878249423Sdim push_back(AttributeSet::get(F->getContext(), Args.size(), B)); 879249423Sdim } 880193323Sed } 881193323Sed 882249423Sdim if (CallPAL.hasAttributes(AttributeSet::FunctionIndex)) 883249423Sdim AttributesVec.push_back(AttributeSet::get(Call->getContext(), 884249423Sdim CallPAL.getFnAttributes())); 885193323Sed 886193323Sed // Reconstruct the AttributesList based on the vector we constructed. 887249423Sdim AttributeSet NewCallPAL = AttributeSet::get(F->getContext(), AttributesVec); 888193323Sed 889193323Sed Instruction *New; 890193323Sed if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 891193323Sed New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(), 892224145Sdim Args, "", Call); 893193323Sed cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv()); 894193323Sed cast<InvokeInst>(New)->setAttributes(NewCallPAL); 895193323Sed } else { 896224145Sdim New = CallInst::Create(NF, Args, "", Call); 897193323Sed cast<CallInst>(New)->setCallingConv(CS.getCallingConv()); 898193323Sed cast<CallInst>(New)->setAttributes(NewCallPAL); 899193323Sed if (cast<CallInst>(Call)->isTailCall()) 900193323Sed cast<CallInst>(New)->setTailCall(); 901193323Sed } 902212904Sdim New->setDebugLoc(Call->getDebugLoc()); 903207618Srdivacky 904193323Sed Args.clear(); 905193323Sed 906193323Sed if (!Call->use_empty()) { 907193323Sed if (New->getType() == Call->getType()) { 908193323Sed // Return type not changed? Just replace users then. 909193323Sed Call->replaceAllUsesWith(New); 910193323Sed New->takeName(Call); 911206083Srdivacky } else if (New->getType()->isVoidTy()) { 912193323Sed // Our return value has uses, but they will get removed later on. 913193323Sed // Replace by null for now. 914218893Sdim if (!Call->getType()->isX86_MMXTy()) 915218893Sdim Call->replaceAllUsesWith(Constant::getNullValue(Call->getType())); 916193323Sed } else { 917204642Srdivacky assert(RetTy->isStructTy() && 918193323Sed "Return type changed, but not into a void. The old return type" 919193323Sed " must have been a struct!"); 920193323Sed Instruction *InsertPt = Call; 921193323Sed if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 922193323Sed BasicBlock::iterator IP = II->getNormalDest()->begin(); 923193323Sed while (isa<PHINode>(IP)) ++IP; 924193323Sed InsertPt = IP; 925193323Sed } 926206083Srdivacky 927193323Sed // We used to return a struct. Instead of doing smart stuff with all the 928193323Sed // uses of this struct, we will just rebuild it using 929193323Sed // extract/insertvalue chaining and let instcombine clean that up. 930193323Sed // 931193323Sed // Start out building up our return value from undef 932198090Srdivacky Value *RetVal = UndefValue::get(RetTy); 933193323Sed for (unsigned i = 0; i != RetCount; ++i) 934193323Sed if (NewRetIdxs[i] != -1) { 935193323Sed Value *V; 936193323Sed if (RetTypes.size() > 1) 937193323Sed // We are still returning a struct, so extract the value from our 938193323Sed // return value 939193323Sed V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret", 940193323Sed InsertPt); 941193323Sed else 942193323Sed // We are now returning a single element, so just insert that 943193323Sed V = New; 944193323Sed // Insert the value at the old position 945193323Sed RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt); 946193323Sed } 947193323Sed // Now, replace all uses of the old call instruction with the return 948193323Sed // struct we built 949193323Sed Call->replaceAllUsesWith(RetVal); 950193323Sed New->takeName(Call); 951193323Sed } 952193323Sed } 953193323Sed 954193323Sed // Finally, remove the old call from the program, reducing the use-count of 955193323Sed // F. 956193323Sed Call->eraseFromParent(); 957193323Sed } 958193323Sed 959193323Sed // Since we have now created the new function, splice the body of the old 960193323Sed // function right into the new function, leaving the old rotting hulk of the 961193323Sed // function empty. 962193323Sed NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList()); 963193323Sed 964221345Sdim // Loop over the argument list, transferring uses of the old arguments over to 965221345Sdim // the new arguments, also transferring over the names as well. 966193323Sed i = 0; 967193323Sed for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(), 968193323Sed I2 = NF->arg_begin(); I != E; ++I, ++i) 969193323Sed if (ArgAlive[i]) { 970193323Sed // If this is a live argument, move the name and users over to the new 971193323Sed // version. 972193323Sed I->replaceAllUsesWith(I2); 973193323Sed I2->takeName(I); 974193323Sed ++I2; 975193323Sed } else { 976193323Sed // If this argument is dead, replace any uses of it with null constants 977193323Sed // (these are guaranteed to become unused later on). 978218893Sdim if (!I->getType()->isX86_MMXTy()) 979218893Sdim I->replaceAllUsesWith(Constant::getNullValue(I->getType())); 980193323Sed } 981193323Sed 982193323Sed // If we change the return value of the function we must rewrite any return 983193323Sed // instructions. Check this now. 984193323Sed if (F->getReturnType() != NF->getReturnType()) 985193323Sed for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB) 986193323Sed if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { 987193323Sed Value *RetVal; 988193323Sed 989208599Srdivacky if (NFTy->getReturnType()->isVoidTy()) { 990193323Sed RetVal = 0; 991193323Sed } else { 992204642Srdivacky assert (RetTy->isStructTy()); 993193323Sed // The original return value was a struct, insert 994193323Sed // extractvalue/insertvalue chains to extract only the values we need 995193323Sed // to return and insert them into our new result. 996193323Sed // This does generate messy code, but we'll let it to instcombine to 997193323Sed // clean that up. 998193323Sed Value *OldRet = RI->getOperand(0); 999193323Sed // Start out building up our return value from undef 1000198090Srdivacky RetVal = UndefValue::get(NRetTy); 1001193323Sed for (unsigned i = 0; i != RetCount; ++i) 1002193323Sed if (NewRetIdxs[i] != -1) { 1003193323Sed ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i, 1004193323Sed "oldret", RI); 1005193323Sed if (RetTypes.size() > 1) { 1006193323Sed // We're still returning a struct, so reinsert the value into 1007193323Sed // our new return value at the new index 1008193323Sed 1009193323Sed RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i], 1010193323Sed "newret", RI); 1011193323Sed } else { 1012193323Sed // We are now only returning a simple value, so just return the 1013193323Sed // extracted value. 1014193323Sed RetVal = EV; 1015193323Sed } 1016193323Sed } 1017193323Sed } 1018193323Sed // Replace the return instruction with one returning the new return 1019193323Sed // value (possibly 0 if we became void). 1020198090Srdivacky ReturnInst::Create(F->getContext(), RetVal, RI); 1021193323Sed BB->getInstList().erase(RI); 1022193323Sed } 1023193323Sed 1024243830Sdim // Patch the pointer to LLVM function in debug info descriptor. 1025243830Sdim FunctionDIMap::iterator DI = FunctionDIs.find(F); 1026243830Sdim if (DI != FunctionDIs.end()) 1027243830Sdim DI->second.replaceFunction(NF); 1028243830Sdim 1029193323Sed // Now that the old function is dead, delete it. 1030193323Sed F->eraseFromParent(); 1031193323Sed 1032193323Sed return true; 1033193323Sed} 1034193323Sed 1035193323Sedbool DAE::runOnModule(Module &M) { 1036193323Sed bool Changed = false; 1037193323Sed 1038243830Sdim // Collect debug info descriptors for functions. 1039243830Sdim CollectFunctionDIs(M); 1040243830Sdim 1041193323Sed // First pass: Do a simple check to see if any functions can have their "..." 1042193323Sed // removed. We can do this if they never call va_start. This loop cannot be 1043193323Sed // fused with the next loop, because deleting a function invalidates 1044193323Sed // information computed while surveying other functions. 1045202375Srdivacky DEBUG(dbgs() << "DAE - Deleting dead varargs\n"); 1046193323Sed for (Module::iterator I = M.begin(), E = M.end(); I != E; ) { 1047193323Sed Function &F = *I++; 1048193323Sed if (F.getFunctionType()->isVarArg()) 1049193323Sed Changed |= DeleteDeadVarargs(F); 1050193323Sed } 1051193323Sed 1052193323Sed // Second phase:loop through the module, determining which arguments are live. 1053193323Sed // We assume all arguments are dead unless proven otherwise (allowing us to 1054193323Sed // determine that dead arguments passed into recursive functions are dead). 1055193323Sed // 1056202375Srdivacky DEBUG(dbgs() << "DAE - Determining liveness\n"); 1057193323Sed for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 1058193323Sed SurveyFunction(*I); 1059206083Srdivacky 1060193323Sed // Now, remove all dead arguments and return values from each function in 1061206083Srdivacky // turn. 1062193323Sed for (Module::iterator I = M.begin(), E = M.end(); I != E; ) { 1063206083Srdivacky // Increment now, because the function will probably get removed (ie. 1064193323Sed // replaced by a new one). 1065193323Sed Function *F = I++; 1066193323Sed Changed |= RemoveDeadStuffFromFunction(F); 1067193323Sed } 1068218893Sdim 1069218893Sdim // Finally, look for any unused parameters in functions with non-local 1070218893Sdim // linkage and replace the passed in parameters with undef. 1071218893Sdim for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { 1072218893Sdim Function& F = *I; 1073218893Sdim 1074218893Sdim Changed |= RemoveDeadArgumentsFromCallers(F); 1075218893Sdim } 1076218893Sdim 1077193323Sed return Changed; 1078193323Sed} 1079