1//===- AMDGPUEmitPrintf.cpp -----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Utility function to lower a printf call into a series of device
10// library calls on the AMDGPU target.
11//
12// WARNING: This file knows about certain library functions. It recognizes them
13// by name, and hardwires knowledge of their semantics.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/Transforms/Utils/AMDGPUEmitPrintf.h"
18#include "llvm/ADT/SparseBitVector.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/Analysis/ValueTracking.h"
21#include "llvm/IR/Module.h"
22#include "llvm/Support/DataExtractor.h"
23#include "llvm/Support/MD5.h"
24#include "llvm/Support/MathExtras.h"
25
26using namespace llvm;
27
28#define DEBUG_TYPE "amdgpu-emit-printf"
29
30static Value *fitArgInto64Bits(IRBuilder<> &Builder, Value *Arg) {
31 auto Int64Ty = Builder.getInt64Ty();
32 auto Ty = Arg->getType();
33
34 if (auto IntTy = dyn_cast<IntegerType>(Val: Ty)) {
35 switch (IntTy->getBitWidth()) {
36 case 32:
37 return Builder.CreateZExt(V: Arg, DestTy: Int64Ty);
38 case 64:
39 return Arg;
40 }
41 }
42
43 if (Ty->getTypeID() == Type::DoubleTyID) {
44 return Builder.CreateBitCast(V: Arg, DestTy: Int64Ty);
45 }
46
47 if (isa<PointerType>(Val: Ty)) {
48 return Builder.CreatePtrToInt(V: Arg, DestTy: Int64Ty);
49 }
50
51 llvm_unreachable("unexpected type");
52}
53
54static Value *callPrintfBegin(IRBuilder<> &Builder, Value *Version) {
55 auto Int64Ty = Builder.getInt64Ty();
56 auto M = Builder.GetInsertBlock()->getModule();
57 auto Fn = M->getOrInsertFunction(Name: "__ockl_printf_begin", RetTy: Int64Ty, Args: Int64Ty);
58 return Builder.CreateCall(Callee: Fn, Args: Version);
59}
60
61static Value *callAppendArgs(IRBuilder<> &Builder, Value *Desc, int NumArgs,
62 Value *Arg0, Value *Arg1, Value *Arg2, Value *Arg3,
63 Value *Arg4, Value *Arg5, Value *Arg6,
64 bool IsLast) {
65 auto Int64Ty = Builder.getInt64Ty();
66 auto Int32Ty = Builder.getInt32Ty();
67 auto M = Builder.GetInsertBlock()->getModule();
68 auto Fn = M->getOrInsertFunction(Name: "__ockl_printf_append_args", RetTy: Int64Ty,
69 Args: Int64Ty, Args: Int32Ty, Args: Int64Ty, Args: Int64Ty, Args: Int64Ty,
70 Args: Int64Ty, Args: Int64Ty, Args: Int64Ty, Args: Int64Ty, Args: Int32Ty);
71 auto IsLastValue = Builder.getInt32(C: IsLast);
72 auto NumArgsValue = Builder.getInt32(C: NumArgs);
73 return Builder.CreateCall(Callee: Fn, Args: {Desc, NumArgsValue, Arg0, Arg1, Arg2, Arg3,
74 Arg4, Arg5, Arg6, IsLastValue});
75}
76
77static Value *appendArg(IRBuilder<> &Builder, Value *Desc, Value *Arg,
78 bool IsLast) {
79 auto Arg0 = fitArgInto64Bits(Builder, Arg);
80 auto Zero = Builder.getInt64(C: 0);
81 return callAppendArgs(Builder, Desc, NumArgs: 1, Arg0, Arg1: Zero, Arg2: Zero, Arg3: Zero, Arg4: Zero, Arg5: Zero,
82 Arg6: Zero, IsLast);
83}
84
85// The device library does not provide strlen, so we build our own loop
86// here. While we are at it, we also include the terminating null in the length.
87static Value *getStrlenWithNull(IRBuilder<> &Builder, Value *Str) {
88 auto *Prev = Builder.GetInsertBlock();
89 Module *M = Prev->getModule();
90
91 auto CharZero = Builder.getInt8(C: 0);
92 auto One = Builder.getInt64(C: 1);
93 auto Zero = Builder.getInt64(C: 0);
94 auto Int64Ty = Builder.getInt64Ty();
95
96 // The length is either zero for a null pointer, or the computed value for an
97 // actual string. We need a join block for a phi that represents the final
98 // value.
99 //
100 // Strictly speaking, the zero does not matter since
101 // __ockl_printf_append_string_n ignores the length if the pointer is null.
102 BasicBlock *Join = nullptr;
103 if (Prev->getTerminator()) {
104 Join = Prev->splitBasicBlock(I: Builder.GetInsertPoint(),
105 BBName: "strlen.join");
106 Prev->getTerminator()->eraseFromParent();
107 } else {
108 Join = BasicBlock::Create(Context&: M->getContext(), Name: "strlen.join",
109 Parent: Prev->getParent());
110 }
111 BasicBlock *While =
112 BasicBlock::Create(Context&: M->getContext(), Name: "strlen.while",
113 Parent: Prev->getParent(), InsertBefore: Join);
114 BasicBlock *WhileDone = BasicBlock::Create(
115 Context&: M->getContext(), Name: "strlen.while.done",
116 Parent: Prev->getParent(), InsertBefore: Join);
117
118 // Emit an early return for when the pointer is null.
119 Builder.SetInsertPoint(Prev);
120 auto CmpNull =
121 Builder.CreateICmpEQ(LHS: Str, RHS: Constant::getNullValue(Ty: Str->getType()));
122 BranchInst::Create(IfTrue: Join, IfFalse: While, Cond: CmpNull, InsertBefore: Prev);
123
124 // Entry to the while loop.
125 Builder.SetInsertPoint(While);
126
127 auto PtrPhi = Builder.CreatePHI(Ty: Str->getType(), NumReservedValues: 2);
128 PtrPhi->addIncoming(V: Str, BB: Prev);
129 auto PtrNext = Builder.CreateGEP(Ty: Builder.getInt8Ty(), Ptr: PtrPhi, IdxList: One);
130 PtrPhi->addIncoming(V: PtrNext, BB: While);
131
132 // Condition for the while loop.
133 auto Data = Builder.CreateLoad(Ty: Builder.getInt8Ty(), Ptr: PtrPhi);
134 auto Cmp = Builder.CreateICmpEQ(LHS: Data, RHS: CharZero);
135 Builder.CreateCondBr(Cond: Cmp, True: WhileDone, False: While);
136
137 // Add one to the computed length.
138 Builder.SetInsertPoint(TheBB: WhileDone, IP: WhileDone->begin());
139 auto Len = Builder.CreatePtrDiff(LHS: PtrPhi, RHS: Str);
140 Len = Builder.CreateZExt(V: Len, DestTy: Int64Ty);
141 Len = Builder.CreateAdd(LHS: Len, RHS: One);
142
143 // Final join.
144 BranchInst::Create(IfTrue: Join, InsertBefore: WhileDone);
145 Builder.SetInsertPoint(TheBB: Join, IP: Join->begin());
146 auto LenPhi = Builder.CreatePHI(Ty: Len->getType(), NumReservedValues: 2);
147 LenPhi->addIncoming(V: Len, BB: WhileDone);
148 LenPhi->addIncoming(V: Zero, BB: Prev);
149
150 return LenPhi;
151}
152
153static Value *callAppendStringN(IRBuilder<> &Builder, Value *Desc, Value *Str,
154 Value *Length, bool isLast) {
155 auto Int64Ty = Builder.getInt64Ty();
156 auto IsLastInt32 = Builder.getInt32(C: isLast);
157 auto M = Builder.GetInsertBlock()->getModule();
158 auto Fn = M->getOrInsertFunction(Name: "__ockl_printf_append_string_n", RetTy: Int64Ty,
159 Args: Desc->getType(), Args: Str->getType(),
160 Args: Length->getType(), Args: IsLastInt32->getType());
161 return Builder.CreateCall(Callee: Fn, Args: {Desc, Str, Length, IsLastInt32});
162}
163
164static Value *appendString(IRBuilder<> &Builder, Value *Desc, Value *Arg,
165 bool IsLast) {
166 auto Length = getStrlenWithNull(Builder, Str: Arg);
167 return callAppendStringN(Builder, Desc, Str: Arg, Length, isLast: IsLast);
168}
169
170static Value *processArg(IRBuilder<> &Builder, Value *Desc, Value *Arg,
171 bool SpecIsCString, bool IsLast) {
172 if (SpecIsCString && isa<PointerType>(Val: Arg->getType())) {
173 return appendString(Builder, Desc, Arg, IsLast);
174 }
175 // If the format specifies a string but the argument is not, the frontend will
176 // have printed a warning. We just rely on undefined behaviour and send the
177 // argument anyway.
178 return appendArg(Builder, Desc, Arg, IsLast);
179}
180
181// Scan the format string to locate all specifiers, and mark the ones that
182// specify a string, i.e, the "%s" specifier with optional '*' characters.
183static void locateCStrings(SparseBitVector<8> &BV, StringRef Str) {
184 static const char ConvSpecifiers[] = "diouxXfFeEgGaAcspn";
185 size_t SpecPos = 0;
186 // Skip the first argument, the format string.
187 unsigned ArgIdx = 1;
188
189 while ((SpecPos = Str.find_first_of(C: '%', From: SpecPos)) != StringRef::npos) {
190 if (Str[SpecPos + 1] == '%') {
191 SpecPos += 2;
192 continue;
193 }
194 auto SpecEnd = Str.find_first_of(Chars: ConvSpecifiers, From: SpecPos);
195 if (SpecEnd == StringRef::npos)
196 return;
197 auto Spec = Str.slice(Start: SpecPos, End: SpecEnd + 1);
198 ArgIdx += Spec.count(C: '*');
199 if (Str[SpecEnd] == 's') {
200 BV.set(ArgIdx);
201 }
202 SpecPos = SpecEnd + 1;
203 ++ArgIdx;
204 }
205}
206
207// helper struct to package the string related data
208struct StringData {
209 StringRef Str;
210 Value *RealSize = nullptr;
211 Value *AlignedSize = nullptr;
212 bool IsConst = true;
213
214 StringData(StringRef ST, Value *RS, Value *AS, bool IC)
215 : Str(ST), RealSize(RS), AlignedSize(AS), IsConst(IC) {}
216};
217
218// Calculates frame size required for current printf expansion and allocates
219// space on printf buffer. Printf frame includes following contents
220// [ ControlDWord , format string/Hash , Arguments (each aligned to 8 byte) ]
221static Value *callBufferedPrintfStart(
222 IRBuilder<> &Builder, ArrayRef<Value *> Args, Value *Fmt,
223 bool isConstFmtStr, SparseBitVector<8> &SpecIsCString,
224 SmallVectorImpl<StringData> &StringContents, Value *&ArgSize) {
225 Module *M = Builder.GetInsertBlock()->getModule();
226 Value *NonConstStrLen = nullptr;
227 Value *LenWithNull = nullptr;
228 Value *LenWithNullAligned = nullptr;
229 Value *TempAdd = nullptr;
230
231 // First 4 bytes to be reserved for control dword
232 size_t BufSize = 4;
233 if (isConstFmtStr)
234 // First 8 bytes of MD5 hash
235 BufSize += 8;
236 else {
237 LenWithNull = getStrlenWithNull(Builder, Str: Fmt);
238
239 // Align the computed length to next 8 byte boundary
240 TempAdd = Builder.CreateAdd(LHS: LenWithNull,
241 RHS: ConstantInt::get(Ty: LenWithNull->getType(), V: 7U));
242 NonConstStrLen = Builder.CreateAnd(
243 LHS: TempAdd, RHS: ConstantInt::get(Ty: LenWithNull->getType(), V: ~7U));
244
245 StringContents.push_back(
246 Elt: StringData(StringRef(), LenWithNull, NonConstStrLen, false));
247 }
248
249 for (size_t i = 1; i < Args.size(); i++) {
250 if (SpecIsCString.test(Idx: i)) {
251 StringRef ArgStr;
252 if (getConstantStringInfo(V: Args[i], Str&: ArgStr)) {
253 auto alignedLen = alignTo(Value: ArgStr.size() + 1, Align: 8);
254 StringContents.push_back(Elt: StringData(
255 ArgStr,
256 /*RealSize*/ nullptr, /*AlignedSize*/ nullptr, /*IsConst*/ true));
257 BufSize += alignedLen;
258 } else {
259 LenWithNull = getStrlenWithNull(Builder, Str: Args[i]);
260
261 // Align the computed length to next 8 byte boundary
262 TempAdd = Builder.CreateAdd(
263 LHS: LenWithNull, RHS: ConstantInt::get(Ty: LenWithNull->getType(), V: 7U));
264 LenWithNullAligned = Builder.CreateAnd(
265 LHS: TempAdd, RHS: ConstantInt::get(Ty: LenWithNull->getType(), V: ~7U));
266
267 if (NonConstStrLen) {
268 auto Val = Builder.CreateAdd(LHS: LenWithNullAligned, RHS: NonConstStrLen,
269 Name: "cumulativeAdd");
270 NonConstStrLen = Val;
271 } else
272 NonConstStrLen = LenWithNullAligned;
273
274 StringContents.push_back(
275 Elt: StringData(StringRef(), LenWithNull, LenWithNullAligned, false));
276 }
277 } else {
278 int AllocSize = M->getDataLayout().getTypeAllocSize(Ty: Args[i]->getType());
279 // We end up expanding non string arguments to 8 bytes
280 // (args smaller than 8 bytes)
281 BufSize += std::max(a: AllocSize, b: 8);
282 }
283 }
284
285 // calculate final size value to be passed to printf_alloc
286 Value *SizeToReserve = ConstantInt::get(Ty: Builder.getInt64Ty(), V: BufSize, IsSigned: false);
287 SmallVector<Value *, 1> Alloc_args;
288 if (NonConstStrLen)
289 SizeToReserve = Builder.CreateAdd(LHS: NonConstStrLen, RHS: SizeToReserve);
290
291 ArgSize = Builder.CreateTrunc(V: SizeToReserve, DestTy: Builder.getInt32Ty());
292 Alloc_args.push_back(Elt: ArgSize);
293
294 // call the printf_alloc function
295 AttributeList Attr = AttributeList::get(
296 C&: Builder.getContext(), Index: AttributeList::FunctionIndex, Kinds: Attribute::NoUnwind);
297
298 Type *Tys_alloc[1] = {Builder.getInt32Ty()};
299 Type *PtrTy =
300 Builder.getPtrTy(AddrSpace: M->getDataLayout().getDefaultGlobalsAddressSpace());
301 FunctionType *FTy_alloc = FunctionType::get(Result: PtrTy, Params: Tys_alloc, isVarArg: false);
302 auto PrintfAllocFn =
303 M->getOrInsertFunction(Name: StringRef("__printf_alloc"), T: FTy_alloc, AttributeList: Attr);
304
305 return Builder.CreateCall(Callee: PrintfAllocFn, Args: Alloc_args, Name: "printf_alloc_fn");
306}
307
308// Prepare constant string argument to push onto the buffer
309static void processConstantStringArg(StringData *SD, IRBuilder<> &Builder,
310 SmallVectorImpl<Value *> &WhatToStore) {
311 std::string Str(SD->Str.str() + '\0');
312
313 DataExtractor Extractor(Str, /*IsLittleEndian=*/true, 8);
314 DataExtractor::Cursor Offset(0);
315 while (Offset && Offset.tell() < Str.size()) {
316 const uint64_t ReadSize = 4;
317 uint64_t ReadNow = std::min(a: ReadSize, b: Str.size() - Offset.tell());
318 uint64_t ReadBytes = 0;
319 switch (ReadNow) {
320 default:
321 llvm_unreachable("min(4, X) > 4?");
322 case 1:
323 ReadBytes = Extractor.getU8(C&: Offset);
324 break;
325 case 2:
326 ReadBytes = Extractor.getU16(C&: Offset);
327 break;
328 case 3:
329 ReadBytes = Extractor.getU24(C&: Offset);
330 break;
331 case 4:
332 ReadBytes = Extractor.getU32(C&: Offset);
333 break;
334 }
335 cantFail(Err: Offset.takeError(), Msg: "failed to read bytes from constant array");
336
337 APInt IntVal(8 * ReadSize, ReadBytes);
338
339 // TODO: Should not bother aligning up.
340 if (ReadNow < ReadSize)
341 IntVal = IntVal.zext(width: 8 * ReadSize);
342
343 Type *IntTy = Type::getIntNTy(C&: Builder.getContext(), N: IntVal.getBitWidth());
344 WhatToStore.push_back(Elt: ConstantInt::get(Ty: IntTy, V: IntVal));
345 }
346 // Additional padding for 8 byte alignment
347 int Rem = (Str.size() % 8);
348 if (Rem > 0 && Rem <= 4)
349 WhatToStore.push_back(Elt: ConstantInt::get(Ty: Builder.getInt32Ty(), V: 0));
350}
351
352static Value *processNonStringArg(Value *Arg, IRBuilder<> &Builder) {
353 const DataLayout &DL = Builder.GetInsertBlock()->getDataLayout();
354 auto Ty = Arg->getType();
355
356 if (auto IntTy = dyn_cast<IntegerType>(Val: Ty)) {
357 if (IntTy->getBitWidth() < 64) {
358 return Builder.CreateZExt(V: Arg, DestTy: Builder.getInt64Ty());
359 }
360 }
361
362 if (Ty->isFloatingPointTy()) {
363 if (DL.getTypeAllocSize(Ty) < 8) {
364 return Builder.CreateFPExt(V: Arg, DestTy: Builder.getDoubleTy());
365 }
366 }
367
368 return Arg;
369}
370
371static void
372callBufferedPrintfArgPush(IRBuilder<> &Builder, ArrayRef<Value *> Args,
373 Value *PtrToStore, SparseBitVector<8> &SpecIsCString,
374 SmallVectorImpl<StringData> &StringContents,
375 bool IsConstFmtStr) {
376 Module *M = Builder.GetInsertBlock()->getModule();
377 const DataLayout &DL = M->getDataLayout();
378 auto StrIt = StringContents.begin();
379 size_t i = IsConstFmtStr ? 1 : 0;
380 for (; i < Args.size(); i++) {
381 SmallVector<Value *, 32> WhatToStore;
382 if ((i == 0) || SpecIsCString.test(Idx: i)) {
383 if (StrIt->IsConst) {
384 processConstantStringArg(SD: StrIt, Builder, WhatToStore);
385 StrIt++;
386 } else {
387 // This copies the contents of the string, however the next offset
388 // is at aligned length, the extra space that might be created due
389 // to alignment padding is not populated with any specific value
390 // here. This would be safe as long as runtime is sync with
391 // the offsets.
392 Builder.CreateMemCpy(Dst: PtrToStore, /*DstAlign*/ Align(1), Src: Args[i],
393 /*SrcAlign*/ Args[i]->getPointerAlignment(DL),
394 Size: StrIt->RealSize);
395
396 PtrToStore =
397 Builder.CreateInBoundsGEP(Ty: Builder.getInt8Ty(), Ptr: PtrToStore,
398 IdxList: {StrIt->AlignedSize}, Name: "PrintBuffNextPtr");
399 LLVM_DEBUG(dbgs() << "inserting gep to the printf buffer:"
400 << *PtrToStore << '\n');
401
402 // done with current argument, move to next
403 StrIt++;
404 continue;
405 }
406 } else {
407 WhatToStore.push_back(Elt: processNonStringArg(Arg: Args[i], Builder));
408 }
409
410 for (Value *toStore : WhatToStore) {
411 StoreInst *StBuff = Builder.CreateStore(Val: toStore, Ptr: PtrToStore);
412 LLVM_DEBUG(dbgs() << "inserting store to printf buffer:" << *StBuff
413 << '\n');
414 (void)StBuff;
415 PtrToStore = Builder.CreateConstInBoundsGEP1_32(
416 Ty: Builder.getInt8Ty(), Ptr: PtrToStore,
417 Idx0: M->getDataLayout().getTypeAllocSize(Ty: toStore->getType()),
418 Name: "PrintBuffNextPtr");
419 LLVM_DEBUG(dbgs() << "inserting gep to the printf buffer:" << *PtrToStore
420 << '\n');
421 }
422 }
423}
424
425Value *llvm::emitAMDGPUPrintfCall(IRBuilder<> &Builder, ArrayRef<Value *> Args,
426 bool IsBuffered) {
427 auto NumOps = Args.size();
428 assert(NumOps >= 1);
429
430 auto Fmt = Args[0];
431 SparseBitVector<8> SpecIsCString;
432 StringRef FmtStr;
433
434 if (getConstantStringInfo(V: Fmt, Str&: FmtStr))
435 locateCStrings(BV&: SpecIsCString, Str: FmtStr);
436
437 if (IsBuffered) {
438 SmallVector<StringData, 8> StringContents;
439 Module *M = Builder.GetInsertBlock()->getModule();
440 LLVMContext &Ctx = Builder.getContext();
441 auto Int8Ty = Builder.getInt8Ty();
442 auto Int32Ty = Builder.getInt32Ty();
443 bool IsConstFmtStr = !FmtStr.empty();
444
445 Value *ArgSize = nullptr;
446 Value *Ptr =
447 callBufferedPrintfStart(Builder, Args, Fmt, isConstFmtStr: IsConstFmtStr,
448 SpecIsCString, StringContents, ArgSize);
449
450 // The buffered version still follows OpenCL printf standards for
451 // printf return value, i.e 0 on success, -1 on failure.
452 ConstantPointerNull *zeroIntPtr =
453 ConstantPointerNull::get(T: cast<PointerType>(Val: Ptr->getType()));
454
455 auto *Cmp = cast<ICmpInst>(Val: Builder.CreateICmpNE(LHS: Ptr, RHS: zeroIntPtr, Name: ""));
456
457 BasicBlock *End = BasicBlock::Create(Context&: Ctx, Name: "end.block",
458 Parent: Builder.GetInsertBlock()->getParent());
459 BasicBlock *ArgPush = BasicBlock::Create(
460 Context&: Ctx, Name: "argpush.block", Parent: Builder.GetInsertBlock()->getParent());
461
462 BranchInst::Create(IfTrue: ArgPush, IfFalse: End, Cond: Cmp, InsertBefore: Builder.GetInsertBlock());
463 Builder.SetInsertPoint(ArgPush);
464
465 // Create controlDWord and store as the first entry, format as follows
466 // Bit 0 (LSB) -> stream (1 if stderr, 0 if stdout, printf always outputs to
467 // stdout) Bit 1 -> constant format string (1 if constant) Bits 2-31 -> size
468 // of printf data frame
469 auto ConstantTwo = Builder.getInt32(C: 2);
470 auto ControlDWord = Builder.CreateShl(LHS: ArgSize, RHS: ConstantTwo);
471 if (IsConstFmtStr)
472 ControlDWord = Builder.CreateOr(LHS: ControlDWord, RHS: ConstantTwo);
473
474 Builder.CreateStore(Val: ControlDWord, Ptr);
475
476 Ptr = Builder.CreateConstInBoundsGEP1_32(Ty: Int8Ty, Ptr, Idx0: 4);
477
478 // Create MD5 hash for costant format string, push low 64 bits of the
479 // same onto buffer and metadata.
480 NamedMDNode *metaD = M->getOrInsertNamedMetadata(Name: "llvm.printf.fmts");
481 if (IsConstFmtStr) {
482 MD5 Hasher;
483 MD5::MD5Result Hash;
484 Hasher.update(Str: FmtStr);
485 Hasher.final(Result&: Hash);
486
487 // Try sticking to llvm.printf.fmts format, although we are not going to
488 // use the ID and argument size fields while printing,
489 std::string MetadataStr =
490 "0:0:" + llvm::utohexstr(X: Hash.low(), /*LowerCase=*/true) + "," +
491 FmtStr.str();
492 MDString *fmtStrArray = MDString::get(Context&: Ctx, Str: MetadataStr);
493 MDNode *myMD = MDNode::get(Context&: Ctx, MDs: fmtStrArray);
494 metaD->addOperand(M: myMD);
495
496 Builder.CreateStore(Val: Builder.getInt64(C: Hash.low()), Ptr);
497 Ptr = Builder.CreateConstInBoundsGEP1_32(Ty: Int8Ty, Ptr, Idx0: 8);
498 } else {
499 // Include a dummy metadata instance in case of only non constant
500 // format string usage, This might be an absurd usecase but needs to
501 // be done for completeness
502 if (metaD->getNumOperands() == 0) {
503 MDString *fmtStrArray =
504 MDString::get(Context&: Ctx, Str: "0:0:ffffffff,\"Non const format string\"");
505 MDNode *myMD = MDNode::get(Context&: Ctx, MDs: fmtStrArray);
506 metaD->addOperand(M: myMD);
507 }
508 }
509
510 // Push The printf arguments onto buffer
511 callBufferedPrintfArgPush(Builder, Args, PtrToStore: Ptr, SpecIsCString, StringContents,
512 IsConstFmtStr);
513
514 // End block, returns -1 on failure
515 BranchInst::Create(IfTrue: End, InsertBefore: ArgPush);
516 Builder.SetInsertPoint(End);
517 return Builder.CreateSExt(V: Builder.CreateNot(V: Cmp), DestTy: Int32Ty, Name: "printf_result");
518 }
519
520 auto Desc = callPrintfBegin(Builder, Version: Builder.getIntN(N: 64, C: 0));
521 Desc = appendString(Builder, Desc, Arg: Fmt, IsLast: NumOps == 1);
522
523 // FIXME: This invokes hostcall once for each argument. We can pack up to
524 // seven scalar printf arguments in a single hostcall. See the signature of
525 // callAppendArgs().
526 for (unsigned int i = 1; i != NumOps; ++i) {
527 bool IsLast = i == NumOps - 1;
528 bool IsCString = SpecIsCString.test(Idx: i);
529 Desc = processArg(Builder, Desc, Arg: Args[i], SpecIsCString: IsCString, IsLast);
530 }
531
532 return Builder.CreateTrunc(V: Desc, DestTy: Builder.getInt32Ty());
533}
534