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