43 #define DEBUG_TYPE "printfToRuntime" 53 explicit AMDGPUPrintfRuntimeBinding();
56 bool runOnModule(
Module &M)
override;
60 bool shouldPrintAsStr(
char Specifier,
Type *OpType)
const;
62 lowerPrintfForGpu(
Module &M,
83 "amdgpu-printf-runtime-binding",
"AMDGPU Printf lowering",
94 return new AMDGPUPrintfRuntimeBinding();
98 AMDGPUPrintfRuntimeBinding::AMDGPUPrintfRuntimeBinding()
103 void AMDGPUPrintfRuntimeBinding::getConversionSpecifiers(
105 size_t NumOps)
const {
111 static const char ConvSpecifiers[] =
"cdieEfgGaosuxXp";
112 size_t CurFmtSpecifierIdx = 0;
113 size_t PrevFmtSpecifierIdx = 0;
117 bool ArgDump =
false;
119 CurFmtSpecifierIdx - PrevFmtSpecifierIdx);
123 while (pTag && CurFmt[--pTag] ==
'%') {
129 OpConvSpecifiers.
push_back(Fmt[CurFmtSpecifierIdx]);
131 PrevFmtSpecifierIdx = ++CurFmtSpecifierIdx;
135 bool AMDGPUPrintfRuntimeBinding::shouldPrintAsStr(
char Specifier,
136 Type *OpType)
const {
137 if (Specifier !=
's')
145 IntegerType *ElemIType = cast<IntegerType>(ElemType);
149 bool AMDGPUPrintfRuntimeBinding::lowerPrintfForGpu(
156 const char NonLiteralStr[4] =
"???";
158 for (
auto CI : Printfs) {
159 unsigned NumOps = CI->getNumArgOperands();
162 Value *
Op = CI->getArgOperand(0);
164 if (
auto LI = dyn_cast<LoadInst>(Op)) {
165 Op = LI->getPointerOperand();
167 if (
auto SI = dyn_cast<StoreInst>(
Use)) {
168 Op =
SI->getValueOperand();
174 if (
auto I = dyn_cast<Instruction>(Op)) {
188 if (
auto CA = dyn_cast<ConstantDataArray>(
Init)) {
190 Str = CA->getAsCString();
191 }
else if (isa<ConstantAggregateZero>(
Init)) {
200 getConversionSpecifiers(OpConvSpecifiers, Str, NumOps - 1);
203 std::string AStreamHolder;
206 Sizes << CI->getNumArgOperands() - 1;
208 for (
unsigned ArgCount = 1; ArgCount < CI->getNumArgOperands() &&
209 ArgCount <= OpConvSpecifiers.
size();
211 Value *
Arg = CI->getArgOperand(ArgCount);
213 unsigned ArgSize = TD->getTypeAllocSizeInBits(ArgType);
214 ArgSize = ArgSize / 8;
223 if (LLVMVecType && NumElem > 1)
227 if (OpConvSpecifiers[ArgCount - 1] ==
'x' ||
228 OpConvSpecifiers[ArgCount - 1] ==
'X' ||
229 OpConvSpecifiers[ArgCount - 1] ==
'u' ||
230 OpConvSpecifiers[ArgCount - 1] ==
'o')
235 ArgSize = TD->getTypeAllocSizeInBits(ArgType);
236 ArgSize = ArgSize / 8;
237 CI->setOperand(ArgCount, Arg);
239 if (OpConvSpecifiers[ArgCount - 1] ==
'f') {
250 if (shouldPrintAsStr(OpConvSpecifiers[ArgCount - 1], ArgType)) {
251 if (
ConstantExpr *ConstExpr = dyn_cast<ConstantExpr>(Arg)) {
273 ArgSize =
sizeof(NonLiteralStr);
276 ArgSize =
sizeof(NonLiteralStr);
280 <<
" for type: " << *ArgType <<
'\n');
281 Sizes << ArgSize <<
':';
284 LLVM_DEBUG(
dbgs() <<
"Printf format string in source = " << Str.str()
286 for (
size_t I = 0;
I < Str.size(); ++
I) {
324 Attribute::NoUnwind);
328 Type *Tys_alloc[1] = {SizetTy};
335 std::string fmtstr =
itostr(++UniqID) +
":" + Sizes.
str().c_str();
364 if (!CI->use_empty()) {
384 nullptr, pcall, ZeroIdxList,
"PrintBuffID", Brnch));
388 new BitCastInst(BufferIdx, idPointer,
"PrintBuffIdCast", Brnch);
401 nullptr, pcall, FourthIdxList,
"PrintBuffGep", Brnch));
405 for (
unsigned ArgCount = 1; ArgCount < CI->getNumArgOperands() &&
406 ArgCount <= OpConvSpecifiers.
size();
408 Value *
Arg = CI->getArgOperand(ArgCount);
414 if (OpConvSpecifiers[ArgCount - 1] ==
'f') {
432 Arg =
new BitCastInst(Arg, IType,
"PrintArgFP", Brnch);
435 if (shouldPrintAsStr(OpConvSpecifiers[ArgCount - 1], ArgType)) {
436 const char *S = NonLiteralStr;
437 if (
ConstantExpr *ConstExpr = dyn_cast<ConstantExpr>(Arg)) {
448 size_t SizeStr = strlen(S) + 1;
457 char *MyNewStr =
new char[NSizeStr]();
459 int NumInts = NSizeStr / 4;
462 int ANum = *(
int *)(MyNewStr + CharC);
475 uint64_t
Size = TD->getTypeAllocSizeInBits(ArgType);
476 assert((Size == 32 || Size == 64) &&
"unsupported size");
477 Type *DstType = (Size == 32) ? Int32Ty : Int64Ty;
478 Arg =
new PtrToIntInst(Arg, DstType,
"PrintArgPtr", Brnch);
483 uint32_t EleCount = cast<VectorType>(ArgType)->getNumElements();
485 uint32_t TotalSize = EleCount * EleSize;
496 TotalSize += EleSize;
500 EleCount = TotalSize / 64;
505 EleCount = TotalSize / 64;
507 }
else if (EleCount >= 3) {
517 EleCount = TotalSize / 64;
528 Arg =
new BitCastInst(Arg, IType,
"PrintArgVect", Brnch);
533 for (
unsigned I = 0,
E = WhatToStore.
size();
I !=
E; ++
I) {
534 Value *TheBtCast = WhatToStore[
I];
536 TD->getTypeAllocSizeInBits(TheBtCast->
getType()) / 8;
542 new BitCastInst(BufferIdx, ArgPointer,
"PrintBuffPtrCast", Brnch);
547 if (
I + 1 ==
E && ArgCount + 1 == CI->getNumArgOperands())
550 nullptr, BufferIdx, BuffOffset,
"PrintBuffNextPtr", Brnch));
552 << *BufferIdx <<
'\n');
559 for (
auto CI : Printfs)
560 CI->eraseFromParent();
566 bool AMDGPUPrintfRuntimeBinding::runOnModule(
Module &M) {
575 for (
auto &U : PrintfFunction->uses()) {
576 if (
auto *CI = dyn_cast<CallInst>(U.getUser())) {
577 if (CI->isCallee(&U))
578 Printfs.push_back(CI);
585 if (
auto HostcallFunction = M.
getFunction(
"__ockl_hostcall_internal")) {
586 for (
auto &U : HostcallFunction->uses()) {
587 if (
auto *CI = dyn_cast<CallInst>(U.getUser())) {
589 CI,
"Cannot use both printf and hostcall in the same module");
595 auto DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
596 DT = DTWP ? &DTWP->getDomTree() :
nullptr;
598 return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
F);
601 return lowerPrintfForGpu(M, GetTLI);
A parsed version of the target data layout string in and methods for querying it. ...
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
A Module instance is used to store all the information related to an LLVM module. ...
static MDString * get(LLVMContext &Context, StringRef Str)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
void push_back(const T &Elt)
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
void addOperand(MDNode *M)
This class represents a function call, abstracting a target machine's calling convention.
Address space for global memory (RAT0, VTX0).
StringRef getAsCString() const
If this array is isCString(), then this method returns the array (without the trailing null byte) as ...
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
An efficient, type-erasing, non-owning reference to a callable.
This instruction constructs a fixed permutation of two input vectors.
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
LLVM_NODISCARD size_t find_last_of(char C, size_t From=npos) const
Find the last character in the string that is C, or npos if not found.
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
static IntegerType * getInt64Ty(LLVMContext &C)
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
static IntegerType * getInt16Ty(LLVMContext &C)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Value * CreateNot(Value *V, const Twine &Name="")
amdgpu printf runtime binding
ModulePass * createAMDGPUPrintfRuntimeBinding()
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
TypeID getTypeID() const
Return the type id for the type.
LLVMContext & getContext() const
Get the global data context.
constexpr char Printf[]
Key for HSA::Metadata::mPrintf.
A Use represents the edge between a Value definition and its users.
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
This class represents a cast from a pointer to an integer.
void emitError(unsigned LocCookie, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
Class to represent function types.
A constant value that is initialized with an expression using other constant values.
Type * getType() const
All values are typed, get the type of this value.
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
std::string itostr(int64_t X)
This class represents a no-op cast from one type to another.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
An instruction for storing to memory.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Value * getOperand(unsigned i) const
Class to represent pointers.
bool isZeroValue() const
Return true if the value is negative zero or null value.
11: Arbitrary bit width integers
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
char & AMDGPUPrintfRuntimeBindingID
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double, and whose elements are just simple data values (i.e.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
INITIALIZE_PASS_BEGIN(AMDGPUPrintfRuntimeBinding, "amdgpu-printf-runtime-binding", "AMDGPU Printf lowering", false, false) INITIALIZE_PASS_END(AMDGPUPrintfRuntimeBinding
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
void initializeAMDGPUPrintfRuntimeBindingPass(PassRegistry &)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
ConstantFP - Floating Point Values [float, double].
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
#define LLVM_LIBRARY_VISIBILITY
LLVM_LIBRARY_VISIBILITY - If a class marked with this attribute is linked into a shared library...
Class to represent integer types.
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Triple - Helper class for working with autoconf configuration names.
const APFloat & getValueAPF() const
static const fltSemantics & IEEEsingle() LLVM_READNONE
This is the shared class of boolean and integer constants.
16: SIMD 'packed' format, or other vector type
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
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.
Provides information about what library functions are available for the current target.
A constant pointer value that points to null.
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.
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Class to represent vector types.
Class for arbitrary precision integers.
iterator_range< user_iterator > users()
static IntegerType * getInt32Ty(LLVMContext &C)
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
LLVM_NODISCARD size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
LLVM Value Representation.
bool hasInitializer() const
Definitions have initializers, declarations don't.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
StringRef - Represent a constant reference to a string, i.e.
Legacy analysis pass which computes a DominatorTree.
This class represents an extension of floating point types.
amdgpu printf runtime AMDGPU Printf lowering
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
static IntegerType * getInt8Ty(LLVMContext &C)
static Constant * get(ArrayRef< Constant *> V)
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
Address space for constant memory (VTX2).
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
bool isString(unsigned CharSize=8) const
This method returns true if this is an array of CharSize integers.