36#define DEBUG_TYPE "printfToRuntime"
40class AMDGPUPrintfRuntimeBinding final :
public ModulePass {
45 explicit AMDGPUPrintfRuntimeBinding() :
ModulePass(
ID) {}
51class AMDGPUPrintfRuntimeBindingImpl {
53 AMDGPUPrintfRuntimeBindingImpl() =
default;
60 bool lowerPrintfForGpu(
Module &M);
67char AMDGPUPrintfRuntimeBinding::ID = 0;
70 "amdgpu-printf-runtime-binding",
"AMDGPU Printf lowering",
80 return new AMDGPUPrintfRuntimeBinding();
83void AMDGPUPrintfRuntimeBindingImpl::getConversionSpecifiers(
85 size_t NumOps)
const {
91 static const char ConvSpecifiers[] =
"cdieEfFgGaAosuxXp";
92 size_t CurFmtSpecifierIdx = 0;
93 size_t PrevFmtSpecifierIdx = 0;
99 CurFmtSpecifierIdx - PrevFmtSpecifierIdx);
103 while (pTag && CurFmt[--pTag] ==
'%') {
109 OpConvSpecifiers.
push_back(Fmt[CurFmtSpecifierIdx]);
111 PrevFmtSpecifierIdx = ++CurFmtSpecifierIdx;
116 return Specifier ==
's' && isa<PointerType>(OpType);
133 "printf format string must be a trivially resolved constant string "
138bool AMDGPUPrintfRuntimeBindingImpl::lowerPrintfForGpu(
Module &M) {
147 NamedMDNode *metaD =
M.getOrInsertNamedMetadata(
"llvm.printf.fmts");
150 for (
auto *CI : Printfs) {
151 unsigned NumOps = CI->arg_size();
154 Value *
Op = CI->getArgOperand(0);
158 Value *Stripped =
Op->stripPointerCasts();
159 if (!isa<UndefValue>(Stripped) && !isa<ConstantPointerNull>(Stripped))
166 getConversionSpecifiers(OpConvSpecifiers, FormatStr, NumOps - 1);
169 std::string AStreamHolder;
172 Sizes << CI->arg_size() - 1;
174 for (
unsigned ArgCount = 1;
175 ArgCount < CI->arg_size() && ArgCount <= OpConvSpecifiers.
size();
177 Value *Arg = CI->getArgOperand(ArgCount);
179 unsigned ArgSize = TD->getTypeAllocSize(ArgType);
186 if (
auto *VecType = dyn_cast<VectorType>(ArgType))
187 ResType = VectorType::get(ResType, VecType->getElementCount());
188 Builder.SetInsertPoint(CI);
189 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
192 Arg = Builder.CreateBitCast(
197 if (OpConvSpecifiers[ArgCount - 1] ==
'x' ||
198 OpConvSpecifiers[ArgCount - 1] ==
'X' ||
199 OpConvSpecifiers[ArgCount - 1] ==
'u' ||
200 OpConvSpecifiers[ArgCount - 1] ==
'o')
201 Arg = Builder.CreateZExt(Arg, ResType);
203 Arg = Builder.CreateSExt(Arg, ResType);
205 ArgSize = TD->getTypeAllocSize(ArgType);
206 CI->setOperand(ArgCount, Arg);
208 if (OpConvSpecifiers[ArgCount - 1] ==
'f') {
209 ConstantFP *FpCons = dyn_cast<ConstantFP>(Arg);
213 FPExtInst *FpExt = dyn_cast<FPExtInst>(Arg);
223 <<
" for type: " << *ArgType <<
'\n');
224 Sizes << ArgSize <<
':';
227 LLVM_DEBUG(
dbgs() <<
"Printf format string in source = " << FormatStr
229 for (
char C : FormatStr) {
263 Builder.SetInsertPoint(CI);
264 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
267 Attribute::NoUnwind);
271 Type *Tys_alloc[1] = {SizetTy};
273 Type *I8Ptr = PointerType::get(Ctx, 1);
274 FunctionType *FTy_alloc = FunctionType::get(I8Ptr, Tys_alloc,
false);
276 M.getOrInsertFunction(
StringRef(
"__printf_alloc"), FTy_alloc, Attr);
279 std::string fmtstr = itostr(++UniqID) +
":" +
Sizes.str();
284 Value *sumC = ConstantInt::get(SizetTy, Sum,
false);
288 "printf_alloc_fn", CI->getIterator());
297 auto *cmp = cast<ICmpInst>(Builder.CreateICmpNE(pcall, zeroIntPtr,
""));
298 if (!CI->use_empty()) {
300 Builder.CreateSExt(Builder.CreateNot(cmp), I32Ty,
"printf_res");
308 Builder.SetInsertPoint(Brnch);
313 I8Ty, pcall, ConstantInt::get(Ctx,
APInt(32, 0)),
"PrintBuffID",
318 new BitCastInst(BufferIdx, idPointer,
"PrintBuffIdCast", BrnchPoint);
320 new StoreInst(ConstantInt::get(I32Ty, UniqID), id_gep_cast, BrnchPoint);
325 ConstantInt::get(Ctx,
APInt(32, 4)),
326 "PrintBuffGep", BrnchPoint);
329 for (
unsigned ArgCount = 1;
330 ArgCount < CI->arg_size() && ArgCount <= OpConvSpecifiers.
size();
332 Value *Arg = CI->getArgOperand(ArgCount);
336 if (OpConvSpecifiers[ArgCount - 1] ==
'f') {
337 if (
auto *FpCons = dyn_cast<ConstantFP>(Arg)) {
340 Val.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
342 Arg = ConstantFP::get(Ctx, Val);
343 }
else if (
auto *FpExt = dyn_cast<FPExtInst>(Arg)) {
344 if (FpExt->getType()->isDoubleTy() &&
345 FpExt->getOperand(0)->getType()->isFloatTy()) {
346 Arg = FpExt->getOperand(0);
351 }
else if (isa<PointerType>(ArgType)) {
365 ReadBytes = Extractor.getU8(
Offset);
368 ReadBytes = Extractor.getU16(
Offset);
371 ReadBytes = Extractor.getU24(
Offset);
374 ReadBytes = Extractor.getU32(
Offset);
379 "failed to read bytes from constant array");
384 if (ReadNow < ReadSize)
388 WhatToStore.
push_back(ConstantInt::get(IntTy, IntVal));
392 Value *ANumV = ConstantInt::get(Int32Ty, 0xFFFFFF00,
false);
401 for (
unsigned I = 0, E = WhatToStore.
size();
I != E; ++
I) {
402 Value *TheBtCast = WhatToStore[
I];
403 unsigned ArgSize = TD->getTypeAllocSize(TheBtCast->
getType());
408 if (
I + 1 == E && ArgCount + 1 == CI->arg_size())
411 I8Ty, BufferIdx, {ConstantInt::get(I32Ty, ArgSize)},
412 "PrintBuffNextPtr", BrnchPoint);
414 << *BufferIdx <<
'\n');
420 for (
auto *CI : Printfs)
421 CI->eraseFromParent();
427bool AMDGPUPrintfRuntimeBindingImpl::run(
Module &M) {
432 auto *PrintfFunction =
M.getFunction(
"printf");
433 if (!PrintfFunction || !PrintfFunction->isDeclaration() ||
434 M.getModuleFlag(
"openmp"))
437 for (
auto &U : PrintfFunction->uses()) {
438 if (
auto *CI = dyn_cast<CallInst>(
U.getUser())) {
439 if (CI->isCallee(&U) && !CI->isNoBuiltin())
440 Printfs.push_back(CI);
447 TD = &
M.getDataLayout();
449 return lowerPrintfForGpu(M);
452bool AMDGPUPrintfRuntimeBinding::runOnModule(
Module &M) {
453 return AMDGPUPrintfRuntimeBindingImpl().run(M);
458 bool Changed = AMDGPUPrintfRuntimeBindingImpl().run(M);
static void diagnoseInvalidFormatString(const CallBase *CI)
amdgpu printf runtime AMDGPU Printf lowering
constexpr StringLiteral NonLiteralStr("???")
static StringRef getAsConstantStr(Value *V)
amdgpu printf runtime binding
static bool shouldPrintAsStr(char Specifier, Type *OpType)
Module.h This file contains the declarations for the Module class.
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Class for arbitrary precision integers.
A container for analyses that lazily runs them and caches their results.
static LLVM_ABI AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
InstListType::iterator iterator
Instruction iterators...
This class represents a no-op cast from one type to another.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
ConstantFP - Floating Point Values [float, double].
const APFloat & getValueAPF() const
A constant pointer value that points to null.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Diagnostic information for unsupported feature in backend.
Legacy analysis pass which computes a DominatorTree.
This class represents an extension of floating point types.
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
This is an important class for using LLVM in a threaded context.
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
virtual bool runOnModule(Module &M)=0
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
A Module instance is used to store all the information related to an LLVM module.
LLVM_ABI unsigned getNumOperands() const
LLVM_ABI void addOperand(MDNode *M)
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.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
StringRef - Represent a constant reference to a string, i.e.
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
constexpr bool empty() const
empty - Check if the string is empty.
constexpr size_t size() const
size - Get the string size.
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.
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.
static constexpr size_t npos
Triple - Helper class for working with autoconf configuration names.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
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.
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
const ParentTy * getParent() const
self_iterator getIterator()
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
char & AMDGPUPrintfRuntimeBindingID
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
ModulePass * createAMDGPUPrintfRuntimeBinding()
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)