26#define DEBUG_TYPE "amdgpu-emit-printf"
29 auto Int64Ty = Builder.getInt64Ty();
33 switch (IntTy->getBitWidth()) {
35 return Builder.CreateZExt(Arg, Int64Ty);
42 return Builder.CreateBitCast(Arg, Int64Ty);
46 return Builder.CreatePtrToInt(Arg, Int64Ty);
53 auto Int64Ty = Builder.getInt64Ty();
54 auto M = Builder.getModule();
55 auto Fn = M->getOrInsertFunction(
"__ockl_printf_begin", Int64Ty, Int64Ty);
56 return Builder.CreateCall(Fn, Version);
63 auto Int64Ty = Builder.getInt64Ty();
64 auto Int32Ty = Builder.getInt32Ty();
65 auto M = Builder.getModule();
66 auto Fn = M->getOrInsertFunction(
"__ockl_printf_append_args", Int64Ty,
67 Int64Ty, Int32Ty, Int64Ty, Int64Ty, Int64Ty,
68 Int64Ty, Int64Ty, Int64Ty, Int64Ty, Int32Ty);
69 auto IsLastValue = Builder.getInt32(IsLast);
70 auto NumArgsValue = Builder.getInt32(NumArgs);
71 return Builder.CreateCall(Fn, {
Desc, NumArgsValue, Arg0, Arg1, Arg2, Arg3,
72 Arg4, Arg5, Arg6, IsLastValue});
78 auto Zero = Builder.getInt64(0);
86 auto *Prev = Builder.GetInsertBlock();
87 Module *M = Prev->getModule();
89 auto CharZero = Builder.getInt8(0);
90 auto One = Builder.getInt64(1);
91 auto Zero = Builder.getInt64(0);
92 auto Int64Ty = Builder.getInt64Ty();
101 if (Prev->hasTerminator()) {
111 Prev->getParent(), Join);
113 M->getContext(),
"strlen.while.done",
114 Prev->getParent(), Join);
117 Builder.SetInsertPoint(Prev);
120 Builder.CreateCondBr(CmpNull, Join, While);
123 Builder.SetInsertPoint(While);
125 auto PtrPhi = Builder.CreatePHI(Str->getType(), 2);
126 PtrPhi->addIncoming(Str, Prev);
127 auto PtrNext = Builder.CreateGEP(Builder.getInt8Ty(), PtrPhi, One);
128 PtrPhi->addIncoming(PtrNext, While);
131 auto Data = Builder.CreateLoad(Builder.getInt8Ty(), PtrPhi);
132 auto Cmp = Builder.CreateICmpEQ(
Data, CharZero);
133 Builder.CreateCondBr(Cmp, WhileDone, While);
136 Builder.SetInsertPoint(WhileDone->
begin());
137 auto Len = Builder.CreatePtrDiff(PtrPhi, Str);
138 Len = Builder.CreateZExt(Len, Int64Ty);
139 Len = Builder.CreateAdd(Len, One);
143 Builder.SetInsertPoint(Join->
begin());
144 auto LenPhi = Builder.CreatePHI(Len->getType(), 2);
145 LenPhi->addIncoming(Len, WhileDone);
146 LenPhi->addIncoming(Zero, Prev);
153 auto Int64Ty = Builder.getInt64Ty();
154 auto IsLastInt32 = Builder.getInt32(isLast);
155 auto M = Builder.getModule();
156 auto Fn = M->getOrInsertFunction(
"__ockl_printf_append_string_n", Int64Ty,
157 Desc->getType(), Str->getType(),
158 Length->getType(), IsLastInt32->getType());
159 return Builder.CreateCall(Fn, {
Desc, Str,
Length, IsLastInt32});
169 bool SpecIsCString,
bool IsLast) {
197 Module *M = Builder.getModule();
198 Value *NonConstStrLen =
nullptr;
199 Value *LenWithNull =
nullptr;
200 Value *LenWithNullAligned =
nullptr;
201 Value *TempAdd =
nullptr;
212 TempAdd = Builder.CreateAdd(LenWithNull,
213 ConstantInt::get(LenWithNull->
getType(), 7U));
214 NonConstStrLen = Builder.CreateAnd(
215 TempAdd, ConstantInt::get(LenWithNull->
getType(), ~7U));
221 for (
size_t i = 1; i < Args.size(); i++) {
222 if (SpecIsCString.
test(i)) {
228 nullptr,
nullptr,
true));
229 BufSize += alignedLen;
234 TempAdd = Builder.CreateAdd(
235 LenWithNull, ConstantInt::get(LenWithNull->
getType(), 7U));
236 LenWithNullAligned = Builder.CreateAnd(
237 TempAdd, ConstantInt::get(LenWithNull->
getType(), ~7U));
239 if (NonConstStrLen) {
240 auto Val = Builder.CreateAdd(LenWithNullAligned, NonConstStrLen,
242 NonConstStrLen = Val;
244 NonConstStrLen = LenWithNullAligned;
250 int AllocSize = M->getDataLayout().getTypeAllocSize(Args[i]->
getType());
253 BufSize += std::max(AllocSize, 8);
258 Value *SizeToReserve = ConstantInt::get(Builder.getInt64Ty(), BufSize,
false);
261 SizeToReserve = Builder.CreateAdd(NonConstStrLen, SizeToReserve);
263 ArgSize = Builder.CreateTrunc(SizeToReserve, Builder.getInt32Ty());
268 Builder.getContext(), AttributeList::FunctionIndex, Attribute::NoUnwind);
270 Type *Tys_alloc[1] = {Builder.getInt32Ty()};
272 Builder.getPtrTy(M->getDataLayout().getDefaultGlobalsAddressSpace());
275 M->getOrInsertFunction(
StringRef(
"__printf_alloc"), FTy_alloc, Attr);
277 return Builder.CreateCall(PrintfAllocFn, Alloc_args,
"printf_alloc_fn");
286 WhatToStore.
push_back(Builder.getInt32(Word));
294 if (IntTy->getBitWidth() < 64) {
295 return Builder.CreateZExt(Arg, Builder.getInt64Ty());
299 if (Ty->isFloatingPointTy()) {
300 if (
DL.getTypeAllocSize(Ty) < 8) {
301 return Builder.CreateFPExt(Arg, Builder.getDoubleTy());
312 bool IsConstFmtStr) {
313 Module *M = Builder.getModule();
315 auto StrIt = StringContents.
begin();
316 size_t i = IsConstFmtStr ? 1 : 0;
317 for (; i < Args.size(); i++) {
319 if ((i == 0) || SpecIsCString.
test(i)) {
320 if (StrIt->IsConst) {
329 Builder.CreateMemCpy(PtrToStore,
Align(1), Args[i],
330 Args[i]->getPointerAlignment(
DL),
334 Builder.CreateInBoundsGEP(Builder.getInt8Ty(), PtrToStore,
335 {StrIt->AlignedSize},
"PrintBuffNextPtr");
337 << *PtrToStore <<
'\n');
347 for (
Value *toStore : WhatToStore) {
348 StoreInst *StBuff = Builder.CreateStore(toStore, PtrToStore);
349 LLVM_DEBUG(
dbgs() <<
"inserting store to printf buffer:" << *StBuff
352 PtrToStore = Builder.CreateConstInBoundsGEP1_32(
353 Builder.getInt8Ty(), PtrToStore,
354 M->getDataLayout().getTypeAllocSize(toStore->getType()),
356 LLVM_DEBUG(
dbgs() <<
"inserting gep to the printf buffer:" << *PtrToStore
364 auto NumOps = Args.size();
376 Module *M = Builder.getModule();
378 auto Int8Ty = Builder.getInt8Ty();
379 auto Int32Ty = Builder.getInt32Ty();
380 bool IsConstFmtStr = !FmtStr.
empty();
382 Value *ArgSize =
nullptr;
385 SpecIsCString, StringContents, ArgSize);
392 auto *Cmp =
cast<ICmpInst>(Builder.CreateICmpNE(Ptr, zeroIntPtr,
""));
395 Builder.GetInsertBlock()->getParent());
397 Ctx,
"argpush.block", Builder.GetInsertBlock()->getParent());
400 Builder.SetInsertPoint(ArgPush);
406 auto ConstantTwo = Builder.getInt32(2);
407 auto ControlDWord = Builder.CreateShl(ArgSize, ConstantTwo);
409 ControlDWord = Builder.CreateOr(ControlDWord, ConstantTwo);
411 Builder.CreateStore(ControlDWord, Ptr);
413 Ptr = Builder.CreateConstInBoundsGEP1_32(Int8Ty, Ptr, 4);
417 NamedMDNode *metaD = M->getOrInsertNamedMetadata(
"llvm.printf.fmts");
426 Ptr = Builder.CreateConstInBoundsGEP1_32(Int8Ty, Ptr, 8);
445 Builder.SetInsertPoint(
End);
446 return Builder.CreateSExt(Builder.CreateNot(Cmp), Int32Ty,
"printf_result");
455 for (
unsigned int i = 1; i !=
NumOps; ++i) {
456 bool IsLast = i ==
NumOps - 1;
457 bool IsCString = SpecIsCString.
test(i);
461 return Builder.CreateTrunc(
Desc, Builder.getInt32Ty());
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static Value * appendString(IRBuilder<> &Builder, Value *Desc, Value *Arg, bool IsLast)
static void callBufferedPrintfArgPush(IRBuilder<> &Builder, ArrayRef< Value * > Args, Value *PtrToStore, SparseBitVector< 8 > &SpecIsCString, SmallVectorImpl< StringData > &StringContents, bool IsConstFmtStr)
static void processConstantStringArg(StringData *SD, IRBuilder<> &Builder, SmallVectorImpl< Value * > &WhatToStore)
static Value * callBufferedPrintfStart(IRBuilder<> &Builder, ArrayRef< Value * > Args, Value *Fmt, bool isConstFmtStr, SparseBitVector< 8 > &SpecIsCString, SmallVectorImpl< StringData > &StringContents, Value *&ArgSize)
static Value * callAppendArgs(IRBuilder<> &Builder, Value *Desc, int NumArgs, Value *Arg0, Value *Arg1, Value *Arg2, Value *Arg3, Value *Arg4, Value *Arg5, Value *Arg6, bool IsLast)
static Value * callPrintfBegin(IRBuilder<> &Builder, Value *Version)
static Value * fitArgInto64Bits(IRBuilder<> &Builder, Value *Arg)
static Value * callAppendStringN(IRBuilder<> &Builder, Value *Desc, Value *Str, Value *Length, bool isLast)
static Value * appendArg(IRBuilder<> &Builder, Value *Desc, Value *Arg, bool IsLast)
static Value * processNonStringArg(Value *Arg, IRBuilder<> &Builder)
static Value * processArg(IRBuilder<> &Builder, Value *Desc, Value *Arg, bool SpecIsCString, bool IsLast)
static Value * getStrlenWithNull(IRBuilder<> &Builder, Value *Str)
Helpers for the AMDGPU printf runtime interface, shared by the lowerings of printf calls on the AMDGP...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Module.h This file contains the declarations for the Module class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
This file defines the SparseBitVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
A constant pointer value that points to null.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
This is an important class for using LLVM in a threaded context.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
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)
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.
bool test(unsigned Idx) const
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
The instances of the Type class are immutable: once they are created, they are never changed.
@ DoubleTyID
64-bit floating point type
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
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.
LLVM_ABI std::string getAMDGPUPrintfFormatMetadata(StringRef Fmt)
Returns the llvm.printf.fmts entry that maps the ID of the constant format string Fmt back to the str...
LLVM_ABI Value * emitAMDGPUPrintfCall(IRBuilder<> &Builder, ArrayRef< Value * > Args, bool isBuffered)
LLVM_ABI uint64_t getAMDGPUPrintfFormatHash(StringRef Fmt)
Returns the ID that buffered printf stores in place of the constant format string Fmt the low 64 bits...
LLVM_ABI void locateAMDGPUPrintfCStrings(SparseBitVector< 8 > &BV, StringRef Fmt)
Marks the printf arguments that the format string Fmt specifies as strings, i.e.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI void packAMDGPUPrintfConstantString(StringRef Str, SmallVectorImpl< uint32_t > &Words)
Splits the constant string argument Str, including its terminating NUL, into the little-endian 32-bit...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
@ End
Run the machine verifier once, at the end of the pipeline.
constexpr StringLiteral AMDGPUPrintfNonConstFormatMetadata
The llvm.printf.fmts entry added when a module only uses buffered printf with non-constant format str...
StringData(StringRef ST, Value *RS, Value *AS, bool IC)
This struct is a compact representation of a valid (non-zero power of two) alignment.