55 #define DEBUG_TYPE "deadargelim" 57 STATISTIC(NumArgumentsEliminated,
"Number of unread args removed");
58 STATISTIC(NumRetValsEliminated ,
"Number of unused return values removed");
60 "Number of unread args replaced with undef");
77 bool runOnModule(
Module &M)
override {
86 virtual bool ShouldHackArguments()
const {
return false; }
93 INITIALIZE_PASS(DAE,
"deadargelim",
"Dead Argument Elimination",
false,
false)
100 struct DAH :
public DAE {
105 bool ShouldHackArguments()
const override {
return true; }
113 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)",
124 bool DeadArgumentEliminationPass::DeleteDeadVarargs(
Function &Fn) {
149 if (II->getIntrinsicID() == Intrinsic::vastart)
165 unsigned NumArgs = Params.size();
171 Fn.getParent()->getFunctionList().insert(Fn.getIterator(), NF);
177 std::vector<Value *>
Args;
191 for (
unsigned ArgNo = 0; ArgNo < NumArgs; ++ArgNo)
201 if (
InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
203 Args, OpBundles,
"", Call);
207 ->setTailCallKind(cast<CallInst>(Call)->getTailCallKind());
214 NewCS->setProfWeight(W);
221 NewCS->takeName(Call);
239 I->replaceAllUsesWith(&*I2);
245 Fn.getAllMetadata(MDs);
255 Fn.eraseFromParent();
262 bool DeadArgumentEliminationPass::RemoveDeadArgumentsFromCallers(
Function &Fn) {
297 if (UnusedArgs.
empty())
300 bool Changed =
false;
304 if (!CS || !CS.isCallee(&U))
308 for (
unsigned I = 0,
E = UnusedArgs.
size();
I !=
E; ++
I) {
309 unsigned ArgNo = UnusedArgs[
I];
313 ++NumArgumentsReplacedWithUndef;
328 else if (
StructType *STy = dyn_cast<StructType>(RetTy))
329 return STy->getNumElements();
330 else if (
ArrayType *ATy = dyn_cast<ArrayType>(RetTy))
331 return ATy->getNumElements();
343 if (
StructType *STy = dyn_cast<StructType>(RetTy))
344 return STy->getElementType(Idx);
345 else if (
ArrayType *ATy = dyn_cast<ArrayType>(RetTy))
346 return ATy->getElementType();
355 DeadArgumentEliminationPass::MarkIfNotLive(RetOrArg
Use,
356 UseVector &MaybeLiveUses) {
358 if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
363 MaybeLiveUses.push_back(Use);
375 DeadArgumentEliminationPass::SurveyUse(
const Use *U, UseVector &MaybeLiveUses,
376 unsigned RetValNum) {
377 const User *V = U->getUser();
378 if (
const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
383 const Function *
F = RI->getParent()->getParent();
384 if (RetValNum != -1U) {
385 RetOrArg Use = CreateRet(F, RetValNum);
387 return MarkIfNotLive(Use, MaybeLiveUses);
390 for (
unsigned i = 0; i <
NumRetVals(F); ++i) {
391 RetOrArg Use = CreateRet(F, i);
396 MarkIfNotLive(Use, MaybeLiveUses);
409 RetValNum = *IV->idx_begin();
414 Liveness
Result = MaybeLive;
415 for (
const Use &UU : IV->uses()) {
416 Result = SurveyUse(&UU, MaybeLiveUses, RetValNum);
424 const Function *
F = CS.getCalledFunction();
429 if (CS.isBundleOperand(U))
436 unsigned ArgNo = CS.getArgumentNo(U);
442 assert(CS.getArgument(ArgNo)
443 == CS->getOperand(U->getOperandNo())
444 &&
"Argument is not where we expected it");
448 RetOrArg Use = CreateArg(F, ArgNo);
449 return MarkIfNotLive(Use, MaybeLiveUses);
463 DeadArgumentEliminationPass::SurveyUses(
const Value *V,
464 UseVector &MaybeLiveUses) {
466 Liveness
Result = MaybeLive;
468 for (
const Use &U : V->
uses()) {
469 Result = SurveyUse(&U, MaybeLiveUses);
483 void DeadArgumentEliminationPass::SurveyFunction(
const Function &
F) {
504 RetVals RetValLiveness(RetCount, MaybeLive);
511 RetUses MaybeLiveRetUses(RetCount);
513 bool HasMustTailCalls =
false;
516 if (
const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
517 if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
527 if (BB->getTerminatingMustTailCall() !=
nullptr)
528 HasMustTailCalls =
true;
531 if (HasMustTailCalls) {
533 <<
" has musttail calls\n");
542 dbgs() <<
"DeadArgumentEliminationPass - Inspecting callers for fn: " 546 unsigned NumLiveRetVals = 0;
548 bool HasMustTailCallers =
false;
551 for (
const Use &U : F.
uses()) {
555 if (!CS || !CS.isCallee(&U)) {
562 if (CS.isMustTailCall())
563 HasMustTailCallers =
true;
576 if (NumLiveRetVals == RetCount)
580 for (
const Use &U : TheCall->
uses()) {
584 unsigned Idx = *
Ext->idx_begin();
585 if (RetValLiveness[Idx] != Live) {
586 RetValLiveness[Idx] = SurveyUses(
Ext, MaybeLiveRetUses[Idx]);
587 if (RetValLiveness[Idx] == Live)
593 UseVector MaybeLiveAggregateUses;
594 if (SurveyUse(&U, MaybeLiveAggregateUses) == Live) {
595 NumLiveRetVals = RetCount;
596 RetValLiveness.assign(RetCount, Live);
599 for (
unsigned i = 0; i != RetCount; ++i) {
600 if (RetValLiveness[i] != Live)
601 MaybeLiveRetUses[i].append(MaybeLiveAggregateUses.begin(),
602 MaybeLiveAggregateUses.end());
609 if (HasMustTailCallers) {
611 <<
" has musttail callers\n");
615 for (
unsigned i = 0; i != RetCount; ++i)
616 MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
618 LLVM_DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Inspecting args for fn: " 623 UseVector MaybeLiveArgUses;
644 Result = SurveyUses(&*AI, MaybeLiveArgUses);
648 MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
650 MaybeLiveArgUses.clear();
658 void DeadArgumentEliminationPass::MarkValue(
const RetOrArg &
RA, Liveness L,
659 const UseVector &MaybeLiveUses) {
667 for (
const auto &MaybeLiveUse : MaybeLiveUses)
668 Uses.insert(std::make_pair(MaybeLiveUse, RA));
677 void DeadArgumentEliminationPass::MarkLive(
const Function &F) {
678 LLVM_DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Intrinsically live fn: " 681 LiveFunctions.insert(&F);
683 for (
unsigned i = 0, e = F.
arg_size(); i != e; ++i)
684 PropagateLiveness(CreateArg(&F, i));
686 for (
unsigned i = 0, e =
NumRetVals(&F); i != e; ++i)
687 PropagateLiveness(CreateRet(&F, i));
693 void DeadArgumentEliminationPass::MarkLive(
const RetOrArg &RA) {
694 if (LiveFunctions.count(RA.F))
697 if (!LiveValues.insert(RA).second)
701 << RA.getDescription() <<
" live\n");
702 PropagateLiveness(RA);
707 void DeadArgumentEliminationPass::PropagateLiveness(
const RetOrArg &RA) {
711 UseMap::iterator Begin = Uses.lower_bound(RA);
712 UseMap::iterator
E = Uses.end();
714 for (I = Begin; I != E && I->first ==
RA; ++
I)
719 Uses.erase(Begin, I);
726 bool DeadArgumentEliminationPass::RemoveDeadStuffFromFunction(
Function *F) {
728 if (LiveFunctions.count(F))
734 std::vector<Type*> Params;
737 bool HasLiveReturnedArg =
false;
751 RetOrArg
Arg = CreateArg(F, i);
752 if (LiveValues.erase(Arg)) {
753 Params.push_back(
I->getType());
758 ++NumArgumentsEliminated;
759 LLVM_DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Removing argument " 760 << i <<
" (" <<
I->getName() <<
") from " 767 Type *NRetTy =
nullptr;
772 std::vector<Type*> RetTypes;
793 if (RetTy->isVoidTy() || HasLiveReturnedArg) {
797 for (
unsigned i = 0; i != RetCount; ++i) {
798 RetOrArg
Ret = CreateRet(F, i);
799 if (LiveValues.erase(Ret)) {
801 NewRetIdxs[i] = RetTypes.
size() - 1;
803 ++NumRetValsEliminated;
805 dbgs() <<
"DeadArgumentEliminationPass - Removing return value " 806 << i <<
" from " << F->
getName() <<
"\n");
809 if (RetTypes.size() > 1) {
811 if (
StructType *STy = dyn_cast<StructType>(RetTy)) {
814 NRetTy =
StructType::get(STy->getContext(), RetTypes, STy->isPacked());
816 assert(isa<ArrayType>(RetTy) &&
"unexpected multi-value return");
819 }
else if (RetTypes.size() == 1)
822 NRetTy = RetTypes.front();
823 else if (RetTypes.empty())
828 assert(NRetTy &&
"No new return type found?");
841 "Return attributes no longer compatible?");
873 std::vector<Value*>
Args;
898 if (NRetTy != RetTy && Attrs.
hasAttribute(Attribute::Returned)) {
928 F->
getContext(), FnAttrs, RetAttrs, ArgAttrVec);
931 CS.getOperandBundlesAsDefs(OpBundles);
934 if (
InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
936 Args, OpBundles,
"", Call->getParent());
940 ->setTailCallKind(cast<CallInst>(Call)->getTailCallKind());
944 NewCS->setDebugLoc(Call->getDebugLoc());
946 if (Call->extractProfTotalWeight(W))
947 NewCS->setProfWeight(W);
952 if (!Call->use_empty()) {
953 if (New->
getType() == Call->getType()) {
960 if (!Call->getType()->isX86_MMXTy())
963 assert((RetTy->isStructTy() || RetTy->isArrayTy()) &&
964 "Return type changed, but not into a void. The old return type" 965 " must have been a struct or an array!");
967 if (
InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
978 for (
unsigned i = 0; i != RetCount; ++i)
979 if (NewRetIdxs[i] != -1) {
981 if (RetTypes.size() > 1)
994 Call->replaceAllUsesWith(RetVal);
1001 Call->eraseFromParent();
1017 I->replaceAllUsesWith(&*I2);
1023 if (!
I->getType()->isX86_MMXTy())
1031 if (
ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
1034 if (NFTy->getReturnType()->isVoidTy()) {
1037 assert(RetTy->isStructTy() || RetTy->isArrayTy());
1043 Value *OldRet = RI->getOperand(0);
1046 for (
unsigned i = 0; i != RetCount; ++i)
1047 if (NewRetIdxs[i] != -1) {
1050 if (RetTypes.size() > 1) {
1066 BB.getInstList().erase(RI);
1073 NF->addMetadata(MD.first, *MD.second);
1083 bool Changed =
false;
1089 LLVM_DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Deleting dead varargs\n");
1093 Changed |= DeleteDeadVarargs(F);
1100 LLVM_DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Determining liveness\n");
1110 Changed |= RemoveDeadStuffFromFunction(F);
1116 Changed |= RemoveDeadArgumentsFromCallers(F);
Return a value (possibly void), from a function.
User::op_iterator arg_iterator
The type of iterator to use when looping over actual arguments at this call site. ...
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
iterator_range< use_iterator > uses()
bool hasLocalLinkage() const
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents an incoming formal argument to a Function.
Eliminate dead arguments (and return values) from functions.
CallingConv::ID getCallingConv() const
Get the calling convention of the call.
Compute iterated dominance frontiers using a linear time algorithm.
A Module instance is used to store all the information related to an LLVM module. ...
This class represents a function call, abstracting a target machine's calling convention.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
STATISTIC(NumFunctions, "Total number of functions")
static CallInst * Create(Value *Func, ArrayRef< Value *> Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
param_iterator param_end() const
This defines the Use class.
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode *>> &MDs) const
Appends all attachments for the global to MDs, sorting by attachment ID.
bool isMustTailCall() const
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
SI optimize exec mask operations pre RA
Class to represent struct types.
ModulePass * createDeadArgHackingPass()
DeadArgHacking pass - Same as DAE, but delete arguments of external functions as well.
A Use represents the edge between a Value definition and its users.
This file contains the simple types necessary to represent the attributes associated with functions a...
AttributeSet getRetAttributes() const
The attributes for the ret value are returned.
InstrTy * getInstruction() const
static StructType * get(LLVMContext &Context, ArrayRef< Type *> Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Class to represent function types.
Type * getType() const
All values are typed, get the type of this value.
INITIALIZE_PASS(DAH, "deadarghaX0r", "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)", false, false) ModulePass *llvm
createDeadArgEliminationPass - This pass removes arguments from functions which are not used by the b...
Class to represent array types.
AttributeSet getParamAttributes(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
void setComdat(Comdat *C)
AttrBuilder & remove(const AttrBuilder &B)
Remove the attributes from the builder.
AttributeList getAttributes() const
Return the attribute list for this Function.
bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
LinkageTypes getLinkage() const
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
void takeName(Value *V)
Transfer the name from V to this value.
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool isVoidTy() const
Return true if this is 'void'.
bool hasAttrSomewhere(Attribute::AttrKind Kind, unsigned *Index=nullptr) const
Return true if the specified attribute is set for at least one parameter or for the return value...
void setAttributes(AttributeList PAL)
Set the parameter attributes of the call.
Type * getReturnType() const
Returns the type of the ret val.
A set of analyses that are preserved following a run of a transformation pass.
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
bool areAllPreserved() const
Test whether all analyses are preserved (and none are abandoned).
static unsigned getAggregateOperandIndex()
const FunctionListType & getFunctionList() const
Get the Module's list of functions (constant).
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
ModulePass * createDeadArgEliminationPass()
createDeadArgEliminationPass - This pass removes arguments from functions which are not used by the b...
AttributeSet removeAttribute(LLVMContext &C, Attribute::AttrKind Kind) const
Remove the specified attribute from this set.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
void initializeDAEPass(PassRegistry &)
param_iterator param_begin() const
static Type * getVoidTy(LLVMContext &C)
void splice(iterator where, iplist_impl &L2)
void setCallingConv(CallingConv::ID CC)
Set the calling convention of the call.
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
self_iterator getIterator()
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static InvokeInst * Create(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value *> Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
static unsigned NumRetVals(const Function *F)
Convenience function that returns the number of return values.
Iterator for intrusive lists based on ilist_node.
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
Equivalent to hasAttribute(ArgNo + FirstArgIndex, Kind).
AttrBuilder & removeAttribute(Attribute::AttrKind Val)
Remove an attribute from the builder.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
static Type * getRetComponentType(const Function *F, unsigned Idx)
Returns the sub-type a function will return at a given Idx.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Type * getReturnType() const
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
amdgpu Simplify well known AMD library false Value Value * Arg
const Comdat * getComdat() const
iterator insert(iterator where, pointer New)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_NODISCARD bool empty() const
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
StringRef getName() const
Return a constant reference to the value's name.
bool hasExactDefinition() const
Return true if this global has an exact defintion.
Establish a view to a call site for examination.
user_iterator_impl< User > user_iterator
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Liveness
Liveness enum - During our initial pass over the program, we determine that things are either alive o...
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
AttrBuilder typeIncompatible(Type *Ty)
Which attributes cannot be applied to a type.
AttributeSet getFnAttributes() const
The function attributes are returned.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the edge connecting specified block.
A container for analyses that lazily runs them and caches their results.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
AttributeList getAttributes() const
Get the parameter attributes of the call.
This header defines various interfaces for pass management in LLVM.
bool isEmpty() const
Return true if there are no attributes.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
PointerType * getType() const
Global values are always pointers.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.
iterator_range< arg_iterator > args()
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
This instruction inserts a struct field of array element value into an aggregate value.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)