Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions clang/docs/LanguageExtensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -4366,6 +4366,15 @@ the SYCL kernel and emits a stable local ordering of the respective lambdas.
The resulting pattern is demanglable. When non-lambda types are passed to the
builtin, the mangler emits their usual pattern without any special treatment.

To prevent name collisions across translation units, names of types that are
only guaranteed to be unique within their translation unit, but not necessarily
across multiple translation units (for example, a type in an unnamed namespace,
or a lambda in a function with internal linkage) are given a vendor-extended
type qualifier containing a hash of the compilation unit ID, if one is provided
with `-cuid=`: For example, `_ZTS<type>` becomes
`_ZTSU<length>cuid_<hash><type>`, where `<hash>` is the hexadecimal MD5 hash of
the `-cuid=` value.

**Syntax**:

```c
Expand Down
14 changes: 14 additions & 0 deletions clang/include/clang/AST/Expr.h
Original file line number Diff line number Diff line change
Expand Up @@ -2223,6 +2223,20 @@ class SYCLUniqueStableNameExpr final : public Expr {
// Get the generated name of the type. Note that this only works after all
// kernels have been instantiated.
static std::string ComputeName(ASTContext &Context, QualType Ty);

// If \p Ty is only guaranteed to be unique within its own TU (it is not
// externally visible, and not declared in an externally visible function) and
// a compilation unit ID (-cuid) is provided, insert a vendor-extended
// qualifier containing a hash of the CUID into the Itanium typeinfo name
// \p TypeName ("_ZTS..."), such that the resulting name is unique across
// translation units. Otherwise, \p TypeName is left unchanged.
//
// This is necessary since kernels do not keep internal linkage: Without
// being able to distinguish mangled names between TUs, TU-local entities
// across separate TUs may end up with the same mangled name, causing
// conflicts at device code link time.
static void maybeAddCUIDQualifier(const ASTContext &Context, QualType Ty,
std::string &TypeName);
};

class SYCLUniqueStableIdExpr final : public Expr {
Expand Down
33 changes: 33 additions & 0 deletions clang/lib/AST/Expr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -617,9 +617,42 @@ std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context,
llvm::raw_string_ostream Out(Buffer);
Ctx->mangleCanonicalTypeName(Ty, Out);

maybeAddCUIDQualifier(Context, Ty, Buffer);
return Buffer;
}

void SYCLUniqueStableNameExpr::maybeAddCUIDQualifier(const ASTContext &Context,
QualType Ty,
std::string &TypeName) {
StringRef CUIDHash = Context.getCUIDHash();
if (CUIDHash.empty() || isExternallyVisible(Ty->getLinkage()))
return;

// A type declared inside a function is mangled relative to that function,
// so its name is already unique across the program if the enclosing function
// is externally visible, and no CUID is needed.
if (const TagDecl *TD = Ty->getAsTagDecl())
if (const DeclContext *DC = TD->getParentFunctionOrMethod())
if (const auto *FD =
dyn_cast_or_null<FunctionDecl>(DC->getNonClosureAncestor());
FD && FD->isExternallyVisible())
return;

constexpr StringRef TypeInfoPrefix = "_ZTS";
if (!StringRef(TypeName).starts_with(TypeInfoPrefix))
return;

// Insert a vendor-extended qualifier with CUID hash to distinguish between
// entities with internal linkage across different TUs:
//
// _ZTS<type> -> _ZTSU<length>cuid_<hash><type>
//
// We don't use a '.' suffix since ptxas rejects identifiers containing '.'.
std::string Qualifier = ("cuid_" + CUIDHash).str();
TypeName.insert(TypeInfoPrefix.size(),
"U" + std::to_string(Qualifier.size()) + Qualifier);
}

SYCLUniqueStableIdExpr::SYCLUniqueStableIdExpr(EmptyShell Empty,
QualType ResultTy)
: Expr(SYCLUniqueStableIdExprClass, ResultTy, VK_PRValue, OK_Ordinary) {}
Expand Down
2 changes: 2 additions & 0 deletions clang/lib/Sema/SemaSYCL.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1320,6 +1320,8 @@ constructKernelName(SemaSYCL &S, const FunctionDecl *KernelCallerFunc,

MC.mangleCanonicalTypeName(KernelNameType, Out);
std::string MangledName(Out.str());
SYCLUniqueStableNameExpr::maybeAddCUIDQualifier(S.getASTContext(),
KernelNameType, MangledName);

std::string StableName =
SYCLUniqueStableNameExpr::ComputeName(S.getASTContext(), KernelNameType);
Expand Down
201 changes: 201 additions & 0 deletions clang/test/CodeGenSYCL/kernel_name_cuid.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
// The MD5-derived hash of `-cuid=abc` (see ASTContext::getCUIDHash):
// DEFINE: %{hash} = b04fd23c98500190
//
// RUN: %clang_cc1 -fsycl-is-device -fsycl-unnamed-lambda \
// RUN: -internal-isystem %S/Inputs -triple spir64-unknown-unknown -cuid=abc \
// RUN: -fsycl-int-header=%t.h -emit-llvm %s -o - \
// RUN: | FileCheck %s --check-prefix=DEVICE -DHASH=%{hash}
// RUN: FileCheck %s --input-file=%t.h --check-prefix=INT-HEADER -DHASH=%{hash}
// RUN: %clang_cc1 -fsycl-is-host -fsycl-unnamed-lambda \
// RUN: -internal-isystem %S/Inputs -triple x86_64-unknown-linux-gnu \
// RUN: -cuid=abc -emit-llvm %s -o - \
// RUN: | FileCheck %s --check-prefix=HOST -DHASH=%{hash}
// RUN: %clang_cc1 -fsycl-is-device -fsycl-unnamed-lambda \
// RUN: -internal-isystem %S/Inputs -triple spir64-unknown-unknown \
// RUN: -fsycl-int-header=%t.nocuid.h -emit-llvm %s -o - \
// RUN: | FileCheck %s --check-prefix=NOCUID --implicit-check-not=cuid_
// RUN: FileCheck %s --input-file=%t.nocuid.h --check-prefix=NOCUID \
// RUN: --implicit-check-not=cuid_
// RUN: %clang_cc1 -fsycl-is-host -fsycl-unnamed-lambda \
// RUN: -internal-isystem %S/Inputs -triple x86_64-unknown-linux-gnu \
// RUN: -emit-llvm %s -o - \
// RUN: | FileCheck %s --check-prefix=HOST-NOCUID --implicit-check-not=cuid_

// Verify that with `-cuid`, mangled names of TU-local kernels have a per-TU
// compilation unit ID inserted into them, to prevent TU-local kernels with
// identical mangled names from silently merging at device link time.

#include "sycl.hpp"

// Used here to expose strings computed by __builtin_sycl_unique_stable_name:
extern "C" int puts(const char *);

static void staticUnnamed(sycl::queue &q) {
// Unnamed kernel in a function with internal linkage:
auto k = [] {};
q.submit([&](sycl::handler &h) { h.single_task(k); });
// Compute k's kernel name as SYCL headers would do on host, in order to
// find the kernel by name later:
puts(__builtin_sycl_unique_stable_name(decltype(k)));
// Host, device, and integration header all need to agree:
// DEVICE-DAG: define {{.*}}spir_kernel void @_ZTSU21cuid_[[HASH]]ZL13staticUnnamedRN4sycl3_V15queueEEUlvE_(
// INT-HEADER-DAG: getName() { return "_ZTSU21cuid_[[HASH]]ZL13staticUnnamedRN4sycl3_V15queueEEUlvE_"; }
// INT-HEADER-DAG: struct KernelInfoData<'_', 'Z', 'T', 'S', 'U', '2', '1', 'c', 'u', 'i', 'd', '_',
// HOST-DAG: c"_ZTSU21cuid_[[HASH]]ZL13staticUnnamedRN4sycl3_V15queueEEUlvE_\00"
// HOST-NOCUID-DAG: c"_ZTSZL13staticUnnamedRN4sycl3_V15queueEEUlvE_\00"
}

void extUnnamed(sycl::queue &q) {
// Unnamed kernel in an externally visible function, don't add CUID:
auto k = [] {};
q.submit([&](sycl::handler &h) { h.single_task(k); });
puts(__builtin_sycl_unique_stable_name(decltype(k)));
// DEVICE-DAG: define {{.*}}spir_kernel void @_ZTSZ10extUnnamedRN4sycl3_V15queueEEUlvE_(
// INT-HEADER-DAG: getName() { return "_ZTSZ10extUnnamedRN4sycl3_V15queueEEUlvE_"; }
// HOST-DAG: c"_ZTSZ10extUnnamedRN4sycl3_V15queueEEUlvE_\00"

// Unnamed kernel nested in a command group lambda: even if it's nested
// deeper, since extUnnamed is still externally visible, we don't need a CUID
// here either:
q.submit([&](sycl::handler &h) { h.single_task([] {}); });
// DEVICE-DAG: define {{.*}}spir_kernel void @_ZTSZZ10extUnnamedRN4sycl3_V15queueEENKUlRNS0_7handlerEE0_clES4_EUlvE_(
// INT-HEADER-DAG: getName() { return "_ZTSZZ10extUnnamedRN4sycl3_V15queueEENKUlRNS0_7handlerEE0_clES4_EUlvE_"; }
// No HOST check here: the nested lambda's type can only be named inside the
// command group, which the mock queue::submit never invokes, so nothing
// inside it is emitted on host.

}

inline void inlineFn(sycl::queue &q) {
// Unnamed kernel in an inline function, which should be the same kernel in
// every TU that includes it, so don't add CUID:
auto k = [] {};
q.submit([&](sycl::handler &h) { h.single_task(k); });
puts(__builtin_sycl_unique_stable_name(decltype(k)));
// DEVICE-DAG: define {{.*}}spir_kernel void @_ZTSZ8inlineFnRN4sycl3_V15queueEEUlvE_(
// INT-HEADER-DAG: getName() { return "_ZTSZ8inlineFnRN4sycl3_V15queueEEUlvE_"; }
// HOST-DAG: c"_ZTSZ8inlineFnRN4sycl3_V15queueEEUlvE_\00"
}

namespace {
struct AnonFunc { void operator()() const {} };
} // namespace

struct ExtFunc { void operator()() const {} };

void funcObjects(sycl::queue &q) {
// Unnamed kernel given as a function object whose type is in an unnamed
// namespace:
q.submit([&](sycl::handler &h) { h.single_task(AnonFunc{}); });
puts(__builtin_sycl_unique_stable_name(AnonFunc));
// DEVICE-DAG: define {{.*}}spir_kernel void @_ZTSU21cuid_[[HASH]]N12_GLOBAL__N_18AnonFuncE(
// INT-HEADER-DAG: getName() { return "_ZTSU21cuid_[[HASH]]N12_GLOBAL__N_18AnonFuncE"; }
// HOST-DAG: c"_ZTSU21cuid_[[HASH]]N12_GLOBAL__N_18AnonFuncE\00"
// NOCUID-DAG: _ZTSN12_GLOBAL__N_18AnonFuncE

// This time the function object is externally visible, so don't add CUID:
q.submit([&](sycl::handler &h) { h.single_task(ExtFunc{}); });
puts(__builtin_sycl_unique_stable_name(ExtFunc));
// DEVICE-DAG: define {{.*}}spir_kernel void @_ZTS7ExtFunc(
// INT-HEADER-DAG: getName() { return "_ZTS7ExtFunc"; }
// HOST-DAG: c"_ZTS7ExtFunc\00"
}

// Kernel names declared in place are local to the function that submits the
// kernel, so they are only TU-local when their parent functions are.
static void staticNamed(sycl::queue &q) {
// Enclosing function has internal linkage:
q.submit([&](sycl::handler &h) { h.single_task<class K>([] {}); });
// DEVICE-DAG: define {{.*}}spir_kernel void @_ZTSU21cuid_[[HASH]]ZZL11staticNamedRN4sycl3_V15queueEENKUlRNS0_7handlerEE_clES4_E1K(
// INT-HEADER-DAG: getName() { return "_ZTSU21cuid_[[HASH]]ZZL11staticNamedRN4sycl3_V15queueEENKUlRNS0_7handlerEE_clES4_E1K"; }
// NOCUID-DAG: _ZTSZZL11staticNamedRN4sycl3_V15queueEENKUlRNS0_7handlerEE_clES4_E1K
}

void extNamed(sycl::queue &q) {
// Enclosing function is externally visible, so don't add CUID:
q.submit([&](sycl::handler &h) { h.single_task<class K>([] {}); });
// DEVICE-DAG: define {{.*}}spir_kernel void @_ZTSZZ8extNamedRN4sycl3_V15queueEENKUlRNS0_7handlerEE_clES4_E1K(
// INT-HEADER-DAG: getName() { return "_ZTSZZ8extNamedRN4sycl3_V15queueEENKUlRNS0_7handlerEE_clES4_E1K"; }
}

namespace {
struct Anonymous {};
} // namespace
struct External {};

template <typename T> class KTmpl;

template <typename T> void templateFn(sycl::queue &q) {
auto k = [] {};
q.submit([&](sycl::handler &h) { h.single_task(k); });
puts(__builtin_sycl_unique_stable_name(decltype(k)));

// If instantiated with a type in an unnamed namespace
// (templateFn<Anonymous>), add CUID: Otherwise another TU doing the same with
// its own 'Anonymous' would get the same name and get silently dropped at
// device link time.
// DEVICE-DAG: define {{.*}}spir_kernel void @_ZTSU21cuid_[[HASH]]Z10templateFnIN12_GLOBAL__N_19AnonymousEEvRN4sycl3_V15queueEEUlvE_(
// INT-HEADER-DAG: getName() { return "_ZTSU21cuid_[[HASH]]Z10templateFnIN12_GLOBAL__N_19AnonymousEEvRN4sycl3_V15queueEEUlvE_"; }
// HOST-DAG: c"_ZTSU21cuid_[[HASH]]Z10templateFnIN12_GLOBAL__N_19AnonymousEEvRN4sycl3_V15queueEEUlvE_\00"
// Don't add CUID if we don't have -cuid:
// NOCUID-DAG: _ZTSZ10templateFnIN12_GLOBAL__N_19AnonymousEEvRN4sycl3_V15queueEEUlvE_

// The same template instantiated with an externally visible type
// (templateFn<External>) is the same kernel in every TU, so don't add CUID:
// DEVICE-DAG: define {{.*}}spir_kernel void @_ZTSZ10templateFnI8ExternalEvRN4sycl3_V15queueEEUlvE_(
// INT-HEADER-DAG: getName() { return "_ZTSZ10templateFnI8ExternalEvRN4sycl3_V15queueEEUlvE_"; }
// HOST-DAG: c"_ZTSZ10templateFnI8ExternalEvRN4sycl3_V15queueEEUlvE_\00"

// Same for an explicit kernel name that is a template specialization:
q.submit([&](sycl::handler &h) { h.single_task<KTmpl<T>>([] {}); });
puts(__builtin_sycl_unique_stable_name(KTmpl<T>));

// With templateFn<Anonymous>:
// DEVICE-DAG: define {{.*}}spir_kernel void @_ZTSU21cuid_[[HASH]]5KTmplIN12_GLOBAL__N_19AnonymousEE(
// INT-HEADER-DAG: getName() { return "_ZTSU21cuid_[[HASH]]5KTmplIN12_GLOBAL__N_19AnonymousEE"; }
// HOST-DAG: c"_ZTSU21cuid_[[HASH]]5KTmplIN12_GLOBAL__N_19AnonymousEE\00"
// NOCUID-DAG: _ZTS5KTmplIN12_GLOBAL__N_19AnonymousEE
// HOST-NOCUID-DAG: c"_ZTS5KTmplIN12_GLOBAL__N_19AnonymousEE\00"

// With templateFn<External>:
// DEVICE-DAG: define {{.*}}spir_kernel void @_ZTS5KTmplI8ExternalE(
// INT-HEADER-DAG: getName() { return "_ZTS5KTmplI8ExternalE"; }
// HOST-DAG: c"_ZTS5KTmplI8ExternalE\00"
}

namespace {
class KAnon;
}
class KExt;

void explicitNames(sycl::queue &q) {
// Named kernel, but name is in an unnamed namespace, so add CUID:
q.submit([&](sycl::handler &h) { h.single_task<KAnon>([] {}); });
puts(__builtin_sycl_unique_stable_name(KAnon));
// DEVICE-DAG: define {{.*}}spir_kernel void @_ZTSU21cuid_[[HASH]]N12_GLOBAL__N_15KAnonE(
// INT-HEADER-DAG: getName() { return "_ZTSU21cuid_[[HASH]]N12_GLOBAL__N_15KAnonE"; }
// HOST-DAG: c"_ZTSU21cuid_[[HASH]]N12_GLOBAL__N_15KAnonE\00"
// NOCUID-DAG: _ZTSN12_GLOBAL__N_15KAnonE
// HOST-NOCUID-DAG: c"_ZTSN12_GLOBAL__N_15KAnonE\00"

// Externally visible kernel name, don't add CUID:
q.submit([&](sycl::handler &h) { h.single_task<KExt>([] {}); });
puts(__builtin_sycl_unique_stable_name(KExt));
// DEVICE-DAG: define {{.*}}spir_kernel void @_ZTS4KExt(
// INT-HEADER-DAG: getName() { return "_ZTS4KExt"; }
// HOST-DAG: c"_ZTS4KExt\00"
}

int main() {
sycl::queue q;

staticUnnamed(q);
templateFn<Anonymous>(q);
templateFn<External>(q);
extUnnamed(q);
inlineFn(q);
funcObjects(q);
staticNamed(q);
extNamed(q);
explicitNames(q);
}
Loading
Loading