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