60 #define DEBUG_TYPE "argpromotion"
62 STATISTIC(NumArgumentsPromoted,
"Number of pointer arguments promoted");
63 STATISTIC(NumAggregatesPromoted,
"Number of aggregate arguments promoted");
64 STATISTIC(NumByValArgsPromoted,
"Number of byval arguments promoted");
65 STATISTIC(NumArgumentsDead,
"Number of dead pointer args eliminated");
82 std::vector<Type *> Params;
84 typedef std::set<std::pair<Type *, IndicesVector>> ScalarizeTable;
93 std::map<Argument *, ScalarizeTable> ScalarizedElements;
100 std::map<std::pair<Argument *, IndicesVector>,
LoadInst *> OriginalLoads;
112 if (ByValArgsToTransform.
count(&*
I)) {
114 Type *AgTy = cast<PointerType>(
I->getType())->getElementType();
119 ++NumByValArgsPromoted;
120 }
else if (!ArgsToPromote.
count(&*
I)) {
122 Params.push_back(
I->getType());
124 }
else if (
I->use_empty()) {
137 ScalarizeTable &ArgIndices = ScalarizedElements[&*
I];
138 for (
User *U :
I->users()) {
141 if (
LoadInst *
L = dyn_cast<LoadInst>(UI))
142 SrcTy =
L->getType();
144 SrcTy = cast<GetElementPtrInst>(UI)->getSourceElementType();
152 Indices.push_back(cast<ConstantInt>(*II)->getSExtValue());
154 if (Indices.size() == 1 && Indices.front() == 0)
156 ArgIndices.insert(std::make_pair(SrcTy, Indices));
158 if (
LoadInst *
L = dyn_cast<LoadInst>(UI))
162 OrigLoad = cast<LoadInst>(UI->
user_back());
163 OriginalLoads[std::make_pair(&*
I, Indices)] = OrigLoad;
167 for (
const auto &ArgIndex : ArgIndices) {
170 cast<PointerType>(
I->getType()->getScalarType())->getElementType(),
176 if (ArgIndices.size() == 1 && ArgIndices.begin()->second.empty())
177 ++NumArgumentsPromoted;
179 ++NumAggregatesPromoted;
196 DEBUG(
dbgs() <<
"ARG PROMOTION: Promoting to:" << *NF <<
"\n"
214 assert(CS.getCalledFunction() ==
F);
224 if (!ArgsToPromote.
count(&*
I) && !ByValArgsToTransform.
count(&*
I)) {
227 }
else if (ByValArgsToTransform.
count(&*
I)) {
229 Type *AgTy = cast<PointerType>(
I->getType())->getElementType();
236 STy, *AI, Idxs, (*AI)->
getName() +
"." +
Twine(i), Call);
241 }
else if (!
I->use_empty()) {
243 ScalarizeTable &ArgIndices = ScalarizedElements[&*
I];
246 std::vector<Value *> Ops;
247 for (
const auto &ArgIndex : ArgIndices) {
250 OriginalLoads[std::make_pair(&*
I, ArgIndex.second)];
251 if (!ArgIndex.second.empty()) {
252 Ops.reserve(ArgIndex.second.size());
254 for (
auto II : ArgIndex.second) {
262 if (
auto *ElPTy = dyn_cast<PointerType>(ElTy))
263 ElTy = ElPTy->getElementType();
265 ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(II);
287 for (; AI != CS.arg_end(); ++AI, ++ArgNo) {
293 CS.getOperandBundlesAsDefs(OpBundles);
296 if (
InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
298 Args, OpBundles,
"", Call);
301 NewCall->setTailCallKind(cast<CallInst>(Call)->getTailCallKind());
308 NewCS->setDebugLoc(Call->getDebugLoc());
310 if (Call->extractProfTotalWeight(W))
311 NewCS->setProfWeight(W);
317 (*ReplaceCallSite)(CS, NewCS);
319 if (!Call->use_empty()) {
321 NewCS->takeName(Call);
326 Call->eraseFromParent();
340 I2 = NF->arg_begin();
342 if (!ArgsToPromote.
count(&*
I) && !ByValArgsToTransform.
count(&*
I)) {
345 I->replaceAllUsesWith(&*I2);
351 if (ByValArgsToTransform.
count(&*
I)) {
357 Type *AgTy = cast<PointerType>(
I->getType())->getElementType();
359 I->getParamAlignment(),
"", InsertPt);
364 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
367 AgTy, TheAlloca, Idxs, TheAlloca->
getName() +
"." +
Twine(i),
374 I->replaceAllUsesWith(TheAlloca);
394 ScalarizeTable &ArgIndices = ScalarizedElements[&*
I];
396 while (!
I->use_empty()) {
397 if (
LoadInst *LI = dyn_cast<LoadInst>(
I->user_back())) {
398 assert(ArgIndices.begin()->second.empty() &&
399 "Load element should sort to front!");
400 I2->setName(
I->getName() +
".val");
401 LI->replaceAllUsesWith(&*I2);
402 LI->eraseFromParent();
403 DEBUG(
dbgs() <<
"*** Promoted load of argument '" <<
I->getName()
404 <<
"' in function '" << F->
getName() <<
"'\n");
411 Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
414 if (Operands.size() == 1 && Operands.front() == 0)
418 for (ScalarizeTable::iterator It = ArgIndices.begin();
419 It->second != Operands; ++It, ++TheArg) {
420 assert(It != ArgIndices.end() &&
"GEP not handled??");
423 std::string NewName =
I->getName();
424 for (
unsigned i = 0, e = Operands.size(); i != e; ++i) {
425 NewName +=
"." +
utostr(Operands[i]);
431 <<
"' of function '" << NF->getName() <<
"'\n");
445 std::advance(I2, ArgIndices.size());
463 assert(CS &&
"Should only have direct calls!");
477 if (Prefix.size() > Longer.size())
479 return std::equal(Prefix.begin(), Prefix.end(), Longer.begin());
484 std::set<IndicesVector> &Set) {
485 std::set<IndicesVector>::iterator Low;
486 Low = Set.upper_bound(Indices);
487 if (Low != Set.begin())
494 return Low != Set.end() &&
isPrefix(*Low, Indices);
503 std::set<IndicesVector> &Safe) {
504 std::set<IndicesVector>::iterator Low;
505 Low = Safe.upper_bound(ToMark);
507 if (Low != Safe.begin())
512 if (Low != Safe.end()) {
522 Low = Safe.insert(Low, ToMark);
525 std::set<IndicesVector>::iterator
End = Safe.end();
526 while (Low != End &&
isPrefix(ToMark, *Low)) {
527 std::set<IndicesVector>::iterator Remove = Low;
540 typedef std::set<IndicesVector> GEPIndicesSet;
564 GEPIndicesSet SafeToUnconditionallyLoad;
568 GEPIndicesSet ToPromote;
580 if (
LoadInst *LI = dyn_cast<LoadInst>(&
I)) {
581 Value *V = LI->getPointerOperand();
583 V =
GEP->getPointerOperand();
586 Indices.reserve(
GEP->getNumIndices());
590 Indices.push_back(CI->getSExtValue());
600 }
else if (V == Arg) {
611 User *UR = U.getUser();
613 if (
LoadInst *LI = dyn_cast<LoadInst>(UR)) {
619 Operands.push_back(0);
621 if (
GEP->use_empty()) {
624 GEP->eraseFromParent();
636 Operands.push_back(
C->getSExtValue());
641 for (
User *GEPU :
GEP->users())
642 if (
LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
657 if (!
prefixIn(Operands, SafeToUnconditionallyLoad))
663 if (ToPromote.find(Operands) == ToPromote.end()) {
664 if (MaxElements > 0 && ToPromote.size() == MaxElements) {
665 DEBUG(
dbgs() <<
"argpromotion not promoting argument '"
667 <<
"' because it would require adding more "
668 <<
"than " << MaxElements
669 <<
" arguments to the function.\n");
674 ToPromote.insert(std::move(Operands));
727 if (!isa<CompositeType>(type))
735 StructType *StructTy = cast<StructType>(type);
737 uint64_t StartPos = 0;
742 if (StartPos != Layout->getElementOffsetInBits(i))
766 while (!WorkList.
empty()) {
769 if (isa<GetElementPtrInst>(V) || isa<PHINode>(V)) {
770 if (PtrValues.insert(V).second)
774 }
else if (!isa<LoadInst>(V)) {
781 if (PtrValues.count(
Store->getValueOperand()))
794 unsigned MaxElements,
812 if (
I.getType()->isPointerTy())
814 if (PointerArgs.
empty())
820 bool isSelfRecursive =
false;
824 if (CS.getInstruction() ==
nullptr || !CS.isCallee(&U))
827 if (CS.getInstruction()->getParent()->getParent() ==
F)
828 isSelfRecursive =
true;
839 for (
Argument *PtrArg : PointerArgs) {
840 Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
844 if (PtrArg->hasStructRetAttr()) {
845 unsigned ArgNo = PtrArg->getArgNo();
850 CS.removeParamAttr(ArgNo, Attribute::StructRet);
859 bool isSafeToPromote =
860 PtrArg->hasByValAttr() &&
862 if (isSafeToPromote) {
863 if (
StructType *STy = dyn_cast<StructType>(AgTy)) {
864 if (MaxElements > 0 && STy->getNumElements() > MaxElements) {
865 DEBUG(
dbgs() <<
"argpromotion disable promoting argument '"
867 <<
"' because it would require adding more"
868 <<
" than " << MaxElements
869 <<
" arguments to the function.\n");
874 bool AllSimple =
true;
875 for (
const auto *EltTy : STy->elements()) {
876 if (!EltTy->isSingleValueType()) {
886 ByValArgsToTransform.
insert(PtrArg);
894 if (isSelfRecursive) {
895 if (
StructType *STy = dyn_cast<StructType>(AgTy)) {
896 bool RecursiveType =
false;
897 for (
const auto *EltTy : STy->elements()) {
898 if (EltTy == PtrArg->getType()) {
899 RecursiveType =
true;
911 ArgsToPromote.
insert(PtrArg);
915 if (ArgsToPromote.
empty() && ByValArgsToTransform.
empty())
918 return doPromotion(F, ArgsToPromote, ByValArgsToTransform, ReplaceCallSite);
925 bool Changed =
false, LocalChange;
939 assert(&F == &OldF &&
"Called with an unexpected function!");
953 C.getOuterRefSCC().replaceNodeFunction(
N, *NewF);
957 Changed |= LocalChange;
958 }
while (LocalChange);
979 explicit ArgPromotion(
unsigned MaxElements = 3)
986 bool doInitialization(
CallGraph &CG)
override;
988 unsigned MaxElements;
994 "Promote 'by reference' arguments to scalars",
false,
1000 "Promote 'by reference' arguments to
scalars",
false, false)
1003 return new ArgPromotion(MaxElements);
1012 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1016 bool Changed =
false, LocalChange;
1020 LocalChange =
false;
1023 Function *OldF = OldNode->getFunction();
1036 {ReplaceCallSite})) {
1042 if (OldNode->getNumReferences() == 0)
1048 SCC.ReplaceNode(OldNode, NewNode);
1052 Changed |= LocalChange;
1053 }
while (LocalChange);
1058 bool ArgPromotion::doInitialization(
CallGraph &CG) {
Pass interface - Implemented by all 'passes'.
AttributeSet getRetAttributes() const
The attributes for the ret value are returned.
User::op_iterator arg_iterator
The type of iterator to use when looping over actual arguments at this call site. ...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
LinkageTypes getLinkage() const
iterator_range< use_iterator > uses()
void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
removes the attribute from the list of attributes.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
This class represents an incoming formal argument to a Function.
STATISTIC(NumFunctions,"Total number of functions")
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
unsigned getNumOperands() const
Implements a lazy call graph analysis and related passes for the new pass manager.
This class represents a function call, abstracting a target machine's calling convention.
An immutable pass that tracks lazily created AssumptionCache objects.
virtual bool doInitialization(CallGraph &CG)
doInitialization - This method is called before the SCC's of the program has been processed...
An efficient, type-erasing, non-owning reference to a callable.
Externally visible function.
const Function * getParent() const
Return the enclosing method, or null if none.
iterator_range< idf_ext_iterator< T, SetTy > > inverse_depth_first_ext(const T &G, SetTy &S)
const Instruction & front() const
The two locations do not alias at all.
An instruction for reading from memory.
static IntegerType * getInt64Ty(LLVMContext &C)
A proxy from a FunctionAnalysisManager to an SCC.
A node in the call graph for a module.
void getAnalysisUsage(AnalysisUsage &Info) const override
getAnalysisUsage - For this class, we declare that we require and preserve the call graph...
unsigned getNumIndices() const
The access modifies the value stored in memory.
Support structure for SCC passes to communicate updates the call graph back to the CGSCC pass manager...
uint64_t getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
StringRef getName() const
Return a constant reference to the value's name.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
AttributeList getAttributes() const
Return the attribute list for this Function.
element_iterator element_end() const
AnalysisUsage & addRequired()
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
#define INITIALIZE_PASS_DEPENDENCY(depName)
AttributeSet getParamAttributes(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Class to represent struct types.
void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode)
Replaces the edge in the node for the specified call site with a new one.
A Use represents the edge between a Value definition and its users.
void initializeArgPromotionPass(PassRegistry &)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class is a functor to be used in legacy module or SCC passes for computing AA results for a func...
Pass * createArgumentPromotionPass(unsigned maxElements=3)
createArgumentPromotionPass - This pass promotes "by reference" arguments to be passed by value if th...
Function * removeFunctionFromModule(CallGraphNode *CGN)
Unlink the function from this module, returning it.
element_iterator element_begin() const
void setName(const Twine &Name)
Change the name of the value.
LLVM_NODISCARD bool empty() const
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
Class to represent function types.
A lazily constructed view of the call graph of a module.
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static std::string utostr(uint64_t X, bool isNeg=false)
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void takeName(Value *V)
Transfer the name from V to this value.
virtual bool doInitialization(Module &)
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
void setAttributes(AttributeList PAL)
Set the parameter attributes of the call.
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
A set of analyses that are preserved following a run of a transformation pass.
The ModulePass which wraps up a CallGraph and the logic to build it.
void setAAMetadata(const AAMDNodes &N)
Sets the metadata on this instruction from the AAMDNodes structure.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
FunctionType * getFunctionType() const
Returns the FunctionType for me.
const Function * getParent() const
bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2, const MemoryLocation &Loc, const ModRefInfo Mode)
Check if it is possible for the execution of the specified instructions to mod(according to the mode)...
void stealCalledFunctionsFrom(CallGraphNode *N)
Moves all the callee information from N to this node.
Type * getElementType(unsigned N) const
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
A manager for alias analyses.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
unsigned getAllocaAddrSpace() const
Represent the analysis usage information of a pass.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
static const unsigned End
void setCallingConv(CallingConv::ID CC)
Set the calling convention of the call.
A node in the call graph.
self_iterator getIterator()
void setAlignment(unsigned Align)
LLVM_NODISCARD bool empty() const
void setTailCall(bool isTC=true)
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.
void getAAResultsAnalysisUsage(AnalysisUsage &AU)
A helper for the legacy pass manager to populate AU to add uses to make sure the analyses required by...
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static InvokeInst * Create(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
bool hasByValAttr() const
Return true if this argument has the byval attribute.
const FunctionListType & getFunctionList() const
Get the Module's list of functions (constant).
Representation for a specific memory location.
This is the superclass of the array and vector type classes.
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
This is the shared class of boolean and integer constants.
InstrTy * getInstruction() const
ValTy * getArgument(unsigned ArgNo) const
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
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.
Type * getType() const
All values are typed, get the type of this value.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
pred_range predecessors(BasicBlock *BB)
AttributeSet getFnAttributes() const
The function attributes are returned.
void setLinkage(LinkageTypes LT)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
DISubprogram * getSubprogram() const
Get the attached subprogram.
StringRef getName() const
Return the name for this struct type if it has an identity.
iterator_range< user_iterator > users()
iterator insert(iterator I, T &&Elt)
bool isStructTy() const
True if this is an instance of StructType.
static Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the type of the element that would be loaded with a load instruction with the specified param...
bool isDereferenceablePointer(const Value *V, const DataLayout &DL, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if this is always a dereferenceable pointer.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
The basic data container for the call graph of a Module of IR.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
iterator insert(iterator where, pointer New)
static IntegerType * getInt32Ty(LLVMContext &C)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
Fills the AAMDNodes structure with AA metadata from this instruction.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
bool hasLocalLinkage() const
Type * getReturnType() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
const BasicBlock & front() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
An SCC of the call graph.
CallGraphSCC - This is a single SCC that a CallGraphSCCPass is run on.
CallGraphNode * getOrInsertFunction(const Function *F)
Similar to operator[], but this will insert a new CallGraphNode for F if one does not already exist...
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
This is the interface for LLVM's primary stateless and local alias analysis.
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)
unsigned getNumElements() const
Random access to the elements.
bool canBasicBlockModify(const BasicBlock &BB, const MemoryLocation &Loc)
Check if it is possible for execution of the specified basic block to modify the location Loc...
const BasicBlock * getParent() const
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()
an instruction to allocate memory on the stack