DeadArgumentElimination.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  1. //===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass deletes dead arguments from internal functions. Dead argument
  11. // elimination removes arguments which are directly dead, as well as arguments
  12. // only passed into function calls as dead arguments of other functions. This
  13. // pass also deletes dead return values in a similar way.
  14. //
  15. // This pass is often useful as a cleanup pass to run after aggressive
  16. // interprocedural passes, which add possibly-dead arguments or return values.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #include "llvm/Transforms/IPO.h"
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/ADT/StringExtras.h"
  24. #include "llvm/IR/CallSite.h"
  25. #include "llvm/IR/CallingConv.h"
  26. #include "llvm/IR/Constant.h"
  27. #include "llvm/IR/DIBuilder.h"
  28. #include "llvm/IR/DebugInfo.h"
  29. #include "llvm/IR/DerivedTypes.h"
  30. #include "llvm/IR/Instructions.h"
  31. #include "llvm/IR/IntrinsicInst.h"
  32. #include "llvm/IR/LLVMContext.h"
  33. #include "llvm/IR/Module.h"
  34. #include "llvm/Pass.h"
  35. #include "llvm/Support/Debug.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include <map>
  38. #include <set>
  39. #include <tuple>
  40. using namespace llvm;
  41. #define DEBUG_TYPE "deadargelim"
  42. STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
  43. STATISTIC(NumRetValsEliminated , "Number of unused return values removed");
  44. STATISTIC(NumArgumentsReplacedWithUndef,
  45. "Number of unread args replaced with undef");
  46. namespace {
  47. /// DAE - The dead argument elimination pass.
  48. ///
  49. class DAE : public ModulePass {
  50. public:
  51. /// Struct that represents (part of) either a return value or a function
  52. /// argument. Used so that arguments and return values can be used
  53. /// interchangeably.
  54. struct RetOrArg {
  55. RetOrArg(const Function *F, unsigned Idx, bool IsArg) : F(F), Idx(Idx),
  56. IsArg(IsArg) {}
  57. const Function *F;
  58. unsigned Idx;
  59. bool IsArg;
  60. /// Make RetOrArg comparable, so we can put it into a map.
  61. bool operator<(const RetOrArg &O) const {
  62. return std::tie(F, Idx, IsArg) < std::tie(O.F, O.Idx, O.IsArg);
  63. }
  64. /// Make RetOrArg comparable, so we can easily iterate the multimap.
  65. bool operator==(const RetOrArg &O) const {
  66. return F == O.F && Idx == O.Idx && IsArg == O.IsArg;
  67. }
  68. std::string getDescription() const {
  69. return (Twine(IsArg ? "Argument #" : "Return value #") + utostr(Idx) +
  70. " of function " + F->getName()).str();
  71. }
  72. };
  73. /// Liveness enum - During our initial pass over the program, we determine
  74. /// that things are either alive or maybe alive. We don't mark anything
  75. /// explicitly dead (even if we know they are), since anything not alive
  76. /// with no registered uses (in Uses) will never be marked alive and will
  77. /// thus become dead in the end.
  78. enum Liveness { Live, MaybeLive };
  79. /// Convenience wrapper
  80. RetOrArg CreateRet(const Function *F, unsigned Idx) {
  81. return RetOrArg(F, Idx, false);
  82. }
  83. /// Convenience wrapper
  84. RetOrArg CreateArg(const Function *F, unsigned Idx) {
  85. return RetOrArg(F, Idx, true);
  86. }
  87. typedef std::multimap<RetOrArg, RetOrArg> UseMap;
  88. /// This maps a return value or argument to any MaybeLive return values or
  89. /// arguments it uses. This allows the MaybeLive values to be marked live
  90. /// when any of its users is marked live.
  91. /// For example (indices are left out for clarity):
  92. /// - Uses[ret F] = ret G
  93. /// This means that F calls G, and F returns the value returned by G.
  94. /// - Uses[arg F] = ret G
  95. /// This means that some function calls G and passes its result as an
  96. /// argument to F.
  97. /// - Uses[ret F] = arg F
  98. /// This means that F returns one of its own arguments.
  99. /// - Uses[arg F] = arg G
  100. /// This means that G calls F and passes one of its own (G's) arguments
  101. /// directly to F.
  102. UseMap Uses;
  103. typedef std::set<RetOrArg> LiveSet;
  104. typedef std::set<const Function*> LiveFuncSet;
  105. /// This set contains all values that have been determined to be live.
  106. LiveSet LiveValues;
  107. /// This set contains all values that are cannot be changed in any way.
  108. LiveFuncSet LiveFunctions;
  109. typedef SmallVector<RetOrArg, 5> UseVector;
  110. // Map each LLVM function to corresponding metadata with debug info. If
  111. // the function is replaced with another one, we should patch the pointer
  112. // to LLVM function in metadata.
  113. // As the code generation for module is finished (and DIBuilder is
  114. // finalized) we assume that subprogram descriptors won't be changed, and
  115. // they are stored in map for short duration anyway.
  116. DenseMap<const Function *, DISubprogram *> FunctionDIs;
  117. protected:
  118. // DAH uses this to specify a different ID.
  119. explicit DAE(char &ID) : ModulePass(ID) {}
  120. public:
  121. static char ID; // Pass identification, replacement for typeid
  122. DAE() : ModulePass(ID) {
  123. initializeDAEPass(*PassRegistry::getPassRegistry());
  124. }
  125. bool runOnModule(Module &M) override;
  126. virtual bool ShouldHackArguments() const { return false; }
  127. private:
  128. Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
  129. Liveness SurveyUse(const Use *U, UseVector &MaybeLiveUses,
  130. unsigned RetValNum = -1U);
  131. Liveness SurveyUses(const Value *V, UseVector &MaybeLiveUses);
  132. void SurveyFunction(const Function &F);
  133. void MarkValue(const RetOrArg &RA, Liveness L,
  134. const UseVector &MaybeLiveUses);
  135. void MarkLive(const RetOrArg &RA);
  136. void MarkLive(const Function &F);
  137. void PropagateLiveness(const RetOrArg &RA);
  138. bool RemoveDeadStuffFromFunction(Function *F);
  139. bool DeleteDeadVarargs(Function &Fn);
  140. bool RemoveDeadArgumentsFromCallers(Function &Fn);
  141. };
  142. }
  143. char DAE::ID = 0;
  144. INITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false)
  145. namespace {
  146. /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
  147. /// deletes arguments to functions which are external. This is only for use
  148. /// by bugpoint.
  149. struct DAH : public DAE {
  150. static char ID;
  151. DAH() : DAE(ID) {}
  152. bool ShouldHackArguments() const override { return true; }
  153. };
  154. }
  155. char DAH::ID = 0;
  156. INITIALIZE_PASS(DAH, "deadarghaX0r",
  157. "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)",
  158. false, false)
  159. /// createDeadArgEliminationPass - This pass removes arguments from functions
  160. /// which are not used by the body of the function.
  161. ///
  162. ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
  163. ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
  164. /// DeleteDeadVarargs - If this is an function that takes a ... list, and if
  165. /// llvm.vastart is never called, the varargs list is dead for the function.
  166. bool DAE::DeleteDeadVarargs(Function &Fn) {
  167. assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
  168. if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false;
  169. // Ensure that the function is only directly called.
  170. if (Fn.hasAddressTaken())
  171. return false;
  172. // Okay, we know we can transform this function if safe. Scan its body
  173. // looking for calls marked musttail or calls to llvm.vastart.
  174. for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
  175. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  176. CallInst *CI = dyn_cast<CallInst>(I);
  177. if (!CI)
  178. continue;
  179. if (CI->isMustTailCall())
  180. return false;
  181. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
  182. if (II->getIntrinsicID() == Intrinsic::vastart)
  183. return false;
  184. }
  185. }
  186. }
  187. // If we get here, there are no calls to llvm.vastart in the function body,
  188. // remove the "..." and adjust all the calls.
  189. // Start by computing a new prototype for the function, which is the same as
  190. // the old function, but doesn't have isVarArg set.
  191. FunctionType *FTy = Fn.getFunctionType();
  192. std::vector<Type*> Params(FTy->param_begin(), FTy->param_end());
  193. FunctionType *NFTy = FunctionType::get(FTy->getReturnType(),
  194. Params, false);
  195. unsigned NumArgs = Params.size();
  196. // Create the new function body and insert it into the module...
  197. Function *NF = Function::Create(NFTy, Fn.getLinkage());
  198. NF->copyAttributesFrom(&Fn);
  199. Fn.getParent()->getFunctionList().insert(&Fn, NF);
  200. NF->takeName(&Fn);
  201. // Loop over all of the callers of the function, transforming the call sites
  202. // to pass in a smaller number of arguments into the new function.
  203. //
  204. std::vector<Value*> Args;
  205. for (Value::user_iterator I = Fn.user_begin(), E = Fn.user_end(); I != E; ) {
  206. CallSite CS(*I++);
  207. if (!CS)
  208. continue;
  209. Instruction *Call = CS.getInstruction();
  210. // Pass all the same arguments.
  211. Args.assign(CS.arg_begin(), CS.arg_begin() + NumArgs);
  212. // Drop any attributes that were on the vararg arguments.
  213. AttributeSet PAL = CS.getAttributes();
  214. if (!PAL.isEmpty() && PAL.getSlotIndex(PAL.getNumSlots() - 1) > NumArgs) {
  215. SmallVector<AttributeSet, 8> AttributesVec;
  216. for (unsigned i = 0; PAL.getSlotIndex(i) <= NumArgs; ++i)
  217. AttributesVec.push_back(PAL.getSlotAttributes(i));
  218. if (PAL.hasAttributes(AttributeSet::FunctionIndex))
  219. AttributesVec.push_back(AttributeSet::get(Fn.getContext(),
  220. PAL.getFnAttributes()));
  221. PAL = AttributeSet::get(Fn.getContext(), AttributesVec);
  222. }
  223. Instruction *New;
  224. if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
  225. New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
  226. Args, "", Call);
  227. cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
  228. cast<InvokeInst>(New)->setAttributes(PAL);
  229. } else {
  230. New = CallInst::Create(NF, Args, "", Call);
  231. cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
  232. cast<CallInst>(New)->setAttributes(PAL);
  233. if (cast<CallInst>(Call)->isTailCall())
  234. cast<CallInst>(New)->setTailCall();
  235. }
  236. New->setDebugLoc(Call->getDebugLoc());
  237. Args.clear();
  238. if (!Call->use_empty())
  239. Call->replaceAllUsesWith(New);
  240. New->takeName(Call);
  241. // Finally, remove the old call from the program, reducing the use-count of
  242. // F.
  243. Call->eraseFromParent();
  244. }
  245. // Since we have now created the new function, splice the body of the old
  246. // function right into the new function, leaving the old rotting hulk of the
  247. // function empty.
  248. NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
  249. // Loop over the argument list, transferring uses of the old arguments over to
  250. // the new arguments, also transferring over the names as well. While we're at
  251. // it, remove the dead arguments from the DeadArguments list.
  252. //
  253. for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
  254. I2 = NF->arg_begin(); I != E; ++I, ++I2) {
  255. // Move the name and users over to the new version.
  256. I->replaceAllUsesWith(I2);
  257. I2->takeName(I);
  258. }
  259. // Patch the pointer to LLVM function in debug info descriptor.
  260. auto DI = FunctionDIs.find(&Fn);
  261. if (DI != FunctionDIs.end()) {
  262. DISubprogram *SP = DI->second;
  263. SP->replaceFunction(NF);
  264. // Ensure the map is updated so it can be reused on non-varargs argument
  265. // eliminations of the same function.
  266. FunctionDIs.erase(DI);
  267. FunctionDIs[NF] = SP;
  268. }
  269. // Fix up any BlockAddresses that refer to the function.
  270. Fn.replaceAllUsesWith(ConstantExpr::getBitCast(NF, Fn.getType()));
  271. // Delete the bitcast that we just created, so that NF does not
  272. // appear to be address-taken.
  273. NF->removeDeadConstantUsers();
  274. // Finally, nuke the old function.
  275. Fn.eraseFromParent();
  276. return true;
  277. }
  278. /// RemoveDeadArgumentsFromCallers - Checks if the given function has any
  279. /// arguments that are unused, and changes the caller parameters to be undefined
  280. /// instead.
  281. bool DAE::RemoveDeadArgumentsFromCallers(Function &Fn)
  282. {
  283. // We cannot change the arguments if this TU does not define the function or
  284. // if the linker may choose a function body from another TU, even if the
  285. // nominal linkage indicates that other copies of the function have the same
  286. // semantics. In the below example, the dead load from %p may not have been
  287. // eliminated from the linker-chosen copy of f, so replacing %p with undef
  288. // in callers may introduce undefined behavior.
  289. //
  290. // define linkonce_odr void @f(i32* %p) {
  291. // %v = load i32 %p
  292. // ret void
  293. // }
  294. if (!Fn.isStrongDefinitionForLinker())
  295. return false;
  296. // Functions with local linkage should already have been handled, except the
  297. // fragile (variadic) ones which we can improve here.
  298. if (Fn.hasLocalLinkage() && !Fn.getFunctionType()->isVarArg())
  299. return false;
  300. if (Fn.use_empty())
  301. return false;
  302. SmallVector<unsigned, 8> UnusedArgs;
  303. for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
  304. I != E; ++I) {
  305. Argument *Arg = I;
  306. if (Arg->use_empty() && !Arg->hasByValOrInAllocaAttr())
  307. UnusedArgs.push_back(Arg->getArgNo());
  308. }
  309. if (UnusedArgs.empty())
  310. return false;
  311. bool Changed = false;
  312. for (Use &U : Fn.uses()) {
  313. CallSite CS(U.getUser());
  314. if (!CS || !CS.isCallee(&U))
  315. continue;
  316. // Now go through all unused args and replace them with "undef".
  317. for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) {
  318. unsigned ArgNo = UnusedArgs[I];
  319. Value *Arg = CS.getArgument(ArgNo);
  320. CS.setArgument(ArgNo, UndefValue::get(Arg->getType()));
  321. ++NumArgumentsReplacedWithUndef;
  322. Changed = true;
  323. }
  324. }
  325. return Changed;
  326. }
  327. /// Convenience function that returns the number of return values. It returns 0
  328. /// for void functions and 1 for functions not returning a struct. It returns
  329. /// the number of struct elements for functions returning a struct.
  330. static unsigned NumRetVals(const Function *F) {
  331. Type *RetTy = F->getReturnType();
  332. if (RetTy->isVoidTy())
  333. return 0;
  334. else if (StructType *STy = dyn_cast<StructType>(RetTy))
  335. return STy->getNumElements();
  336. else if (ArrayType *ATy = dyn_cast<ArrayType>(RetTy))
  337. return ATy->getNumElements();
  338. else
  339. return 1;
  340. }
  341. /// Returns the sub-type a function will return at a given Idx. Should
  342. /// correspond to the result type of an ExtractValue instruction executed with
  343. /// just that one Idx (i.e. only top-level structure is considered).
  344. static Type *getRetComponentType(const Function *F, unsigned Idx) {
  345. Type *RetTy = F->getReturnType();
  346. assert(!RetTy->isVoidTy() && "void type has no subtype");
  347. if (StructType *STy = dyn_cast<StructType>(RetTy))
  348. return STy->getElementType(Idx);
  349. else if (ArrayType *ATy = dyn_cast<ArrayType>(RetTy))
  350. return ATy->getElementType();
  351. else
  352. return RetTy;
  353. }
  354. /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
  355. /// live, it adds Use to the MaybeLiveUses argument. Returns the determined
  356. /// liveness of Use.
  357. DAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
  358. // We're live if our use or its Function is already marked as live.
  359. if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
  360. return Live;
  361. // We're maybe live otherwise, but remember that we must become live if
  362. // Use becomes live.
  363. MaybeLiveUses.push_back(Use);
  364. return MaybeLive;
  365. }
  366. /// SurveyUse - This looks at a single use of an argument or return value
  367. /// and determines if it should be alive or not. Adds this use to MaybeLiveUses
  368. /// if it causes the used value to become MaybeLive.
  369. ///
  370. /// RetValNum is the return value number to use when this use is used in a
  371. /// return instruction. This is used in the recursion, you should always leave
  372. /// it at 0.
  373. DAE::Liveness DAE::SurveyUse(const Use *U,
  374. UseVector &MaybeLiveUses, unsigned RetValNum) {
  375. const User *V = U->getUser();
  376. if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
  377. // The value is returned from a function. It's only live when the
  378. // function's return value is live. We use RetValNum here, for the case
  379. // that U is really a use of an insertvalue instruction that uses the
  380. // original Use.
  381. const Function *F = RI->getParent()->getParent();
  382. if (RetValNum != -1U) {
  383. RetOrArg Use = CreateRet(F, RetValNum);
  384. // We might be live, depending on the liveness of Use.
  385. return MarkIfNotLive(Use, MaybeLiveUses);
  386. } else {
  387. DAE::Liveness Result = MaybeLive;
  388. for (unsigned i = 0; i < NumRetVals(F); ++i) {
  389. RetOrArg Use = CreateRet(F, i);
  390. // We might be live, depending on the liveness of Use. If any
  391. // sub-value is live, then the entire value is considered live. This
  392. // is a conservative choice, and better tracking is possible.
  393. DAE::Liveness SubResult = MarkIfNotLive(Use, MaybeLiveUses);
  394. if (Result != Live)
  395. Result = SubResult;
  396. }
  397. return Result;
  398. }
  399. }
  400. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
  401. if (U->getOperandNo() != InsertValueInst::getAggregateOperandIndex()
  402. && IV->hasIndices())
  403. // The use we are examining is inserted into an aggregate. Our liveness
  404. // depends on all uses of that aggregate, but if it is used as a return
  405. // value, only index at which we were inserted counts.
  406. RetValNum = *IV->idx_begin();
  407. // Note that if we are used as the aggregate operand to the insertvalue,
  408. // we don't change RetValNum, but do survey all our uses.
  409. Liveness Result = MaybeLive;
  410. for (const Use &UU : IV->uses()) {
  411. Result = SurveyUse(&UU, MaybeLiveUses, RetValNum);
  412. if (Result == Live)
  413. break;
  414. }
  415. return Result;
  416. }
  417. if (auto CS = ImmutableCallSite(V)) {
  418. const Function *F = CS.getCalledFunction();
  419. if (F) {
  420. // Used in a direct call.
  421. // Find the argument number. We know for sure that this use is an
  422. // argument, since if it was the function argument this would be an
  423. // indirect call and the we know can't be looking at a value of the
  424. // label type (for the invoke instruction).
  425. unsigned ArgNo = CS.getArgumentNo(U);
  426. if (ArgNo >= F->getFunctionType()->getNumParams())
  427. // The value is passed in through a vararg! Must be live.
  428. return Live;
  429. assert(CS.getArgument(ArgNo)
  430. == CS->getOperand(U->getOperandNo())
  431. && "Argument is not where we expected it");
  432. // Value passed to a normal call. It's only live when the corresponding
  433. // argument to the called function turns out live.
  434. RetOrArg Use = CreateArg(F, ArgNo);
  435. return MarkIfNotLive(Use, MaybeLiveUses);
  436. }
  437. }
  438. // Used in any other way? Value must be live.
  439. return Live;
  440. }
  441. /// SurveyUses - This looks at all the uses of the given value
  442. /// Returns the Liveness deduced from the uses of this value.
  443. ///
  444. /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
  445. /// the result is Live, MaybeLiveUses might be modified but its content should
  446. /// be ignored (since it might not be complete).
  447. DAE::Liveness DAE::SurveyUses(const Value *V, UseVector &MaybeLiveUses) {
  448. // Assume it's dead (which will only hold if there are no uses at all..).
  449. Liveness Result = MaybeLive;
  450. // Check each use.
  451. for (const Use &U : V->uses()) {
  452. Result = SurveyUse(&U, MaybeLiveUses);
  453. if (Result == Live)
  454. break;
  455. }
  456. return Result;
  457. }
  458. // SurveyFunction - This performs the initial survey of the specified function,
  459. // checking out whether or not it uses any of its incoming arguments or whether
  460. // any callers use the return value. This fills in the LiveValues set and Uses
  461. // map.
  462. //
  463. // We consider arguments of non-internal functions to be intrinsically alive as
  464. // well as arguments to functions which have their "address taken".
  465. //
  466. void DAE::SurveyFunction(const Function &F) {
  467. // Functions with inalloca parameters are expecting args in a particular
  468. // register and memory layout.
  469. if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca)) {
  470. MarkLive(F);
  471. return;
  472. }
  473. unsigned RetCount = NumRetVals(&F);
  474. // Assume all return values are dead
  475. typedef SmallVector<Liveness, 5> RetVals;
  476. RetVals RetValLiveness(RetCount, MaybeLive);
  477. typedef SmallVector<UseVector, 5> RetUses;
  478. // These vectors map each return value to the uses that make it MaybeLive, so
  479. // we can add those to the Uses map if the return value really turns out to be
  480. // MaybeLive. Initialized to a list of RetCount empty lists.
  481. RetUses MaybeLiveRetUses(RetCount);
  482. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
  483. if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
  484. if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
  485. != F.getFunctionType()->getReturnType()) {
  486. // We don't support old style multiple return values.
  487. MarkLive(F);
  488. return;
  489. }
  490. if (!F.hasLocalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
  491. MarkLive(F);
  492. return;
  493. }
  494. DEBUG(dbgs() << "DAE - Inspecting callers for fn: " << F.getName() << "\n");
  495. // Keep track of the number of live retvals, so we can skip checks once all
  496. // of them turn out to be live.
  497. unsigned NumLiveRetVals = 0;
  498. // Loop all uses of the function.
  499. for (const Use &U : F.uses()) {
  500. // If the function is PASSED IN as an argument, its address has been
  501. // taken.
  502. ImmutableCallSite CS(U.getUser());
  503. if (!CS || !CS.isCallee(&U)) {
  504. MarkLive(F);
  505. return;
  506. }
  507. // If this use is anything other than a call site, the function is alive.
  508. const Instruction *TheCall = CS.getInstruction();
  509. if (!TheCall) { // Not a direct call site?
  510. MarkLive(F);
  511. return;
  512. }
  513. // If we end up here, we are looking at a direct call to our function.
  514. // Now, check how our return value(s) is/are used in this caller. Don't
  515. // bother checking return values if all of them are live already.
  516. if (NumLiveRetVals == RetCount)
  517. continue;
  518. // Check all uses of the return value.
  519. for (const Use &U : TheCall->uses()) {
  520. if (ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(U.getUser())) {
  521. // This use uses a part of our return value, survey the uses of
  522. // that part and store the results for this index only.
  523. unsigned Idx = *Ext->idx_begin();
  524. if (RetValLiveness[Idx] != Live) {
  525. RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
  526. if (RetValLiveness[Idx] == Live)
  527. NumLiveRetVals++;
  528. }
  529. } else {
  530. // Used by something else than extractvalue. Survey, but assume that the
  531. // result applies to all sub-values.
  532. UseVector MaybeLiveAggregateUses;
  533. if (SurveyUse(&U, MaybeLiveAggregateUses) == Live) {
  534. NumLiveRetVals = RetCount;
  535. RetValLiveness.assign(RetCount, Live);
  536. break;
  537. } else {
  538. for (unsigned i = 0; i != RetCount; ++i) {
  539. if (RetValLiveness[i] != Live)
  540. MaybeLiveRetUses[i].append(MaybeLiveAggregateUses.begin(),
  541. MaybeLiveAggregateUses.end());
  542. }
  543. }
  544. }
  545. }
  546. }
  547. // Now we've inspected all callers, record the liveness of our return values.
  548. for (unsigned i = 0; i != RetCount; ++i)
  549. MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
  550. DEBUG(dbgs() << "DAE - Inspecting args for fn: " << F.getName() << "\n");
  551. // Now, check all of our arguments.
  552. unsigned i = 0;
  553. UseVector MaybeLiveArgUses;
  554. for (Function::const_arg_iterator AI = F.arg_begin(),
  555. E = F.arg_end(); AI != E; ++AI, ++i) {
  556. Liveness Result;
  557. if (F.getFunctionType()->isVarArg()) {
  558. // Variadic functions will already have a va_arg function expanded inside
  559. // them, making them potentially very sensitive to ABI changes resulting
  560. // from removing arguments entirely, so don't. For example AArch64 handles
  561. // register and stack HFAs very differently, and this is reflected in the
  562. // IR which has already been generated.
  563. Result = Live;
  564. } else {
  565. // See what the effect of this use is (recording any uses that cause
  566. // MaybeLive in MaybeLiveArgUses).
  567. Result = SurveyUses(AI, MaybeLiveArgUses);
  568. }
  569. // Mark the result.
  570. MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
  571. // Clear the vector again for the next iteration.
  572. MaybeLiveArgUses.clear();
  573. }
  574. }
  575. /// MarkValue - This function marks the liveness of RA depending on L. If L is
  576. /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
  577. /// such that RA will be marked live if any use in MaybeLiveUses gets marked
  578. /// live later on.
  579. void DAE::MarkValue(const RetOrArg &RA, Liveness L,
  580. const UseVector &MaybeLiveUses) {
  581. switch (L) {
  582. case Live: MarkLive(RA); break;
  583. case MaybeLive:
  584. {
  585. // Note any uses of this value, so this return value can be
  586. // marked live whenever one of the uses becomes live.
  587. for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
  588. UE = MaybeLiveUses.end(); UI != UE; ++UI)
  589. Uses.insert(std::make_pair(*UI, RA));
  590. break;
  591. }
  592. }
  593. }
  594. /// MarkLive - Mark the given Function as alive, meaning that it cannot be
  595. /// changed in any way. Additionally,
  596. /// mark any values that are used as this function's parameters or by its return
  597. /// values (according to Uses) live as well.
  598. void DAE::MarkLive(const Function &F) {
  599. DEBUG(dbgs() << "DAE - Intrinsically live fn: " << F.getName() << "\n");
  600. // Mark the function as live.
  601. LiveFunctions.insert(&F);
  602. // Mark all arguments as live.
  603. for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
  604. PropagateLiveness(CreateArg(&F, i));
  605. // Mark all return values as live.
  606. for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
  607. PropagateLiveness(CreateRet(&F, i));
  608. }
  609. /// MarkLive - Mark the given return value or argument as live. Additionally,
  610. /// mark any values that are used by this value (according to Uses) live as
  611. /// well.
  612. void DAE::MarkLive(const RetOrArg &RA) {
  613. if (LiveFunctions.count(RA.F))
  614. return; // Function was already marked Live.
  615. if (!LiveValues.insert(RA).second)
  616. return; // We were already marked Live.
  617. DEBUG(dbgs() << "DAE - Marking " << RA.getDescription() << " live\n");
  618. PropagateLiveness(RA);
  619. }
  620. /// PropagateLiveness - Given that RA is a live value, propagate it's liveness
  621. /// to any other values it uses (according to Uses).
  622. void DAE::PropagateLiveness(const RetOrArg &RA) {
  623. // We don't use upper_bound (or equal_range) here, because our recursive call
  624. // to ourselves is likely to cause the upper_bound (which is the first value
  625. // not belonging to RA) to become erased and the iterator invalidated.
  626. UseMap::iterator Begin = Uses.lower_bound(RA);
  627. UseMap::iterator E = Uses.end();
  628. UseMap::iterator I;
  629. for (I = Begin; I != E && I->first == RA; ++I)
  630. MarkLive(I->second);
  631. // Erase RA from the Uses map (from the lower bound to wherever we ended up
  632. // after the loop).
  633. Uses.erase(Begin, I);
  634. }
  635. // RemoveDeadStuffFromFunction - Remove any arguments and return values from F
  636. // that are not in LiveValues. Transform the function and all of the callees of
  637. // the function to not have these arguments and return values.
  638. //
  639. bool DAE::RemoveDeadStuffFromFunction(Function *F) {
  640. // Don't modify fully live functions
  641. if (LiveFunctions.count(F))
  642. return false;
  643. // Start by computing a new prototype for the function, which is the same as
  644. // the old function, but has fewer arguments and a different return type.
  645. FunctionType *FTy = F->getFunctionType();
  646. std::vector<Type*> Params;
  647. // Keep track of if we have a live 'returned' argument
  648. bool HasLiveReturnedArg = false;
  649. // Set up to build a new list of parameter attributes.
  650. SmallVector<AttributeSet, 8> AttributesVec;
  651. const AttributeSet &PAL = F->getAttributes();
  652. // Remember which arguments are still alive.
  653. SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
  654. // Construct the new parameter list from non-dead arguments. Also construct
  655. // a new set of parameter attributes to correspond. Skip the first parameter
  656. // attribute, since that belongs to the return value.
  657. unsigned i = 0;
  658. for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
  659. I != E; ++I, ++i) {
  660. RetOrArg Arg = CreateArg(F, i);
  661. if (LiveValues.erase(Arg)) {
  662. Params.push_back(I->getType());
  663. ArgAlive[i] = true;
  664. // Get the original parameter attributes (skipping the first one, that is
  665. // for the return value.
  666. if (PAL.hasAttributes(i + 1)) {
  667. AttrBuilder B(PAL, i + 1);
  668. if (B.contains(Attribute::Returned))
  669. HasLiveReturnedArg = true;
  670. AttributesVec.
  671. push_back(AttributeSet::get(F->getContext(), Params.size(), B));
  672. }
  673. } else {
  674. ++NumArgumentsEliminated;
  675. DEBUG(dbgs() << "DAE - Removing argument " << i << " (" << I->getName()
  676. << ") from " << F->getName() << "\n");
  677. }
  678. }
  679. // Find out the new return value.
  680. Type *RetTy = FTy->getReturnType();
  681. Type *NRetTy = nullptr;
  682. unsigned RetCount = NumRetVals(F);
  683. // -1 means unused, other numbers are the new index
  684. SmallVector<int, 5> NewRetIdxs(RetCount, -1);
  685. std::vector<Type*> RetTypes;
  686. // If there is a function with a live 'returned' argument but a dead return
  687. // value, then there are two possible actions:
  688. // 1) Eliminate the return value and take off the 'returned' attribute on the
  689. // argument.
  690. // 2) Retain the 'returned' attribute and treat the return value (but not the
  691. // entire function) as live so that it is not eliminated.
  692. //
  693. // It's not clear in the general case which option is more profitable because,
  694. // even in the absence of explicit uses of the return value, code generation
  695. // is free to use the 'returned' attribute to do things like eliding
  696. // save/restores of registers across calls. Whether or not this happens is
  697. // target and ABI-specific as well as depending on the amount of register
  698. // pressure, so there's no good way for an IR-level pass to figure this out.
  699. //
  700. // Fortunately, the only places where 'returned' is currently generated by
  701. // the FE are places where 'returned' is basically free and almost always a
  702. // performance win, so the second option can just be used always for now.
  703. //
  704. // This should be revisited if 'returned' is ever applied more liberally.
  705. if (RetTy->isVoidTy() || HasLiveReturnedArg) {
  706. NRetTy = RetTy;
  707. } else {
  708. // Look at each of the original return values individually.
  709. for (unsigned i = 0; i != RetCount; ++i) {
  710. RetOrArg Ret = CreateRet(F, i);
  711. if (LiveValues.erase(Ret)) {
  712. RetTypes.push_back(getRetComponentType(F, i));
  713. NewRetIdxs[i] = RetTypes.size() - 1;
  714. } else {
  715. ++NumRetValsEliminated;
  716. DEBUG(dbgs() << "DAE - Removing return value " << i << " from "
  717. << F->getName() << "\n");
  718. }
  719. }
  720. if (RetTypes.size() > 1) {
  721. // More than one return type? Reduce it down to size.
  722. if (StructType *STy = dyn_cast<StructType>(RetTy)) {
  723. // Make the new struct packed if we used to return a packed struct
  724. // already.
  725. NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked());
  726. } else {
  727. assert(isa<ArrayType>(RetTy) && "unexpected multi-value return");
  728. NRetTy = ArrayType::get(RetTypes[0], RetTypes.size());
  729. }
  730. } else if (RetTypes.size() == 1)
  731. // One return type? Just a simple value then, but only if we didn't use to
  732. // return a struct with that simple value before.
  733. NRetTy = RetTypes.front();
  734. else if (RetTypes.size() == 0)
  735. // No return types? Make it void, but only if we didn't use to return {}.
  736. NRetTy = Type::getVoidTy(F->getContext());
  737. }
  738. assert(NRetTy && "No new return type found?");
  739. // The existing function return attributes.
  740. AttributeSet RAttrs = PAL.getRetAttributes();
  741. // Remove any incompatible attributes, but only if we removed all return
  742. // values. Otherwise, ensure that we don't have any conflicting attributes
  743. // here. Currently, this should not be possible, but special handling might be
  744. // required when new return value attributes are added.
  745. if (NRetTy->isVoidTy())
  746. RAttrs = RAttrs.removeAttributes(NRetTy->getContext(),
  747. AttributeSet::ReturnIndex,
  748. AttributeFuncs::typeIncompatible(NRetTy));
  749. else
  750. assert(!AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
  751. overlaps(AttributeFuncs::typeIncompatible(NRetTy)) &&
  752. "Return attributes no longer compatible?");
  753. if (RAttrs.hasAttributes(AttributeSet::ReturnIndex))
  754. AttributesVec.push_back(AttributeSet::get(NRetTy->getContext(), RAttrs));
  755. if (PAL.hasAttributes(AttributeSet::FunctionIndex))
  756. AttributesVec.push_back(AttributeSet::get(F->getContext(),
  757. PAL.getFnAttributes()));
  758. // Reconstruct the AttributesList based on the vector we constructed.
  759. AttributeSet NewPAL = AttributeSet::get(F->getContext(), AttributesVec);
  760. // Create the new function type based on the recomputed parameters.
  761. FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
  762. // No change?
  763. if (NFTy == FTy)
  764. return false;
  765. // Create the new function body and insert it into the module...
  766. Function *NF = Function::Create(NFTy, F->getLinkage());
  767. NF->copyAttributesFrom(F);
  768. NF->setAttributes(NewPAL);
  769. // Insert the new function before the old function, so we won't be processing
  770. // it again.
  771. F->getParent()->getFunctionList().insert(F, NF);
  772. NF->takeName(F);
  773. // Loop over all of the callers of the function, transforming the call sites
  774. // to pass in a smaller number of arguments into the new function.
  775. //
  776. std::vector<Value*> Args;
  777. while (!F->use_empty()) {
  778. CallSite CS(F->user_back());
  779. Instruction *Call = CS.getInstruction();
  780. AttributesVec.clear();
  781. const AttributeSet &CallPAL = CS.getAttributes();
  782. // The call return attributes.
  783. AttributeSet RAttrs = CallPAL.getRetAttributes();
  784. // Adjust in case the function was changed to return void.
  785. RAttrs = RAttrs.removeAttributes(NRetTy->getContext(),
  786. AttributeSet::ReturnIndex,
  787. AttributeFuncs::typeIncompatible(NF->getReturnType()));
  788. if (RAttrs.hasAttributes(AttributeSet::ReturnIndex))
  789. AttributesVec.push_back(AttributeSet::get(NF->getContext(), RAttrs));
  790. // Declare these outside of the loops, so we can reuse them for the second
  791. // loop, which loops the varargs.
  792. CallSite::arg_iterator I = CS.arg_begin();
  793. unsigned i = 0;
  794. // Loop over those operands, corresponding to the normal arguments to the
  795. // original function, and add those that are still alive.
  796. for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
  797. if (ArgAlive[i]) {
  798. Args.push_back(*I);
  799. // Get original parameter attributes, but skip return attributes.
  800. if (CallPAL.hasAttributes(i + 1)) {
  801. AttrBuilder B(CallPAL, i + 1);
  802. // If the return type has changed, then get rid of 'returned' on the
  803. // call site. The alternative is to make all 'returned' attributes on
  804. // call sites keep the return value alive just like 'returned'
  805. // attributes on function declaration but it's less clearly a win
  806. // and this is not an expected case anyway
  807. if (NRetTy != RetTy && B.contains(Attribute::Returned))
  808. B.removeAttribute(Attribute::Returned);
  809. AttributesVec.
  810. push_back(AttributeSet::get(F->getContext(), Args.size(), B));
  811. }
  812. }
  813. // Push any varargs arguments on the list. Don't forget their attributes.
  814. for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
  815. Args.push_back(*I);
  816. if (CallPAL.hasAttributes(i + 1)) {
  817. AttrBuilder B(CallPAL, i + 1);
  818. AttributesVec.
  819. push_back(AttributeSet::get(F->getContext(), Args.size(), B));
  820. }
  821. }
  822. if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
  823. AttributesVec.push_back(AttributeSet::get(Call->getContext(),
  824. CallPAL.getFnAttributes()));
  825. // Reconstruct the AttributesList based on the vector we constructed.
  826. AttributeSet NewCallPAL = AttributeSet::get(F->getContext(), AttributesVec);
  827. Instruction *New;
  828. if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
  829. New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
  830. Args, "", Call);
  831. cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
  832. cast<InvokeInst>(New)->setAttributes(NewCallPAL);
  833. } else {
  834. New = CallInst::Create(NF, Args, "", Call);
  835. cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
  836. cast<CallInst>(New)->setAttributes(NewCallPAL);
  837. if (cast<CallInst>(Call)->isTailCall())
  838. cast<CallInst>(New)->setTailCall();
  839. }
  840. New->setDebugLoc(Call->getDebugLoc());
  841. Args.clear();
  842. if (!Call->use_empty()) {
  843. if (New->getType() == Call->getType()) {
  844. // Return type not changed? Just replace users then.
  845. Call->replaceAllUsesWith(New);
  846. New->takeName(Call);
  847. } else if (New->getType()->isVoidTy()) {
  848. // Our return value has uses, but they will get removed later on.
  849. // Replace by null for now.
  850. if (!Call->getType()->isX86_MMXTy())
  851. Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
  852. } else {
  853. assert((RetTy->isStructTy() || RetTy->isArrayTy()) &&
  854. "Return type changed, but not into a void. The old return type"
  855. " must have been a struct or an array!");
  856. Instruction *InsertPt = Call;
  857. if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
  858. BasicBlock::iterator IP = II->getNormalDest()->begin();
  859. while (isa<PHINode>(IP)) ++IP;
  860. InsertPt = IP;
  861. }
  862. // We used to return a struct or array. Instead of doing smart stuff
  863. // with all the uses, we will just rebuild it using extract/insertvalue
  864. // chaining and let instcombine clean that up.
  865. //
  866. // Start out building up our return value from undef
  867. Value *RetVal = UndefValue::get(RetTy);
  868. for (unsigned i = 0; i != RetCount; ++i)
  869. if (NewRetIdxs[i] != -1) {
  870. Value *V;
  871. if (RetTypes.size() > 1)
  872. // We are still returning a struct, so extract the value from our
  873. // return value
  874. V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret",
  875. InsertPt);
  876. else
  877. // We are now returning a single element, so just insert that
  878. V = New;
  879. // Insert the value at the old position
  880. RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt);
  881. }
  882. // Now, replace all uses of the old call instruction with the return
  883. // struct we built
  884. Call->replaceAllUsesWith(RetVal);
  885. New->takeName(Call);
  886. }
  887. }
  888. // Finally, remove the old call from the program, reducing the use-count of
  889. // F.
  890. Call->eraseFromParent();
  891. }
  892. // Since we have now created the new function, splice the body of the old
  893. // function right into the new function, leaving the old rotting hulk of the
  894. // function empty.
  895. NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
  896. // Loop over the argument list, transferring uses of the old arguments over to
  897. // the new arguments, also transferring over the names as well.
  898. i = 0;
  899. for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
  900. I2 = NF->arg_begin(); I != E; ++I, ++i)
  901. if (ArgAlive[i]) {
  902. // If this is a live argument, move the name and users over to the new
  903. // version.
  904. I->replaceAllUsesWith(I2);
  905. I2->takeName(I);
  906. ++I2;
  907. } else {
  908. // If this argument is dead, replace any uses of it with null constants
  909. // (these are guaranteed to become unused later on).
  910. if (!I->getType()->isX86_MMXTy())
  911. I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
  912. }
  913. // If we change the return value of the function we must rewrite any return
  914. // instructions. Check this now.
  915. if (F->getReturnType() != NF->getReturnType())
  916. for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
  917. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
  918. Value *RetVal;
  919. if (NFTy->getReturnType()->isVoidTy()) {
  920. RetVal = nullptr;
  921. } else {
  922. assert(RetTy->isStructTy() || RetTy->isArrayTy());
  923. // The original return value was a struct or array, insert
  924. // extractvalue/insertvalue chains to extract only the values we need
  925. // to return and insert them into our new result.
  926. // This does generate messy code, but we'll let it to instcombine to
  927. // clean that up.
  928. Value *OldRet = RI->getOperand(0);
  929. // Start out building up our return value from undef
  930. RetVal = UndefValue::get(NRetTy);
  931. for (unsigned i = 0; i != RetCount; ++i)
  932. if (NewRetIdxs[i] != -1) {
  933. ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
  934. "oldret", RI);
  935. if (RetTypes.size() > 1) {
  936. // We're still returning a struct, so reinsert the value into
  937. // our new return value at the new index
  938. RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
  939. "newret", RI);
  940. } else {
  941. // We are now only returning a simple value, so just return the
  942. // extracted value.
  943. RetVal = EV;
  944. }
  945. }
  946. }
  947. // Replace the return instruction with one returning the new return
  948. // value (possibly 0 if we became void).
  949. ReturnInst::Create(F->getContext(), RetVal, RI);
  950. BB->getInstList().erase(RI);
  951. }
  952. // Patch the pointer to LLVM function in debug info descriptor.
  953. auto DI = FunctionDIs.find(F);
  954. if (DI != FunctionDIs.end())
  955. DI->second->replaceFunction(NF);
  956. // Now that the old function is dead, delete it.
  957. F->eraseFromParent();
  958. return true;
  959. }
  960. bool DAE::runOnModule(Module &M) {
  961. bool Changed = false;
  962. // Collect debug info descriptors for functions.
  963. FunctionDIs = makeSubprogramMap(M);
  964. // First pass: Do a simple check to see if any functions can have their "..."
  965. // removed. We can do this if they never call va_start. This loop cannot be
  966. // fused with the next loop, because deleting a function invalidates
  967. // information computed while surveying other functions.
  968. DEBUG(dbgs() << "DAE - Deleting dead varargs\n");
  969. for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
  970. Function &F = *I++;
  971. if (F.getFunctionType()->isVarArg())
  972. Changed |= DeleteDeadVarargs(F);
  973. }
  974. // Second phase:loop through the module, determining which arguments are live.
  975. // We assume all arguments are dead unless proven otherwise (allowing us to
  976. // determine that dead arguments passed into recursive functions are dead).
  977. //
  978. DEBUG(dbgs() << "DAE - Determining liveness\n");
  979. for (auto &F : M)
  980. SurveyFunction(F);
  981. // Now, remove all dead arguments and return values from each function in
  982. // turn.
  983. for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
  984. // Increment now, because the function will probably get removed (ie.
  985. // replaced by a new one).
  986. Function *F = I++;
  987. Changed |= RemoveDeadStuffFromFunction(F);
  988. }
  989. // Finally, look for any unused parameters in functions with non-local
  990. // linkage and replace the passed in parameters with undef.
  991. for (auto &F : M)
  992. Changed |= RemoveDeadArgumentsFromCallers(F);
  993. return Changed;
  994. }