62 #define DEBUG_TYPE "amdgpu-promote-alloca"
80 bool IsAMDGCN =
false;
81 bool IsAMDHSA =
false;
83 std::pair<Value *, Value *> getLocalSizeYZ(
IRBuilder<> &Builder);
88 bool collectUsesWithPtrTypes(
Value *BaseAlloca,
90 std::vector<Value*> &WorkList)
const;
96 bool binaryOpIsDerivedFromSameAlloca(
Value *Alloca,
Value *Val,
98 int OpIdx0,
int OpIdx1)
const;
101 bool hasSufficientLocalMem(
const Function &
F);
108 bool doInitialization(
Module &M)
override;
109 bool runOnFunction(
Function &F)
override;
111 StringRef getPassName()
const override {
return "AMDGPU Promote Alloca"; }
113 bool handleAlloca(
AllocaInst &
I,
bool SufficientLDS);
126 "AMDGPU promote alloca to vector or LDS",
false,
false)
130 bool AMDGPUPromoteAlloca::doInitialization(
Module &M) {
132 DL = &Mod->getDataLayout();
137 bool AMDGPUPromoteAlloca::runOnFunction(
Function &
F) {
141 if (
auto *
TPC = getAnalysisIfAvailable<TargetPassConfig>())
146 const Triple &TT =
TM->getTargetTriple();
156 bool SufficientLDS = hasSufficientLocalMem(F);
157 bool Changed =
false;
159 for (
auto I = EntryBB.
begin(),
E = EntryBB.
end();
I !=
E; ) {
164 Changed |= handleAlloca(*AI, SufficientLDS);
170 std::pair<Value *, Value *>
171 AMDGPUPromoteAlloca::getLocalSizeYZ(
IRBuilder<> &Builder) {
187 return std::make_pair(LocalSizeY, LocalSizeZ);
255 return std::make_pair(Y, LoadZU);
265 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_x
266 : Intrinsic::r600_read_tidig_x;
269 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_y
270 : Intrinsic::r600_read_tidig_y;
274 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_z
275 : Intrinsic::r600_read_tidig_z;
295 const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
298 auto I = GEPIdx.find(GEP);
299 return I == GEPIdx.end() ?
nullptr : I->second;
321 LoadInst *LI = cast<LoadInst>(Inst);
325 case Instruction::BitCast:
326 case Instruction::AddrSpaceCast:
342 DEBUG(
dbgs() <<
"Alloca candidate for vectorization\n");
353 DEBUG(
dbgs() <<
" Cannot convert type to vector\n");
357 std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
358 std::vector<Value*> WorkList;
359 for (
User *AllocaUser : Alloca->
users()) {
365 WorkList.push_back(AllocaUser);
374 DEBUG(
dbgs() <<
" Cannot compute vector index for GEP " << *GEP <<
'\n');
378 GEPVectorIdx[
GEP] = Index;
379 for (
User *GEPUser : AllocaUser->
users()) {
383 WorkList.push_back(GEPUser);
389 DEBUG(
dbgs() <<
" Converting alloca to vector "
390 << *AllocaTy <<
" -> " << *VectorTy <<
'\n');
392 for (
Value *V : WorkList) {
401 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
402 Value *VecValue = Builder.CreateLoad(BitCast);
403 Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
414 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
415 Value *VecValue = Builder.CreateLoad(BitCast);
416 Value *NewVecValue = Builder.CreateInsertElement(VecValue,
419 Builder.CreateStore(NewVecValue, BitCast);
423 case Instruction::BitCast:
424 case Instruction::AddrSpaceCast:
440 case Intrinsic::memcpy:
441 case Intrinsic::memmove:
442 case Intrinsic::memset:
443 case Intrinsic::lifetime_start:
444 case Intrinsic::lifetime_end:
445 case Intrinsic::invariant_start:
446 case Intrinsic::invariant_end:
447 case Intrinsic::invariant_group_barrier:
448 case Intrinsic::objectsize:
455 bool AMDGPUPromoteAlloca::binaryOpIsDerivedFromSameAlloca(
Value *BaseAlloca,
465 if (isa<ConstantPointerNull>(OtherOp))
469 if (!isa<AllocaInst>(OtherObj))
478 if (OtherObj != BaseAlloca) {
479 DEBUG(
dbgs() <<
"Found a binary instruction with another alloca object\n");
486 bool AMDGPUPromoteAlloca::collectUsesWithPtrTypes(
489 std::vector<Value*> &WorkList)
const {
499 WorkList.push_back(
User);
504 if (UseInst->
getOpcode() == Instruction::PtrToInt)
507 if (
LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
508 if (LI->isVolatile())
514 if (
StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
515 if (
SI->isVolatile())
519 if (
SI->getPointerOperand() != Val)
521 }
else if (
AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
522 if (RMW->isVolatile())
525 if (CAS->isVolatile())
531 if (
ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
532 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
536 WorkList.push_back(ICmp);
539 if (UseInst->
getOpcode() == Instruction::AddrSpaceCast) {
544 WorkList.push_back(
User);
554 if (!
GEP->isInBounds())
560 if (
SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
561 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
566 if (
PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
569 switch (Phi->getNumIncomingValues()) {
573 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
581 WorkList.push_back(
User);
582 if (!collectUsesWithPtrTypes(BaseAlloca,
User, WorkList))
589 bool AMDGPUPromoteAlloca::hasSufficientLocalMem(
const Function &F) {
601 DEBUG(
dbgs() <<
"Function has local memory argument. Promoting to "
602 "local memory disabled.\n");
608 if (LocalMemLimit == 0)
614 CurrentLocalMemUsage = 0;
616 if (GV.getType()->getAddressSpace() != AS.LOCAL_ADDRESS)
625 unsigned Align = GV.getAlignment();
634 CurrentLocalMemUsage =
alignTo(CurrentLocalMemUsage, Align);
635 CurrentLocalMemUsage += AllocSize;
650 if (OccupancyHint == 0)
658 MaxOccupancy =
std::min(OccupancyHint, MaxOccupancy);
662 unsigned MaxSizeWithWaveCount
666 if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
669 LocalMemLimit = MaxSizeWithWaveCount;
672 dbgs() << F.
getName() <<
" uses " << CurrentLocalMemUsage <<
" bytes of LDS\n"
673 <<
" Rounding size to " << MaxSizeWithWaveCount
674 <<
" with a maximum occupancy of " << MaxOccupancy <<
'\n'
675 <<
" and " << (LocalMemLimit - CurrentLocalMemUsage)
676 <<
" available for promotion\n"
683 bool AMDGPUPromoteAlloca::handleAlloca(
AllocaInst &
I,
bool SufficientLDS) {
694 DEBUG(
dbgs() <<
"Trying to promote " << I <<
'\n');
710 DEBUG(
dbgs() <<
" promote alloca to LDS not supported with calling convention.\n");
736 NewSize += AllocSize;
738 if (NewSize > LocalMemLimit) {
740 <<
" bytes of local memory not available to promote\n");
744 CurrentLocalMemUsage = NewSize;
746 std::vector<Value*> WorkList;
748 if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
749 DEBUG(
dbgs() <<
" Do not know how to convert all uses\n");
753 DEBUG(
dbgs() <<
"Promoting alloca to local memory\n");
768 Value *TCntY, *TCntZ;
770 std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
771 Value *TIdX = getWorkitemID(Builder, 0);
772 Value *TIdY = getWorkitemID(Builder, 1);
773 Value *TIdZ = getWorkitemID(Builder, 2);
791 for (
Value *V : WorkList) {
794 if (
ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
799 if (isa<ConstantPointerNull>(CI->
getOperand(0)))
802 if (isa<ConstantPointerNull>(CI->
getOperand(1)))
810 if (isa<AddrSpaceCastInst>(V))
818 V->mutateType(NewTy);
821 if (
SelectInst *SI = dyn_cast<SelectInst>(V)) {
822 if (isa<ConstantPointerNull>(
SI->getOperand(1)))
825 if (isa<ConstantPointerNull>(
SI->getOperand(2)))
827 }
else if (
PHINode *Phi = dyn_cast<PHINode>(V)) {
828 for (
unsigned I = 0,
E = Phi->getNumIncomingValues(); I !=
E; ++
I) {
829 if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
840 case Intrinsic::lifetime_start:
841 case Intrinsic::lifetime_end:
845 case Intrinsic::memcpy: {
853 case Intrinsic::memmove: {
861 case Intrinsic::memset: {
869 case Intrinsic::invariant_start:
870 case Intrinsic::invariant_end:
871 case Intrinsic::invariant_group_barrier:
877 case Intrinsic::objectsize: {
881 Intrinsic::objectsize,
900 return new AMDGPUPromoteAlloca();
unsigned getAlignment() const
OSType getOS() const
getOS - Get the parsed operating system type of this triple.
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
AMDGPU specific subclass of TargetSubtarget.
bool makeLIDRangeMetadata(Instruction *I) const
Creates value range metadata on an workitemid.* inrinsic call or load.
bool isVolatile() const
Return true if this is a store to a volatile memory location.
A Module instance is used to store all the information related to an LLVM module. ...
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
Value * getValue() const
Return the arguments to the instruction.
unsigned getNumOperands() const
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
This class represents a function call, abstracting a target machine's calling convention.
ArrayRef< Type * > params() const
AMDGPUAS getAMDGPUAS(const Module &M)
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
This class wraps the llvm.memset intrinsic.
FunctionPass * createAMDGPUPromoteAlloca()
const Function * getParent() const
Return the enclosing method, or null if none.
The two locations do not alias at all.
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
CallInst * CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memset to the specified pointer and the specified value.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
An instruction for reading from memory.
int getLocalMemorySize() const
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Type * getPointerElementType() const
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
uint64_t getArrayNumElements() const
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
static Value * getPointerOperand(Instruction &Inst)
This class represents the LLVM 'select' instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
OpenCL uses address spaces to differentiate between various memory regions on the hardware...
This class wraps the llvm.memmove intrinsic.
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
Type * getArrayElementType() const
A Use represents the edge between a Value definition and its users.
std::pair< unsigned, unsigned > getWavesPerEU(const Function &F) const
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This file contains the simple types necessary to represent the attributes associated with functions a...
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
This file implements a class to represent arbitrary precision integral constant values and operations...
Class to represent function types.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Class to represent array types.
CallInst * CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memmove between the specified pointers.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool isArrayTy() const
True if this is an instance of ArrayType.
Value * CreateInBoundsGEP(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Type * getElementType() const
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Class to represent pointers.
SPIR_KERNEL - Calling convention for SPIR kernel functions.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
unsigned getMaxWavesPerEU() const
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.
bool isVectorTy() const
True if this is an instance of VectorType.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
Value * getRawDest() const
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
uint64_t getNumElements() const
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
Value * getPointerOperand()
unsigned getOccupancyWithLocalMemSize(uint32_t Bytes, const Function &) const
Inverse of getMaxLocalMemWithWaveCount.
bool isPointerTy() const
True if this is an instance of PointerType.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, bool StoreCaptures)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
bool isPromoteAllocaEnabled() const
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Triple - Helper class for working with autoconf configuration names.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
This is the shared class of boolean and integer constants.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
Value * getLength() const
BasicBlock * GetInsertBlock() const
This class wraps the llvm.memcpy intrinsic.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Value * CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name="")
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Class to represent vector types.
iterator_range< user_iterator > users()
unsigned getMaxLocalMemSizeWithWaveCount(unsigned WaveCount, const Function &) const
Return the amount of LDS that can be used that will not restrict the occupancy lower than WaveCount...
llvm_unreachable("Unknown RegBank!")
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
CallInst * CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memcpy between the specified pointers.
void setUnnamedAddr(UnnamedAddr Val)
static IntegerType * getInt32Ty(LLVMContext &C)
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
CallInst * CreateCall(Value *Callee, ArrayRef< Value * > Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
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)
Rename collisions when linking (static functions).
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Value * getRawSource() const
Return the arguments to the instruction.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LoadInst * CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name)
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Primary interface to the complete machine description for the target machine.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
char & AMDGPUPromoteAllocaID
StringRef - Represent a constant reference to a string, i.e.
std::pair< unsigned, unsigned > getFlatWorkGroupSizes(const Function &F) const
void addAttribute(unsigned i, Attribute::AttrKind Kind)
adds the attribute to the list of attributes.
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml","ocaml 3.10-compatible collector")
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Calling convention for AMDGPU code object kernels.
Value * getPointerOperand()
const BasicBlock * getParent() const
unsigned PRIVATE_ADDRESS
Address space for private memory.
void addDereferenceableAttr(unsigned i, uint64_t Bytes)
adds the dereferenceable attribute to the list of attributes.
A wrapper class for inspecting calls to intrinsic functions.
an instruction to allocate memory on the stack
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.