56#define DEBUG_TYPE "deadargelim"
58STATISTIC(NumArgumentsEliminated,
"Number of unread args removed");
59STATISTIC(NumRetValsEliminated,
"Number of unused return values removed");
61 "Number of unread args replaced with poison");
74 DAE() : ModulePass(ID) {}
76 bool runOnModule(
Module &M)
override {
79 DeadArgumentEliminationPass DAEP;
81 PreservedAnalyses PA = DAEP.
run(M, DummyMAM);
90INITIALIZE_PASS(DAE,
"deadargelim",
"Dead Argument Elimination",
false,
false)
98bool DeadArgumentEliminationPass::deleteDeadVarargs(
Function &
F) {
99 assert(
F.getFunctionType()->isVarArg() &&
"Function isn't varargs!");
100 if (
F.isDeclaration() || !
F.hasLocalLinkage())
104 if (
F.hasAddressTaken())
110 if (!
F.canChangeSignature()) {
116 for (BasicBlock &BB :
F) {
117 for (Instruction &
I : BB) {
124 if (
II->getIntrinsicID() == Intrinsic::vastart)
135 FunctionType *FTy =
F.getFunctionType();
137 std::vector<Type *> Params(FTy->param_begin(), FTy->param_end());
139 unsigned NumArgs = Params.size();
145 F.getParent()->getFunctionList().insert(
F.getIterator(), NF);
151 std::vector<Value *>
Args;
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);
174 CallBase *NewCB =
nullptr;
211 I->replaceAllUsesWith(&*I2);
217 F.getAllMetadata(MDs);
218 for (
auto [KindID, Node] : MDs)
222 F.replaceAllUsesWith(NF);
227 eraseReplacedFunction(
F, *NF);
233bool DeadArgumentEliminationPass::removeDeadArgumentsFromCallers(
Function &
F) {
245 if (!
F.hasExactDefinition())
253 !
F.getFunctionType()->isVarArg())
259 if (!
F.canChangeSignature())
265 SmallVector<unsigned, 8> UnusedArgs;
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()) {
278 F.removeParamAttrs(Arg.getArgNo(), UBImplyingAttributes);
282 if (UnusedArgs.
empty())
284 ChangedFunctions.insert(&
F);
286 for (Use &U :
F.uses()) {
294 for (
unsigned ArgNo : UnusedArgs) {
299 ++NumArgumentsReplacedWithPoison;
311 Type *RetTy =
F->getReturnType();
315 return STy->getNumElements();
317 return ATy->getNumElements();
325 Type *RetTy =
F->getReturnType();
329 return STy->getElementType(Idx);
331 return ATy->getElementType();
338DeadArgumentEliminationPass::markIfNotLive(RetOrArg
Use,
339 UseVector &MaybeLiveUses) {
346 MaybeLiveUses.push_back(Use);
358DeadArgumentEliminationPass::surveyUse(
const Use *U, UseVector &MaybeLiveUses,
359 unsigned RetValNum) {
360 const User *
V =
U->getUser();
366 const Function *
F = RI->getParent()->getParent();
367 if (RetValNum != -1U) {
370 return markIfNotLive(Use, MaybeLiveUses);
380 markIfNotLive(Use, MaybeLiveUses);
393 RetValNum = *
IV->idx_begin();
399 for (
const Use &UU :
IV->uses()) {
400 Result = surveyUse(&UU, MaybeLiveUses, RetValNum);
422 if (ArgNo >=
F->getFunctionType()->getNumParams())
427 "Argument is not where we expected it");
432 return markIfNotLive(Use, MaybeLiveUses);
446DeadArgumentEliminationPass::surveyUses(
const Value *
V,
447 UseVector &MaybeLiveUses) {
451 for (
const Use &U :
V->uses()) {
452 Result = surveyUse(&U, MaybeLiveUses);
465void DeadArgumentEliminationPass::surveyFunction(
const Function &
F) {
467 if (!
F.hasLocalLinkage()) {
474 if (
F.getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
475 F.getAttributes().hasAttrSomewhere(Attribute::Preallocated)) {
483 if (!
F.canChangeSignature()) {
489 if (!
F.isDefinitionExact()) {
499 RetVals RetValLiveness(RetCount,
MaybeLive);
506 RetUses MaybeLiveRetUses(RetCount);
508 for (
const BasicBlock &BB :
F) {
509 if (BB.getTerminatingMustTailCall()) {
511 <<
" has musttail calls\n");
512 if (markFnOrRetTyFrozenOnMusttail(
F))
518 dbgs() <<
"DeadArgumentEliminationPass - Inspecting callers for fn: "
519 <<
F.getName() <<
"\n");
522 unsigned NumLiveRetVals = 0;
525 for (
const Use &U :
F.uses()) {
537 <<
" has musttail callers\n");
538 if (markFnOrRetTyFrozenOnMusttail(
F))
546 if (NumLiveRetVals == RetCount)
550 for (
const Use &UU : CB->
uses()) {
554 unsigned Idx = *Ext->idx_begin();
555 if (RetValLiveness[Idx] !=
Live) {
556 RetValLiveness[
Idx] = surveyUses(Ext, MaybeLiveRetUses[Idx]);
557 if (RetValLiveness[Idx] ==
Live)
564 if (surveyUse(&UU, MaybeLiveAggregateUses) ==
Live) {
565 NumLiveRetVals = RetCount;
566 RetValLiveness.assign(RetCount,
Live);
570 for (
unsigned Ri = 0; Ri != RetCount; ++Ri) {
571 if (RetValLiveness[Ri] !=
Live)
572 MaybeLiveRetUses[Ri].append(MaybeLiveAggregateUses.begin(),
573 MaybeLiveAggregateUses.end());
580 for (
unsigned Ri = 0; Ri != RetCount; ++Ri)
581 markValue(
createRet(&
F, Ri), RetValLiveness[Ri], MaybeLiveRetUses[Ri]);
583 LLVM_DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Inspecting args for fn: "
584 <<
F.getName() <<
"\n");
590 AI !=
E; ++AI, ++ArgI) {
592 if (
F.getFunctionType()->isVarArg()) {
602 Result = surveyUses(&*AI, MaybeLiveArgUses);
606 markValue(
createArg(&
F, ArgI), Result, MaybeLiveArgUses);
608 MaybeLiveArgUses.clear();
615void DeadArgumentEliminationPass::markValue(
const RetOrArg &
RA, Liveness L,
616 const UseVector &MaybeLiveUses) {
622 assert(!isLive(
RA) &&
"Use is already live!");
623 for (
const auto &MaybeLiveUse : MaybeLiveUses) {
624 if (isLive(MaybeLiveUse)) {
631 Uses.emplace(MaybeLiveUse,
RA);
641bool DeadArgumentEliminationPass::markFnOrRetTyFrozenOnMusttail(
656void DeadArgumentEliminationPass::markFrozen(
const Function &
F) {
658 <<
F.getName() <<
"\n");
662 for (
unsigned ArgI = 0,
E =
F.arg_size(); ArgI !=
E; ++ArgI)
669void DeadArgumentEliminationPass::markRetTyFrozen(
const Function &
F) {
670 LLVM_DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - frozen return type fn: "
671 <<
F.getName() <<
"\n");
677void DeadArgumentEliminationPass::markLive(
const RetOrArg &
RA) {
684 <<
RA.getDescription() <<
" live\n");
685 propagateLiveness(
RA);
688bool DeadArgumentEliminationPass::isLive(
const RetOrArg &
RA) {
694void DeadArgumentEliminationPass::propagateLiveness(
const RetOrArg &
RA) {
698 UseMap::iterator Begin =
Uses.lower_bound(
RA);
699 UseMap::iterator
E =
Uses.end();
701 for (
I = Begin;
I !=
E &&
I->first ==
RA; ++
I)
706 Uses.erase(Begin,
I);
712bool DeadArgumentEliminationPass::removeDeadStuffFromFunction(
Function *
F) {
719 FunctionType *FTy =
F->getFunctionType();
720 std::vector<Type *> Params;
723 bool HasLiveReturnedArg =
false;
727 const AttributeList &PAL =
F->getAttributes();
728 OptimizationRemarkEmitter ORE(
F);
740 Params.push_back(
I->getType());
741 ArgAlive[ArgI] =
true;
742 ArgAttrVec.
push_back(PAL.getParamAttrs(ArgI));
743 HasLiveReturnedArg |= PAL.hasParamAttr(ArgI, Attribute::Returned);
745 ++NumArgumentsEliminated;
748 return OptimizationRemark(
DEBUG_TYPE,
"ArgumentRemoved",
F)
749 <<
"eliminating argument " <<
ore::NV(
"ArgName",
I->getName())
750 <<
"(" <<
ore::NV(
"ArgIndex", ArgI) <<
")";
752 LLVM_DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Removing argument "
753 << ArgI <<
" (" <<
I->getName() <<
") from "
754 <<
F->getName() <<
"\n");
759 Type *RetTy = FTy->getReturnType();
760 Type *NRetTy =
nullptr;
765 std::vector<Type *> RetTypes;
786 if (RetTy->
isVoidTy() || HasLiveReturnedArg ||
791 for (
unsigned Ri = 0; Ri != RetCount; ++Ri) {
795 NewRetIdxs[Ri] = RetTypes.size() - 1;
797 ++NumRetValsEliminated;
800 return OptimizationRemark(
DEBUG_TYPE,
"ReturnValueRemoved",
F)
801 <<
"removing return value " << std::to_string(Ri);
804 dbgs() <<
"DeadArgumentEliminationPass - Removing return value "
805 << Ri <<
" from " <<
F->getName() <<
"\n");
808 if (RetTypes.size() > 1) {
813 NRetTy =
StructType::get(STy->getContext(), RetTypes, STy->isPacked());
818 }
else if (RetTypes.size() == 1)
821 NRetTy = RetTypes.front();
822 else if (RetTypes.empty())
827 assert(NRetTy &&
"No new return type found?");
830 AttrBuilder RAttrs(
F->getContext(), PAL.getRetAttrs());
837 RAttrs.remove(AttributeFuncs::typeIncompatible(NRetTy, PAL.getRetAttrs()));
840 AttributeFuncs::typeIncompatible(NRetTy, PAL.getRetAttrs())) &&
841 "Return attributes no longer compatible?");
846 AttributeSet FnAttrs =
847 PAL.getFnAttrs().removeAttribute(
F->getContext(), Attribute::AllocSize);
851 AttributeList NewPAL =
852 AttributeList::get(
F->getContext(), FnAttrs, RetAttrs, ArgAttrVec);
868 F->getParent()->getFunctionList().insert(
F->getIterator(), NF);
873 std::vector<Value *>
Args;
874 while (!
F->use_empty()) {
883 AttrBuilder RAttrs(
F->getContext(), CallPAL.getRetAttrs());
885 AttributeFuncs::typeIncompatible(NRetTy, CallPAL.getRetAttrs()));
894 for (
unsigned E = FTy->getNumParams(); Pi !=
E; ++
I, ++Pi)
898 AttributeSet
Attrs = CallPAL.getParamAttrs(Pi);
899 if (NRetTy != RetTy &&
Attrs.hasAttribute(Attribute::Returned)) {
906 F->getContext(), AttrBuilder(
F->getContext(), Attrs)
907 .removeAttribute(Attribute::Returned)));
917 ArgAttrVec.
push_back(CallPAL.getParamAttrs(Pi));
925 AttributeSet FnAttrs = CallPAL.getFnAttrs().removeAttribute(
926 F->getContext(), Attribute::AllocSize);
928 AttributeList NewCallPAL =
929 AttributeList::get(
F->getContext(), FnAttrs, RetAttrs, ArgAttrVec);
934 CallBase *NewCB =
nullptr;
960 "Return type changed, but not into a void. The old return type"
961 " must have been a struct or an array!");
975 for (
unsigned Ri = 0; Ri != RetCount; ++Ri)
976 if (NewRetIdxs[Ri] != -1) {
979 if (RetTypes.size() > 1)
982 V = IRB.CreateExtractValue(NewCB, NewRetIdxs[Ri],
"newret");
987 RetVal = IRB.CreateInsertValue(RetVal,
V, Ri,
"oldret");
1011 I !=
E; ++
I, ++ArgI)
1012 if (ArgAlive[ArgI]) {
1015 I->replaceAllUsesWith(&*I2);
1027 for (BasicBlock &BB : *NF)
1030 Value *RetVal =
nullptr;
1032 if (!NFTy->getReturnType()->isVoidTy()) {
1039 Value *OldRet = RI->getOperand(0);
1042 for (
unsigned RetI = 0; RetI != RetCount; ++RetI)
1043 if (NewRetIdxs[RetI] != -1) {
1044 Value *EV = IRB.CreateExtractValue(OldRet, RetI,
"oldret");
1046 if (RetTypes.size() > 1) {
1050 RetVal = IRB.CreateInsertValue(RetVal, EV, NewRetIdxs[RetI],
1063 NewRet->setDebugLoc(RI->getDebugLoc());
1064 RI->eraseFromParent();
1069 F->getAllMetadata(MDs);
1070 for (
auto [KindID, Node] : MDs)
1071 NF->addMetadata(KindID, *Node);
1077 if (NFTy != FTy && NF->getSubprogram()) {
1078 DISubprogram *
SP = NF->getSubprogram();
1079 auto Temp =
SP->getType()->cloneWithCC(llvm::dwarf::DW_CC_nocall);
1084 eraseReplacedFunction(*
F, *NF);
1089void DeadArgumentEliminationPass::eraseReplacedFunction(
Function &
F,
1091 ChangedFunctions.remove(&
F);
1094 F.eraseFromParent();
1106 LLVM_DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Deleting dead varargs\n");
1108 if (
F.getFunctionType()->isVarArg())
1114 LLVM_DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Determining liveness\n");
1122 Changed |= removeDeadStuffFromFunction(&
F);
1127 Changed |= removeDeadArgumentsFromCallers(
F);
1133 ChangedFunctions.clear();
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.
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.
uint64_t IntrinsicInst * II
ModuleAnalysisManager MAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
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)
static const uint32_t IV[8]
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
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.
SmallVector< RetOrArg, 5 > UseVector
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)
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Type * getReturnType() const
Returns the type of the ret val.
const Argument * const_arg_iterator
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
LLVM_ABI void setComdat(Comdat *C)
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.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
A Module instance is used to store all the information related to an LLVM module.
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.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
bool areAllPreserved() const
Test whether all analyses are preserved (and none are abandoned).
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
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.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isArrayTy() const
True if this is an instance of ArrayType.
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
bool isStructTy() const
True if this is an instance of StructType.
bool isVoidTy() const
Return true if this is 'void'.
A Use represents the edge between a Value definition and its users.
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool isUsedByMetadata() const
Return true if there is metadata referencing this value.
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
const ParentTy * getParent() const
self_iterator getIterator()
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...
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
@ BasicBlock
Various leaf nodes.
@ User
could "use" a pointer
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< UseNode * > Use
friend class Instruction
Iterator for Instructions in a `BasicBlock.
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.
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...
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
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.
Struct that represents (part of) either a return value or a function argument.