DeadArgumentElimination.cpp 43 KB

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