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