DeadArgumentElimination.cpp 43 KB

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