https://github.com/steffenlarsen updated https://github.com/llvm/llvm-project/pull/238287
>From 53afc36fa983ce8a18a2033cf8e7f6a954f6ce28 Mon Sep 17 00:00:00 2001 From: Steffen Holst Larsen <[email protected]> Date: Tue, 3 Nov 2026 05:21:53 -0600 Subject: [PATCH 1/3] [clang][HIP] Disallow non-constant format string with pointer argument Disallow non-constant format string with pointer argument in HIP printf. This is to avoid wrong behavior when the lowering finds a %s specifier in a non-constant format string. Signed-off-by: Steffen Holst Larsen <[email protected]> --- .../clang/Basic/DiagnosticFrontendKinds.td | 4 +++ clang/lib/CodeGen/CGGPUBuiltin.cpp | 17 ++++++++++ .../printf-nonconst-fmt-ptr-arg.cpp | 32 +++++++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 clang/test/CodeGenHIP/printf-nonconst-fmt-ptr-arg.cpp diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index b51aa3ff0a0cb4..1c21ea392e61f8 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -546,6 +546,10 @@ def err_open_hotpatch_file_failed def err_codegen_unsupported : Error<"cannot compile this %0 yet">; +def err_amdgpu_printf_nonconst_fmt_with_ptr_arg + : Error<"AMDGPU printf requires a constant format string when pointer " + "arguments are passed">; + def warn_trivial_auto_var_limit : Warning<"-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit " "the number of times ftrivial-auto-var-init=%1 gets applied">, diff --git a/clang/lib/CodeGen/CGGPUBuiltin.cpp b/clang/lib/CodeGen/CGGPUBuiltin.cpp index 327a317a1e78ed..6a6f0e2d976d10 100644 --- a/clang/lib/CodeGen/CGGPUBuiltin.cpp +++ b/clang/lib/CodeGen/CGGPUBuiltin.cpp @@ -13,6 +13,8 @@ #include "CodeGenFunction.h" #include "clang/Basic/Builtins.h" +#include "clang/Basic/DiagnosticFrontend.h" +#include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/Instruction.h" #include "llvm/Transforms/Utils/AMDGPUEmitPrintf.h" @@ -181,6 +183,21 @@ RValue CodeGenFunction::EmitAMDGPUDevicePrintfCallExpr(const CallExpr *E) { Args.push_back(Arg); } + // The lowering can only find %s specifiers in a constant format string, so + // with a non-constant format a string argument would cause wrong behavior. + // Instead we reject it. + StringRef FmtStr; + if (!llvm::getConstantStringInfo(Args[0], FmtStr)) { + for (unsigned I = 1, NumArgs = Args.size(); I < NumArgs; ++I) { + if (Args[I]->getType()->isPointerTy()) { + CGM.getDiags().Report(E->getArg(0)->getExprLoc(), + diag::err_amdgpu_printf_nonconst_fmt_with_ptr_arg) + << E->getArg(I)->getSourceRange(); + return RValue::get(llvm::ConstantInt::getAllOnesValue(IntTy)); + } + } + } + llvm::IRBuilder<> IRB(Builder.GetInsertPoint()); IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation()); diff --git a/clang/test/CodeGenHIP/printf-nonconst-fmt-ptr-arg.cpp b/clang/test/CodeGenHIP/printf-nonconst-fmt-ptr-arg.cpp new file mode 100644 index 00000000000000..50a93b57da0eb2 --- /dev/null +++ b/clang/test/CodeGenHIP/printf-nonconst-fmt-ptr-arg.cpp @@ -0,0 +1,32 @@ +// REQUIRES: amdgpu-registered-target, spirv-registered-target +// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -x hip -fcuda-is-device \ +// RUN: -Wno-format-security -verify -emit-llvm-only %s +// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -x hip -fcuda-is-device \ +// RUN: -mprintf-kind=buffered -Wno-format-security -verify -emit-llvm-only %s +// RUN: %clang_cc1 -triple spirv64-amd-amdhsa -x hip -fcuda-is-device \ +// RUN: -Wno-format-security -verify -emit-llvm-only %s +// RUN: %clang_cc1 -triple spirv64-amd-amdhsa -x hip -fcuda-is-device \ +// RUN: -mprintf-kind=buffered -Wno-format-security -verify -emit-llvm-only %s + +// The %s specifiers can only be found in a constant format string, so a +// non-constant format string is rejected if any argument is a pointer. + +#define __device__ __attribute__((device)) +extern "C" __device__ int printf(const char *format, ...); + +__device__ void NonConstFmtNoPtrArgs(const char *fmt) { + printf(fmt); + printf(fmt, 1, 2.0, 'c'); +} + +__device__ void ConstFmtPtrArgs(const char *s, int *p) { + printf("%s %p\n", s, p); +} + +// CodeGen stops emitting functions after the first error, so all error cases +// share the last function. +__device__ void NonConstFmtPtrArgs(const char *fmt, const char *s, int *p) { + printf(fmt, s); // expected-error {{AMDGPU printf requires a constant format string when pointer arguments are passed}} + printf(fmt, 1, p); // expected-error {{AMDGPU printf requires a constant format string when pointer arguments are passed}} + printf(fmt, nullptr); // expected-error {{AMDGPU printf requires a constant format string when pointer arguments are passed}} +} >From 4f34a1659606e75e1a93ac52cc2a68167767c071 Mon Sep 17 00:00:00 2001 From: Steffen Holst Larsen <[email protected]> Date: Tue, 3 Nov 2026 08:54:41 -0600 Subject: [PATCH 2/3] Move check to Sema Signed-off-by: Steffen Holst Larsen <[email protected]> --- .../clang/Basic/DiagnosticFrontendKinds.td | 4 - .../clang/Basic/DiagnosticSemaKinds.td | 3 + clang/lib/CodeGen/CGGPUBuiltin.cpp | 17 ----- clang/lib/Sema/SemaChecking.cpp | 33 ++++++++ .../printf-nonconst-fmt-ptr-arg.cpp | 32 -------- .../amdgpu-printf-nonconst-fmt-ptr-arg.hip | 76 +++++++++++++++++++ 6 files changed, 112 insertions(+), 53 deletions(-) delete mode 100644 clang/test/CodeGenHIP/printf-nonconst-fmt-ptr-arg.cpp create mode 100644 clang/test/SemaHIP/amdgpu-printf-nonconst-fmt-ptr-arg.hip diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index 1c21ea392e61f8..b51aa3ff0a0cb4 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -546,10 +546,6 @@ def err_open_hotpatch_file_failed def err_codegen_unsupported : Error<"cannot compile this %0 yet">; -def err_amdgpu_printf_nonconst_fmt_with_ptr_arg - : Error<"AMDGPU printf requires a constant format string when pointer " - "arguments are passed">; - def warn_trivial_auto_var_limit : Warning<"-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit " "the number of times ftrivial-auto-var-init=%1 gets applied">, diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index 56cc9721781063..2b3b64a2992ad9 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -9895,6 +9895,9 @@ def note_cuda_device_builtin_surftex_should_be_template_class : Note< def err_hip_invalid_args_builtin_mangled_name : Error< "invalid argument: symbol must be a device-side function or global variable">; +def err_amdgpu_printf_nonconst_fmt_with_ptr_arg + : Error<"AMDGPU printf requires a constant format string when pointer " + "arguments are passed">; def warn_hip_omp_target_directives : Warning< "HIP does not support OpenMP target directives; directive has been ignored">, diff --git a/clang/lib/CodeGen/CGGPUBuiltin.cpp b/clang/lib/CodeGen/CGGPUBuiltin.cpp index 6a6f0e2d976d10..327a317a1e78ed 100644 --- a/clang/lib/CodeGen/CGGPUBuiltin.cpp +++ b/clang/lib/CodeGen/CGGPUBuiltin.cpp @@ -13,8 +13,6 @@ #include "CodeGenFunction.h" #include "clang/Basic/Builtins.h" -#include "clang/Basic/DiagnosticFrontend.h" -#include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/Instruction.h" #include "llvm/Transforms/Utils/AMDGPUEmitPrintf.h" @@ -183,21 +181,6 @@ RValue CodeGenFunction::EmitAMDGPUDevicePrintfCallExpr(const CallExpr *E) { Args.push_back(Arg); } - // The lowering can only find %s specifiers in a constant format string, so - // with a non-constant format a string argument would cause wrong behavior. - // Instead we reject it. - StringRef FmtStr; - if (!llvm::getConstantStringInfo(Args[0], FmtStr)) { - for (unsigned I = 1, NumArgs = Args.size(); I < NumArgs; ++I) { - if (Args[I]->getType()->isPointerTy()) { - CGM.getDiags().Report(E->getArg(0)->getExprLoc(), - diag::err_amdgpu_printf_nonconst_fmt_with_ptr_arg) - << E->getArg(I)->getSourceRange(); - return RValue::get(llvm::ConstantInt::getAllOnesValue(IntTy)); - } - } - } - llvm::IRBuilder<> IRB(Builder.GetInsertPoint()); IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation()); diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index 406f03a17f7ebe..7172b4fa0dba2d 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -65,6 +65,7 @@ #include "clang/Sema/SemaAMDGPU.h" #include "clang/Sema/SemaARM.h" #include "clang/Sema/SemaBPF.h" +#include "clang/Sema/SemaCUDA.h" #include "clang/Sema/SemaDirectX.h" #include "clang/Sema/SemaHLSL.h" #include "clang/Sema/SemaHexagon.h" @@ -2499,6 +2500,34 @@ checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, return false; } +/// The AMDGPU printf lowering can only find %s specifiers in a format string +/// known at compile time, so with any other format a string argument would be +/// printed as its address. Any pointer argument may be a string, so reject it. +static void checkAMDGPUDevicePrintf(Sema &S, CallExpr *TheCall) { + const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); + if (!S.getLangOpts().HIP || + !(TT.isAMDGCN() || (TT.isSPIRV() && TT.getVendor() == llvm::Triple::AMD))) + return; + if (TheCall->getNumArgs() < 2 || TheCall->isValueDependent() || + TheCall->isTypeDependent()) + return; + + auto PtrArg = + llvm::find_if(llvm::drop_begin(TheCall->arguments()), [](const Expr *E) { + return E->getType()->isPointerType(); + }); + if (PtrArg == TheCall->arg_end()) + return; + + const Expr *Fmt = TheCall->getArg(0); + if (Fmt->tryEvaluateString(S.Context)) + return; + + S.CUDA().DiagIfDeviceCode(Fmt->getExprLoc(), + diag::err_amdgpu_printf_nonconst_fmt_with_ptr_arg) + << (*PtrArg)->getSourceRange(); +} + /// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *). /// This checks that the target supports the builtin and that the string /// argument is constant and valid. @@ -3203,6 +3232,10 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, << Context.BuiltinInfo.getQuotedName(BuiltinID) << "__safestack_get_unsafe_stack_ptr"; break; + case Builtin::BIprintf: + case Builtin::BI__builtin_printf: + checkAMDGPUDevicePrintf(*this, TheCall); + break; case Builtin::BI__builtin_cpu_supports: case Builtin::BI__builtin_cpu_is: if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall, diff --git a/clang/test/CodeGenHIP/printf-nonconst-fmt-ptr-arg.cpp b/clang/test/CodeGenHIP/printf-nonconst-fmt-ptr-arg.cpp deleted file mode 100644 index 50a93b57da0eb2..00000000000000 --- a/clang/test/CodeGenHIP/printf-nonconst-fmt-ptr-arg.cpp +++ /dev/null @@ -1,32 +0,0 @@ -// REQUIRES: amdgpu-registered-target, spirv-registered-target -// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -x hip -fcuda-is-device \ -// RUN: -Wno-format-security -verify -emit-llvm-only %s -// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -x hip -fcuda-is-device \ -// RUN: -mprintf-kind=buffered -Wno-format-security -verify -emit-llvm-only %s -// RUN: %clang_cc1 -triple spirv64-amd-amdhsa -x hip -fcuda-is-device \ -// RUN: -Wno-format-security -verify -emit-llvm-only %s -// RUN: %clang_cc1 -triple spirv64-amd-amdhsa -x hip -fcuda-is-device \ -// RUN: -mprintf-kind=buffered -Wno-format-security -verify -emit-llvm-only %s - -// The %s specifiers can only be found in a constant format string, so a -// non-constant format string is rejected if any argument is a pointer. - -#define __device__ __attribute__((device)) -extern "C" __device__ int printf(const char *format, ...); - -__device__ void NonConstFmtNoPtrArgs(const char *fmt) { - printf(fmt); - printf(fmt, 1, 2.0, 'c'); -} - -__device__ void ConstFmtPtrArgs(const char *s, int *p) { - printf("%s %p\n", s, p); -} - -// CodeGen stops emitting functions after the first error, so all error cases -// share the last function. -__device__ void NonConstFmtPtrArgs(const char *fmt, const char *s, int *p) { - printf(fmt, s); // expected-error {{AMDGPU printf requires a constant format string when pointer arguments are passed}} - printf(fmt, 1, p); // expected-error {{AMDGPU printf requires a constant format string when pointer arguments are passed}} - printf(fmt, nullptr); // expected-error {{AMDGPU printf requires a constant format string when pointer arguments are passed}} -} diff --git a/clang/test/SemaHIP/amdgpu-printf-nonconst-fmt-ptr-arg.hip b/clang/test/SemaHIP/amdgpu-printf-nonconst-fmt-ptr-arg.hip new file mode 100644 index 00000000000000..5ba429f831c08d --- /dev/null +++ b/clang/test/SemaHIP/amdgpu-printf-nonconst-fmt-ptr-arg.hip @@ -0,0 +1,76 @@ +// REQUIRES: amdgpu-registered-target, spirv-registered-target, nvptx-registered-target, x86-registered-target +// RUN: %clang_cc1 -triple amdgpu9.0a-amd-amdhsa -x hip -fcuda-is-device \ +// RUN: -Wno-format-security -fsyntax-only -verify %s +// RUN: %clang_cc1 -triple spirv64-amd-amdhsa -x hip -fcuda-is-device \ +// RUN: -Wno-format-security -fsyntax-only -verify %s +// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -x hip \ +// RUN: -Wno-format-security -fsyntax-only -verify=none %s +// RUN: %clang_cc1 -triple nvptx64-nvidia-cuda -x hip -fcuda-is-device \ +// RUN: -Wno-format-security -fsyntax-only -verify=none %s +// RUN: %clang_cc1 -triple amdgpu9.0a-amd-amdhsa -x hip -fcuda-is-device \ +// RUN: -fno-builtin-printf -Wno-format-security -fsyntax-only -verify=nobuiltin %s + +// none-no-diagnostics + +// The AMDGPU printf lowering can only find %s specifiers in a format string +// known at compile time, so a pointer argument requires such a format. + +#define __device__ __attribute__((device)) +#define __host__ __attribute__((host)) +#define __global__ __attribute__((global)) + +extern "C" __host__ __device__ int printf(const char *format, ...); + +__device__ void NonConstFmtPtrArgs(const char *fmt, const char *s, int *p) { + printf(fmt, s); // expected-error {{AMDGPU printf requires a constant format string when pointer arguments are passed}} + printf(fmt, 1, p); // expected-error {{AMDGPU printf requires a constant format string when pointer arguments are passed}} + printf(fmt, nullptr); // expected-error {{AMDGPU printf requires a constant format string when pointer arguments are passed}} + // -fno-builtin-printf only affects printf, not __builtin_printf. + __builtin_printf(fmt, s); // expected-error {{AMDGPU printf requires a constant format string when pointer arguments are passed}} \ + // nobuiltin-error {{AMDGPU printf requires a constant format string when pointer arguments are passed}} +} + +__device__ void NonConstFmtNoPtrArgs(const char *fmt) { + printf(fmt); + printf(fmt, 1, 2.0, 'c'); +} + +__device__ const char DeviceFmt[] = "%s\n"; +__device__ constexpr char ConstexprFmt[] = "x%s\n"; + +__device__ void ConstFmtPtrArgs(const char *s, int *p) { + constexpr const char LocalFmt[] = "%s\n"; + printf("%s %p\n", s, p); + printf(LocalFmt, s); + printf(DeviceFmt, s); + printf(ConstexprFmt + 1, s); +} + +__host__ void HostOnly(const char *fmt, const char *s) { + printf(fmt, s); +} + +inline __host__ __device__ void HostDeviceUnused(const char *fmt, const char *s) { + printf(fmt, s); +} + +inline __host__ __device__ void HostDeviceUsed(const char *fmt, const char *s) { + printf(fmt, s); // expected-error {{AMDGPU printf requires a constant format string when pointer arguments are passed}} +} + +__global__ void Kernel(const char *fmt, const char *s) { + HostDeviceUsed(fmt, s); // expected-note {{called by 'Kernel'}} +} + +template <typename T> __device__ void TypeDependentFmt(T fmt, const char *s) { + printf(fmt, s); // expected-error {{AMDGPU printf requires a constant format string when pointer arguments are passed}} +} + +template <const char *Fmt> __device__ void ValueDependentFmt(const char *s) { + printf(Fmt, s); +} + +__device__ void Instantiate(const char *fmt, const char *s) { + TypeDependentFmt(fmt, s); // expected-note {{in instantiation of function template specialization 'TypeDependentFmt<const char *>' requested here}} + ValueDependentFmt<ConstexprFmt>(s); +} >From aaf9fca353511c25bb581dc132af9de280dd6f4b Mon Sep 17 00:00:00 2001 From: Steffen Holst Larsen <[email protected]> Date: Mon, 9 Nov 2026 06:59:19 -0600 Subject: [PATCH 3/3] Exclude unevaluated exprs Signed-off-by: Steffen Holst Larsen <[email protected]> --- clang/lib/Sema/SemaChecking.cpp | 2 +- .../SemaHIP/amdgpu-printf-nonconst-fmt-ptr-arg.hip | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index 7172b4fa0dba2d..0bc272dc5f86f4 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -2509,7 +2509,7 @@ static void checkAMDGPUDevicePrintf(Sema &S, CallExpr *TheCall) { !(TT.isAMDGCN() || (TT.isSPIRV() && TT.getVendor() == llvm::Triple::AMD))) return; if (TheCall->getNumArgs() < 2 || TheCall->isValueDependent() || - TheCall->isTypeDependent()) + TheCall->isTypeDependent() || S.isUnevaluatedContext()) return; auto PtrArg = diff --git a/clang/test/SemaHIP/amdgpu-printf-nonconst-fmt-ptr-arg.hip b/clang/test/SemaHIP/amdgpu-printf-nonconst-fmt-ptr-arg.hip index 5ba429f831c08d..c739d0e9bc02cb 100644 --- a/clang/test/SemaHIP/amdgpu-printf-nonconst-fmt-ptr-arg.hip +++ b/clang/test/SemaHIP/amdgpu-printf-nonconst-fmt-ptr-arg.hip @@ -35,6 +35,18 @@ __device__ void NonConstFmtNoPtrArgs(const char *fmt) { printf(fmt, 1, 2.0, 'c'); } +// An unevaluated printf is never called, so it is not lowered. +__device__ void UnevaluatedNonConstFmtPtrArgs(const char *fmt, const char *s) { + (void)sizeof(printf(fmt, s)); + using T = decltype(printf(fmt, s)); + (void)noexcept(printf(fmt, s)); +} + +template <typename T> +__device__ void UnevaluatedTypeDependentFmt(T fmt, const char *s) { + (void)sizeof(printf(fmt, s)); +} + __device__ const char DeviceFmt[] = "%s\n"; __device__ constexpr char ConstexprFmt[] = "x%s\n"; @@ -73,4 +85,5 @@ template <const char *Fmt> __device__ void ValueDependentFmt(const char *s) { __device__ void Instantiate(const char *fmt, const char *s) { TypeDependentFmt(fmt, s); // expected-note {{in instantiation of function template specialization 'TypeDependentFmt<const char *>' requested here}} ValueDependentFmt<ConstexprFmt>(s); + UnevaluatedTypeDependentFmt(fmt, s); } _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
