From dac1b5daea49b6b97867daf733008e81b687f578 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Sun, 25 Oct 2026 09:01:07 +0100 Subject: [PATCH 1/8] SPIR wrapper: support 32-bit x86 hosts Add an --address-bits option. With 32, size_t-typed builtin parameters and returns (vloadN/vstoreN, vload_half, async copies, prefetch, get_image_array_size) are mangled and typed as uint, and the module uses the spir triple. Selecting the 32-bit prefix through sys.argv had been dead since the switch to argparse. For cpu_x86, 32 address bits select the i386 System V ABI. Clang passes and returns every OpenCL vector directly there, except that <8 x i8>, <4 x i16> and <2 x i32> arguments are coerced to i64. This holds for every i686 kernel library variant, so the register size doesn't matter. The output for 64-bit targets is unchanged. --- lib/kernel/SPIR/generate_spir_wrapper.py | 63 ++++++++++++++++-------- 1 file changed, 42 insertions(+), 21 deletions(-) diff --git a/lib/kernel/SPIR/generate_spir_wrapper.py b/lib/kernel/SPIR/generate_spir_wrapper.py index 0be521c8b5..790ebd6324 100644 --- a/lib/kernel/SPIR/generate_spir_wrapper.py +++ b/lib/kernel/SPIR/generate_spir_wrapper.py @@ -10,7 +10,8 @@ # # output is LLVM IR text format. # -# Usage: python3 generate_spir_wrapper.py [-q] [-g] [-m] [-t ] [-r ] OUTPUT +# Usage: python3 generate_spir_wrapper.py [-q] [-g] [-m] [-t ] [-r ] +# [-b ] OUTPUT # ... place the file in the target-specific lib/kernel subdirectory. # # Notes for CPU SPIR wrapper: @@ -26,6 +27,9 @@ # 4) the above applies to the System V and AArch64/RISC-V ABIs. On x86-64 MinGW, # clang passes and returns all vectors directly (the backend lowers the large # ones itself), so the wrappers must not do any of this; see --mingw. +# 5) on 32-bit x86 (i386 System V), clang passes and returns all vectors directly, +# except that 64-bit integer vector arguments are coerced to i64. This does not +# depend on the available vector registers, so the register size is ignored. # # Notes for CUDA SPIR wrapper: # 1) mangling is not required for CUDA @@ -49,6 +53,11 @@ default=128, type=int, choices=[128,256,512], help='largest register size (cpu target only)') +parser.add_argument('-b', '--address-bits', + dest='address_bits', + default=64, type=int, choices=[32,64], + help='device address bits, which determine size_t and the SPIR triple') + parser.add_argument('output', type=argparse.FileType('w', encoding='utf-8'), help='output file') @@ -72,6 +81,8 @@ if args.mingw and args.target != 'cpu_x86': parser.error('--mingw is only supported for the cpu_x86 target') +if args.address_bits == 32 and (args.target != 'cpu_x86' or args.mingw): + parser.error('32 address bits are only supported for the cpu_x86 target, without --mingw') # function prefix used by PoCL's kernel library POCL_LIB_PREFIX = "_cl_" @@ -86,7 +97,8 @@ # if set to True, does target specific hacks like # argument coercing (2xfloat -> double) # use of byval/sret for args that don't fit into registers -X86_CALLING_ABI = (args.target == 'cpu_x86') +X86_CALLING_ABI = (args.target == 'cpu_x86') and args.address_bits == 64 +I386_CALLING_ABI = (args.target == 'cpu_x86') and args.address_bits == 32 ARM_CALLING_ABI = (args.target == 'cpu_arm') RISCV64_CALLING_ABI = (args.target == 'cpu_riscv') SPIR_CALLING_ABI = (args.target == 'cuda') @@ -328,6 +340,12 @@ "<8 x i8>": "double", } +elif I386_CALLING_ABI: + COERCE_VECTOR_MAP = { + "<8 x i8>": "i64", + "<4 x i16>": "i64", + "<2 x i32>": "i64", + } elif ARM_CALLING_ABI: COERCE_VECTOR_MAP = { "<2 x half>": "i32", @@ -394,7 +412,11 @@ } -if CPU_ABI_REG_SIZE == 128: +if I386_CALLING_ABI: + BYVAL_VECTOR_MAP = {} + SRET_VECTOR_MAP = {} + +elif CPU_ABI_REG_SIZE == 128: BYVAL_VECTOR_MAP = { "<3 x double>":"ptr noundef byval(<3 x double>) align 32", "<3 x i64>":"ptr noundef byval(<3 x i64>) align 32", @@ -815,8 +837,8 @@ def generate_function(name, ret_type, ret_type_ext, multiAS, *args): # args without qualifiers, saved for mangling name compression saved_pure_args = [] - # ARM does not coerce return types, x86-64 & RISC-V does - if ARM_CALLING_ABI: + # ARM and i386 do not coerce return types, x86-64 & RISC-V does + if ARM_CALLING_ABI or I386_CALLING_ABI: coerced_ret_type = ret_type else: coerced_ret_type = coerce_llvm_vector_type(ret_type) @@ -1072,11 +1094,10 @@ def generate_function(name, ret_type, ret_type_ext, multiAS, *args): } -triple = SPIR_MODULE_PREFIX[64] -if (len(sys.argv) > 1) and (sys.argv[1] == "32"): - triple = SPIR_MODULE_PREFIX[32] +print(SPIR_MODULE_PREFIX[args.address_bits]) -print(triple) +# mangled name of size_t +SIZE_T = 'j' if args.address_bits == 32 else 'm' MANG_TYPES = { "half": { @@ -1287,28 +1308,28 @@ def generate_function(name, ret_type, ret_type_ext, multiAS, *args): arg = "Dv" + s + "_" + arg_type if vector_size > 1: - generate_function("vload"+str(vector_size), SIG_TO_LLVM_TYPE_MAP[arg], '', True, 'm', PConstArg) - generate_function("vstore"+str(vector_size), SIG_TO_LLVM_TYPE_MAP['v'], '', True, arg, 'm', PArg) + generate_function("vload"+str(vector_size), SIG_TO_LLVM_TYPE_MAP[arg], '', True, SIZE_T, PConstArg) + generate_function("vstore"+str(vector_size), SIG_TO_LLVM_TYPE_MAP['v'], '', True, arg, SIZE_T, PArg) if vector_size > 1: PConstArg = 'PK' + arg PArg = 'P' + arg - generate_function("prefetch", SIG_TO_LLVM_TYPE_MAP['v'], '', True, PConstArg, 'm') + generate_function("prefetch", SIG_TO_LLVM_TYPE_MAP['v'], '', True, PConstArg, SIZE_T) generate_function("async_work_group_copy", 'ptr', '', ("global", "local", "none", "none", "none"), - PArg, PConstArg, 'm', '9ocl_event') + PArg, PConstArg, SIZE_T, '9ocl_event') generate_function("async_work_group_copy", 'ptr', '', ("local", "global", "none", "none", "none"), - PArg, PConstArg, 'm', '9ocl_event') + PArg, PConstArg, SIZE_T, '9ocl_event') generate_function("async_work_group_strided_copy", 'ptr', '', ("global", "local", "none", "none", "none"), - PArg, PConstArg, 'm', 'm', '9ocl_event') + PArg, PConstArg, SIZE_T, SIZE_T, '9ocl_event') generate_function("async_work_group_strided_copy", 'ptr', '', ("local", "global", "none", "none", "none"), - PArg, PConstArg, 'm', 'm', '9ocl_event') + PArg, PConstArg, SIZE_T, SIZE_T, '9ocl_event') # vload_half / vstore_half @@ -1324,11 +1345,11 @@ def generate_function(name, ret_type, ret_type_ext, multiAS, *args): suffix = 'half' + s ret = "Dv" + s + "_" + ret if ret_type == 'f': - generate_function("vload_"+suffix, SIG_TO_LLVM_TYPE_MAP[ret], '', True, 'm', PConstArg) - generate_function("vloada_"+suffix, SIG_TO_LLVM_TYPE_MAP[ret], '', True, 'm', PConstArg) + generate_function("vload_"+suffix, SIG_TO_LLVM_TYPE_MAP[ret], '', True, SIZE_T, PConstArg) + generate_function("vloada_"+suffix, SIG_TO_LLVM_TYPE_MAP[ret], '', True, SIZE_T, PConstArg) for rounding in ['', '_rte', '_rtn', '_rtp', '_rtz']: - generate_function("vstore_"+suffix+rounding, SIG_TO_LLVM_TYPE_MAP['v'], '', True, ret, 'm', PArg) - generate_function("vstorea_"+suffix+rounding, SIG_TO_LLVM_TYPE_MAP['v'], '', True, ret, 'm', PArg) + generate_function("vstore_"+suffix+rounding, SIG_TO_LLVM_TYPE_MAP['v'], '', True, ret, SIZE_T, PArg) + generate_function("vstorea_"+suffix+rounding, SIG_TO_LLVM_TYPE_MAP['v'], '', True, ret, SIZE_T, PArg) # Integer for arg_type in IGENTYPES: @@ -1460,7 +1481,7 @@ def generate_function(name, ret_type, ret_type_ext, multiAS, *args): generate_function('get_image_depth', 'i32', '', True, img_type_llvm) generate_function('get_image_dim', '<4 x i32>', '', True, img_type_llvm) if img_type in ['image2d_array', 'image2d_array_depth', 'image1d_array']: - generate_function('get_image_array_size', 'i64', '', True, img_type_llvm) + generate_function('get_image_array_size', SIG_TO_LLVM_TYPE_MAP[SIZE_T], '', True, img_type_llvm) # Atomics From 4ca7a22e790c8aba83fd8a120fa90a8fd5beaa15 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Sun, 25 Oct 2026 09:09:12 +0100 Subject: [PATCH 2/8] cmake: generate the SPIR wrapper for i386 hosts Use the generated wrapper with --address-bits 32 instead of the checked-in spir_wrapper32.ll, which only has scalar builtins. Like on RISC-V, generate it once per kernel library variant: the i386 ABI doesn't depend on the vector registers, and the variants without SSE2 never reach the generation in the SLEEF vector-size loop. --- cmake/bitcode_rules.cmake | 3 +++ lib/kernel/host/CMakeLists.txt | 7 ++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/cmake/bitcode_rules.cmake b/cmake/bitcode_rules.cmake index ed339cae9d..dd32fc829b 100644 --- a/cmake/bitcode_rules.cmake +++ b/cmake/bitcode_rules.cmake @@ -281,6 +281,9 @@ function(generate_cpu_spir_wrapper ARCH SUBDIR SIZE OUTPUT) if(ARCH STREQUAL "cpu_x86" AND LLC_TRIPLE MATCHES "-windows-gnu") list(APPEND EXTRA_OPT "--mingw") endif() + if(ARCH STREQUAL "cpu_x86") + list(APPEND EXTRA_OPT "--address-bits" "${HOST_DEVICE_ADDRESS_BITS}") + endif() add_custom_command( OUTPUT "${FNAME}" DEPENDS "${CMAKE_SOURCE_DIR}/lib/kernel/SPIR/generate_spir_wrapper.py" diff --git a/lib/kernel/host/CMakeLists.txt b/lib/kernel/host/CMakeLists.txt index ba99f00fcd..f92ce1b201 100644 --- a/lib/kernel/host/CMakeLists.txt +++ b/lib/kernel/host/CMakeLists.txt @@ -584,7 +584,12 @@ function(compile_sleef VARIANT SLEEF_CONFIG SLEEF_CONFIG_NEW SLEEF_BC) # the "runtime/clGetKernelArgInfo" requires working images with spir, # that only works if we're using the new (generated) wrappers set(HAVE_WORKING_IMAGES_WITH_SPIR OFF CACHE BOOL "image functions work with SPIR" FORCE) - if(HOST_DEVICE_ADDRESS_BITS EQUAL 32) + if(I386) + # the i386 ABI passes vectors the same way regardless of the vector + # registers, so the 128bit wrapper works for every variant, including + # those without SSE2 that never reach the generation in the loop below + generate_cpu_spir_wrapper(cpu_x86 ${VARIANT} 128 SPIR_WRAPPER_FILE) + elseif(HOST_DEVICE_ADDRESS_BITS EQUAL 32) set(SPIR_WRAPPER_FILE "host/spir_wrapper32.ll") else() if(RISCV) From 3a901f268a3f42a20f6e5374c0e25aa76f1c3ac9 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Sun, 25 Oct 2026 09:09:40 +0100 Subject: [PATCH 3/8] Preserve SPIR struct layouts when retargeting SPIR modules Before linking a SPIR module with the kernel library, its datalayout is replaced by the host's. Struct types from SPIR(-V) aren't padded explicitly, because the SPIR datalayout already aligns long and double to 8 bytes as OpenCL C requires. Where the host aligns them less (i386), field offsets, struct sizes and array strides silently changed, while sizeof and offsetof, folded by the SPIR compiler, still reported the SPIR layout. Before the swap, replace every struct type whose layout differs, wherever it describes memory, by a packed struct with explicit padding: GEPs (renumbering the field indices), allocas, globals and their initializers, and the byval/sret/byref/elementtype attributes. Aggregate SSA values have no layout and keep their type; aggregate loads and stores are split into per-element accesses at the SPIR offsets. This is what Clang does for OpenCL C on i386, and a no-op where the layouts agree (all 64-bit hosts). The test checks struct buffers, by-value struct arguments, nested structs, tail padding, private arrays of structs, constant initializers and aggregate loads and stores, from 32-bit and 64-bit SPIR-V. --- lib/CL/pocl_llvm_build.cc | 15 +- lib/llvmopencl/CMakeLists.txt | 2 + lib/llvmopencl/SPIRStructLayout.cc | 530 ++++++++++++++++++ lib/llvmopencl/SPIRStructLayout.h | 51 ++ poclu/misc.c | 11 + poclu/poclu.h | 7 + tests/regression/CMakeLists.txt | 3 + tests/regression/test_spirv_struct_layout.c | 315 +++++++++++ tests/regression/test_spirv_struct_layout.cl | 71 +++ tests/regression/test_spirv_struct_layout.ll | 47 ++ .../regression/test_spirv_struct_layout32.spv | Bin 0 -> 7340 bytes .../regression/test_spirv_struct_layout64.spv | Bin 0 -> 7556 bytes 12 files changed, 1049 insertions(+), 3 deletions(-) create mode 100644 lib/llvmopencl/SPIRStructLayout.cc create mode 100644 lib/llvmopencl/SPIRStructLayout.h create mode 100644 tests/regression/test_spirv_struct_layout.c create mode 100644 tests/regression/test_spirv_struct_layout.cl create mode 100644 tests/regression/test_spirv_struct_layout.ll create mode 100644 tests/regression/test_spirv_struct_layout32.spv create mode 100644 tests/regression/test_spirv_struct_layout64.spv diff --git a/lib/CL/pocl_llvm_build.cc b/lib/CL/pocl_llvm_build.cc index 8aa581411d..0a2ef50d4a 100644 --- a/lib/CL/pocl_llvm_build.cc +++ b/lib/CL/pocl_llvm_build.cc @@ -95,6 +95,7 @@ using namespace llvm; POP_COMPILER_DIAGS #include "ProgramScopeVariables.h" +#include "SPIRStructLayout.h" #include "linker.h" //#define DEBUG_POCL_LLVM_API @@ -884,10 +885,12 @@ int pocl_llvm_build_program(cl_program program, } /* converts a "spir-unknown-unknown" module triple to target (CPU/CUDA etc) - * triple, resets the datalayout to the target datalayout */ + * triple, resets the datalayout to the target datalayout while keeping the + * memory layout of the SPIR struct types */ static int pocl_convert_spir_bitcode_to_target(llvm::Module *p, llvm::Module *libmodule, - cl_device_id device) { + cl_device_id device, + std::string &Log) { #if LLVM_MAJOR < 21 const std::string &ModTriple = p->getTargetTriple(); @@ -912,6 +915,9 @@ static int pocl_convert_spir_bitcode_to_target(llvm::Module *p, device->llvm_target_triplet, ModTriple.c_str()); } + if (!pocl::preserveSPIRStructLayouts(*p, libmodule->getDataLayout(), Log)) + return CL_LINK_PROGRAM_FAILURE; + /* Note this is a hack to get SPIR working. We'll be linking the * host kernel library (plain LLVM IR) to the SPIR program.bc, * so LLVM complains about incompatible DataLayouts. @@ -986,8 +992,11 @@ int pocl_llvm_link_program(cl_program program, unsigned device_i, } } + std::string ConvertLog; error = pocl_convert_spir_bitcode_to_target(TempModule.get(), LibraryModule, - device); + device, ConvertLog); + if (!ConvertLog.empty()) + appendToProgramBuildLog(program, device_i, ConvertLog); POCL_RETURN_ERROR_ON((error != CL_SUCCESS), CL_LINK_PROGRAM_FAILURE, "could not convert SPIR to Target\n"); diff --git a/lib/llvmopencl/CMakeLists.txt b/lib/llvmopencl/CMakeLists.txt index 104105d10b..ed03274bc0 100644 --- a/lib/llvmopencl/CMakeLists.txt +++ b/lib/llvmopencl/CMakeLists.txt @@ -73,6 +73,8 @@ set(LLVMPASSES_SOURCES "AllocasToEntry.cc" "RemoveBarrierCalls.h" "SanitizeUBofDivRem.cc" "SanitizeUBofDivRem.h" + "SPIRStructLayout.cc" + "SPIRStructLayout.h" "SubCFGFormation.cc" "SubCFGFormation.h" "UnreachablesToReturns.cc" diff --git a/lib/llvmopencl/SPIRStructLayout.cc b/lib/llvmopencl/SPIRStructLayout.cc new file mode 100644 index 0000000000..a20d6f59fd --- /dev/null +++ b/lib/llvmopencl/SPIRStructLayout.cc @@ -0,0 +1,530 @@ +// Preserves the memory layout of SPIR struct types when a module is +// retargeted to the host datalayout. +// +// SPIR modules (e.g. from SPIR-V) carry the SPIR datalayout, which follows +// OpenCL C: long and double are 8-byte aligned. Linking them with the +// kernel library replaces that datalayout with the host's, where these +// types can be less aligned (4 bytes on i386). Struct types without explicit +// padding would then silently change their field offsets, sizes and array +// strides. Clang avoids this for OpenCL C by emitting explicitly padded +// structs; this does the same for SPIR modules. +// +// Every struct type whose layout differs between the two datalayouts is +// replaced, wherever it describes memory, by a packed struct with explicit +// [N x i8] padding that has the SPIR offsets and size under any datalayout. +// That covers GEPs (with renumbered field indices), allocas, globals and +// their initializers, and the byval/sret/byref/elementtype attributes. +// Aggregate SSA values have no layout, so they keep their original type; +// aggregate loads and stores of such types are split into per-element +// accesses at the SPIR offsets instead. +// +// Copyright (c) 2026 Tim Besard +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. + +#include "config.h" + +#include "CompilerWarnings.h" +IGNORE_COMPILER_WARNING("-Wunused-parameter") +#include +#include +#include +#include +#include +#include +POP_COMPILER_DIAGS + +#include "SPIRStructLayout.h" + +using namespace llvm; + +namespace { + +class SPIRLayoutPreserver { +public: + SPIRLayoutPreserver(Module &M, const DataLayout &TargetDL) + : M(M), Ctx(M.getContext()), SPIRDL(M.getDataLayout()), + TargetDL(TargetDL) {} + + bool run(std::string &Log); + +private: + Module &M; + LLVMContext &Ctx; + const DataLayout &SPIRDL; + const DataLayout &TargetDL; + + // The replacement of every type looked at, or the type itself if its + // layout is the same under both datalayouts. + DenseMap Replacements; + // For each replaced struct, the index of each original field in the + // replacement. + DenseMap> FieldIndices; + DenseMap MappedConstants; + std::string Error; + + Type *replace(Type *T); + Type *replaceStruct(StructType *ST); + template + SmallVector mapIndices(Type *SrcTy, RangeT Indices); + Constant *mapConstant(Constant *C); + Constant *mapValueConstant(Constant *C); + AttributeList mapTypeAttributes(AttributeList Attrs); + void replaceGlobals(); + void rewriteInstructions(Function &F); + Value *splitLoad(IRBuilder<> &B, Type *Ty, Value *Ptr, uint64_t Offset, + Align A); + void splitStore(IRBuilder<> &B, Value *V, Value *Ptr, uint64_t Offset, + Align A); +}; + +Type *SPIRLayoutPreserver::replace(Type *T) { + auto It = Replacements.find(T); + if (It != Replacements.end()) + return It->second; + + Type *R = T; + if (auto *AT = dyn_cast(T)) { + Type *Elt = replace(AT->getElementType()); + if (Elt != AT->getElementType()) + R = ArrayType::get(Elt, AT->getNumElements()); + } else if (auto *ST = dyn_cast(T)) { + if (!ST->isOpaque()) + R = replaceStruct(ST); + } + Replacements[T] = R; + return R; +} + +Type *SPIRLayoutPreserver::replaceStruct(StructType *ST) { + SmallVector Elts; + bool EltReplaced = false; + for (Type *Elt : ST->elements()) { + Elts.push_back(replace(Elt)); + EltReplaced |= Elts.back() != Elt; + } + + const StructLayout *SPIRLayout = SPIRDL.getStructLayout(ST); + if (!EltReplaced) { + const StructLayout *TargetLayout = TargetDL.getStructLayout(ST); + bool Same = SPIRLayout->getSizeInBytes() == TargetLayout->getSizeInBytes(); + for (unsigned I = 0; Same && I < ST->getNumElements(); ++I) + Same = + SPIRLayout->getElementOffset(I) == TargetLayout->getElementOffset(I); + if (Same) + return ST; + } + + // Packed, so that the padding alone determines the offsets. + SmallVector Fields; + SmallVector Indices; + uint64_t Offset = 0; + auto padTo = [&](uint64_t To) { + if (To > Offset) + Fields.push_back(ArrayType::get(Type::getInt8Ty(Ctx), To - Offset)); + Offset = To; + }; + for (unsigned I = 0; I < Elts.size(); ++I) { + padTo(SPIRLayout->getElementOffset(I)); + Indices.push_back(Fields.size()); + Fields.push_back(Elts[I]); + Offset += TargetDL.getTypeAllocSize(Elts[I]).getFixedValue(); + } + padTo(SPIRLayout->getSizeInBytes()); + + StructType *R = + ST->hasName() + ? StructType::create(Ctx, Fields, (ST->getName() + ".spir").str(), + /*isPacked=*/true) + : StructType::get(Ctx, Fields, /*isPacked=*/true); + + // Only fails if an element's size differs between the datalayouts. + const StructLayout *NewLayout = TargetDL.getStructLayout(R); + bool Same = NewLayout->getSizeInBytes() == SPIRLayout->getSizeInBytes(); + for (unsigned I = 0; Same && I < Elts.size(); ++I) + Same = NewLayout->getElementOffset(Indices[I]) == + SPIRLayout->getElementOffset(I); + if (!Same && Error.empty()) { + raw_string_ostream OS(Error); + OS << "cannot preserve the SPIR layout of " << *ST << "\n"; + } + + FieldIndices[ST] = std::move(Indices); + return R; +} + +// Maps the indices of a GEP over SrcTy to the ones over its replacement. +template +SmallVector SPIRLayoutPreserver::mapIndices(Type *SrcTy, + RangeT Indices) { + SmallVector Result; + Type *Ty = nullptr; + for (Value *Idx : Indices) { + if (Ty == nullptr) { + // The first index steps over whole objects, whose size is preserved. + Result.push_back(Idx); + Ty = SrcTy; + continue; + } + if (auto *ST = dyn_cast(Ty)) { + auto *C = cast(Idx); + if (C->getType()->isVectorTy()) + C = C->getSplatValue(); + unsigned Field = cast(C)->getZExtValue(); + auto It = FieldIndices.find(ST); + Result.push_back( + It == FieldIndices.end() + ? Idx + : ConstantInt::get(Idx->getType(), It->second[Field])); + Ty = ST->getElementType(Field); + } else { + Result.push_back(Idx); + Ty = Ty->isArrayTy() ? Ty->getArrayElementType() + : cast(Ty)->getElementType(); + } + } + return Result; +} + +Constant *SPIRLayoutPreserver::mapConstant(Constant *C) { + auto It = MappedConstants.find(C); + if (It != MappedConstants.end()) + return It->second; + + Constant *R = C; + Type *Ty = C->getType(); + Type *NewTy = replace(Ty); + if (NewTy != Ty) { + if (isa(C)) + R = PoisonValue::get(NewTy); + else if (isa(C)) + R = UndefValue::get(NewTy); + else if (C->isNullValue()) + R = Constant::getNullValue(NewTy); + else if (auto *ST = dyn_cast(Ty)) { + auto *NewST = cast(NewTy); + SmallVector Fields; + for (Type *FieldTy : NewST->elements()) + Fields.push_back(Constant::getNullValue(FieldTy)); + const auto &Indices = FieldIndices[ST]; + for (unsigned I = 0; I < ST->getNumElements(); ++I) + Fields[Indices[I]] = mapConstant(C->getAggregateElement(I)); + R = ConstantStruct::get(NewST, Fields); + } else { + auto *AT = cast(Ty); + SmallVector Elts; + for (unsigned I = 0; I < AT->getNumElements(); ++I) + Elts.push_back(mapConstant(C->getAggregateElement(I))); + R = ConstantArray::get(cast(NewTy), Elts); + } + } else if (isa(C) || isa(C)) { + SmallVector Ops; + bool Changed = false; + for (Value *Op : C->operands()) { + Ops.push_back(mapConstant(cast(Op))); + Changed |= Ops.back() != Op; + } + Type *NewSrcTy = nullptr; + if (auto *GEP = dyn_cast(C)) { + Type *SrcTy = GEP->getSourceElementType(); + if (replace(SrcTy) != SrcTy) { + NewSrcTy = replace(SrcTy); + auto Indices = mapIndices(SrcTy, GEP->indices()); + for (unsigned I = 0; I < Indices.size(); ++I) + Ops[I + 1] = cast(Indices[I]); + } + } + if (NewSrcTy) { + // getWithOperands would ignore a new source type if nothing else + // changed, e.g. for GEPs that only index arrays of a replaced type. + auto *GEP = cast(C); + ArrayRef Indices = ArrayRef(Ops).drop_front(); +#if LLVM_MAJOR < 19 + R = ConstantExpr::getGetElementPtr( + NewSrcTy, Ops[0], Indices, GEP->isInBounds(), GEP->getInRangeIndex()); +#else + R = ConstantExpr::getGetElementPtr( + NewSrcTy, Ops[0], Indices, GEP->getNoWrapFlags(), GEP->getInRange()); +#endif + } else if (Changed) { + if (auto *CE = dyn_cast(C)) + R = CE->getWithOperands(Ops, Ty); + else if (auto *ST = dyn_cast(Ty)) + R = ConstantStruct::get(ST, Ops); + else if (auto *AT = dyn_cast(Ty)) + R = ConstantArray::get(AT, Ops); + else + R = ConstantVector::get(Ops); + } + } + MappedConstants[C] = R; + return R; +} + +// Like mapConstant, but for an SSA operand: aggregates keep their type. +Constant *SPIRLayoutPreserver::mapValueConstant(Constant *C) { + if (replace(C->getType()) == C->getType()) + return mapConstant(C); + if (!isa(C)) + return C; + SmallVector Ops; + bool Changed = false; + for (Value *Op : C->operands()) { + Ops.push_back(mapValueConstant(cast(Op))); + Changed |= Ops.back() != Op; + } + if (!Changed) + return C; + if (auto *ST = dyn_cast(C->getType())) + return ConstantStruct::get(ST, Ops); + return ConstantArray::get(cast(C->getType()), Ops); +} + +AttributeList SPIRLayoutPreserver::mapTypeAttributes(AttributeList Attrs) { + static const Attribute::AttrKind Kinds[] = { + Attribute::ByVal, Attribute::StructRet, Attribute::ByRef, + Attribute::InAlloca, Attribute::Preallocated, Attribute::ElementType}; + // Not only parameters: llvm.call.preallocated.arg calls carry + // preallocated as a function attribute. + AttributeList Orig = Attrs; + for (unsigned Index : Orig.indexes()) { + for (Attribute::AttrKind Kind : Kinds) { + Attribute A = Orig.getAttributeAtIndex(Index, Kind); + if (!A.isValid()) + continue; + Type *Ty = A.getValueAsType(); + Type *NewTy = replace(Ty); + if (NewTy != Ty) + Attrs = Attrs.replaceAttributeTypeAtIndex(Ctx, Index, Kind, NewTy); + + // Without an explicit alignment, the pointee is aligned like its type, + // which the replacement (packed) or the target datalayout may lower. + if (Kind != Attribute::ElementType && + Index != AttributeList::FunctionIndex && + Index >= AttributeList::FirstArgIndex) { + unsigned ArgNo = Index - AttributeList::FirstArgIndex; + Align SPIRAlign = SPIRDL.getABITypeAlign(Ty); + if (!Attrs.getParamAlignment(ArgNo) && + TargetDL.getABITypeAlign(NewTy) != SPIRAlign) + Attrs = Attrs.addParamAttribute( + Ctx, ArgNo, Attribute::getWithAlignment(Ctx, SPIRAlign)); + } + } + } + return Attrs; +} + +void SPIRLayoutPreserver::replaceGlobals() { + SmallVector, 8> Replaced; + for (GlobalVariable &GV : M.globals()) { + Type *Ty = GV.getValueType(); + Type *NewTy = replace(Ty); + if (NewTy == Ty) + continue; + auto *NewGV = + new GlobalVariable(M, NewTy, GV.isConstant(), GV.getLinkage(), nullptr, + "", &GV, GV.getThreadLocalMode(), + GV.getAddressSpace(), GV.isExternallyInitialized()); + NewGV->copyAttributesFrom(&GV); + NewGV->setComdat(GV.getComdat()); + NewGV->copyMetadata(&GV, 0); + NewGV->setAlignment(GV.getAlign() ? *GV.getAlign() + : SPIRDL.getPreferredAlign(&GV)); + Replaced.push_back({&GV, NewGV}); + } + + // Pointers are opaque, so the replacements can take over every use, also + // in the initializers of other globals, before those are mapped below. + for (auto [GV, NewGV] : Replaced) + GV->replaceAllUsesWith(NewGV); + for (auto [GV, NewGV] : Replaced) { + if (GV->hasInitializer()) + NewGV->setInitializer(mapConstant(GV->getInitializer())); + NewGV->takeName(GV); + GV->eraseFromParent(); + } + + for (GlobalVariable &GV : M.globals()) { + if (!GV.getAlign() && + SPIRDL.getPreferredAlign(&GV) != TargetDL.getPreferredAlign(&GV)) + GV.setAlignment(SPIRDL.getPreferredAlign(&GV)); + if (!GV.hasInitializer()) + continue; + Constant *Init = mapConstant(GV.getInitializer()); + if (Init != GV.getInitializer()) + GV.setInitializer(Init); + } + for (GlobalAlias &GA : M.aliases()) { + Constant *Aliasee = mapConstant(GA.getAliasee()); + if (Aliasee != GA.getAliasee()) + GA.setAliasee(Aliasee); + } +} + +Value *SPIRLayoutPreserver::splitLoad(IRBuilder<> &B, Type *Ty, Value *Ptr, + uint64_t Offset, Align A) { + if (auto *ST = dyn_cast(Ty)) { + const StructLayout *Layout = SPIRDL.getStructLayout(ST); + Value *V = PoisonValue::get(ST); + for (unsigned I = 0; I < ST->getNumElements(); ++I) + V = B.CreateInsertValue(V, + splitLoad(B, ST->getElementType(I), Ptr, + Offset + Layout->getElementOffset(I), + A), + I); + return V; + } + if (auto *AT = dyn_cast(Ty)) { + uint64_t Stride = + SPIRDL.getTypeAllocSize(AT->getElementType()).getFixedValue(); + Value *V = PoisonValue::get(AT); + for (unsigned I = 0; I < AT->getNumElements(); ++I) + V = B.CreateInsertValue( + V, splitLoad(B, AT->getElementType(), Ptr, Offset + I * Stride, A), + I); + return V; + } + Value *P = + Offset ? B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), Ptr, Offset) : Ptr; + return B.CreateAlignedLoad(Ty, P, commonAlignment(A, Offset)); +} + +void SPIRLayoutPreserver::splitStore(IRBuilder<> &B, Value *V, Value *Ptr, + uint64_t Offset, Align A) { + Type *Ty = V->getType(); + if (auto *ST = dyn_cast(Ty)) { + const StructLayout *Layout = SPIRDL.getStructLayout(ST); + for (unsigned I = 0; I < ST->getNumElements(); ++I) + splitStore(B, B.CreateExtractValue(V, I), Ptr, + Offset + Layout->getElementOffset(I), A); + return; + } + if (auto *AT = dyn_cast(Ty)) { + uint64_t Stride = + SPIRDL.getTypeAllocSize(AT->getElementType()).getFixedValue(); + for (unsigned I = 0; I < AT->getNumElements(); ++I) + splitStore(B, B.CreateExtractValue(V, I), Ptr, Offset + I * Stride, A); + return; + } + Value *P = + Offset ? B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), Ptr, Offset) : Ptr; + B.CreateAlignedStore(V, P, commonAlignment(A, Offset)); +} + +void SPIRLayoutPreserver::rewriteInstructions(Function &F) { + SmallVector ToSplit; + for (BasicBlock &BB : F) { + for (Instruction &I : BB) { + for (Use &U : I.operands()) { + auto *C = dyn_cast(U.get()); + if (C == nullptr || isa(C)) + continue; + Constant *NewC = mapValueConstant(C); + if (NewC != C) + U.set(NewC); + } + + if (auto *GEP = dyn_cast(&I)) { + Type *SrcTy = GEP->getSourceElementType(); + Type *NewSrcTy = replace(SrcTy); + if (NewSrcTy == SrcTy) + continue; + auto Indices = mapIndices(SrcTy, GEP->indices()); + for (unsigned Idx = 0; Idx < Indices.size(); ++Idx) + GEP->setOperand(Idx + 1, Indices[Idx]); + GEP->setSourceElementType(NewSrcTy); + GEP->setResultElementType(replace(GEP->getResultElementType())); + } else if (auto *AI = dyn_cast(&I)) { + AI->setAllocatedType(replace(AI->getAllocatedType())); + } else if (auto *CB = dyn_cast(&I)) { + CB->setAttributes(mapTypeAttributes(CB->getAttributes())); + } else if (auto *LI = dyn_cast(&I)) { + if (replace(LI->getType()) != LI->getType()) + ToSplit.push_back(LI); + } else if (auto *SI = dyn_cast(&I)) { + Type *Ty = SI->getValueOperand()->getType(); + if (replace(Ty) != Ty) + ToSplit.push_back(SI); + } + } + } + + for (Instruction *I : ToSplit) { + IRBuilder<> B(I); + if (auto *LI = dyn_cast(I)) { + if (LI->isVolatile()) { + Error = "volatile aggregate loads are not supported\n"; + return; + } + Value *V = splitLoad(B, LI->getType(), LI->getPointerOperand(), 0, + LI->getAlign()); + V->takeName(LI); + LI->replaceAllUsesWith(V); + } else { + auto *SI = cast(I); + if (SI->isVolatile()) { + Error = "volatile aggregate stores are not supported\n"; + return; + } + splitStore(B, SI->getValueOperand(), SI->getPointerOperand(), 0, + SI->getAlign()); + } + I->eraseFromParent(); + } +} + +bool SPIRLayoutPreserver::run(std::string &Log) { + // Kernel arguments are passed in memory, which the launcher would read + // with the target layout. + for (Function &F : M) { + if (F.getCallingConv() != CallingConv::SPIR_KERNEL) + continue; + for (Argument &A : F.args()) { + if (!A.hasByValAttr() && replace(A.getType()) != A.getType()) { + Log = "kernel " + F.getName().str() + + " takes an aggregate argument by value, which is only " + "supported through a byval pointer\n"; + return false; + } + } + } + + replaceGlobals(); + for (Function &F : M) { + F.setAttributes(mapTypeAttributes(F.getAttributes())); + rewriteInstructions(F); + } + + if (!Error.empty()) { + Log = Error; + return false; + } + return true; +} + +} // namespace + +namespace pocl { + +bool preserveSPIRStructLayouts(Module &M, const DataLayout &TargetDL, + std::string &Log) { + return SPIRLayoutPreserver(M, TargetDL).run(Log); +} + +} // namespace pocl diff --git a/lib/llvmopencl/SPIRStructLayout.h b/lib/llvmopencl/SPIRStructLayout.h new file mode 100644 index 0000000000..a01ac18a99 --- /dev/null +++ b/lib/llvmopencl/SPIRStructLayout.h @@ -0,0 +1,51 @@ +// Header for preserving SPIR struct layouts across a datalayout change. +// +// Copyright (c) 2026 Tim Besard +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. + +#ifndef POCL_SPIR_STRUCT_LAYOUT_H +#define POCL_SPIR_STRUCT_LAYOUT_H + +#include +#include + +#include + +#ifdef __GNUC__ +#pragma GCC visibility push(hidden) +#endif + +namespace pocl { + +// Rewrites the module, which still has the SPIR datalayout, so that its +// memory layout stays the same once the datalayout is replaced by +// TargetDL. Returns false and explains why in Log if the module uses a +// construct that can't be preserved. +bool preserveSPIRStructLayouts(llvm::Module &M, + const llvm::DataLayout &TargetDL, + std::string &Log); + +} // namespace pocl + +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + +#endif diff --git a/poclu/misc.c b/poclu/misc.c index 1bc792d0f9..699affee4f 100644 --- a/poclu/misc.c +++ b/poclu/misc.c @@ -814,3 +814,14 @@ poclu_device_supports_il (cl_device_id device, const char *il) free (ils); return has_il; } + +cl_uint +poclu_device_address_bits (cl_device_id device) +{ + cl_uint address_bits = 0; + cl_int err = clGetDeviceInfo (device, CL_DEVICE_ADDRESS_BITS, + sizeof (cl_uint), &address_bits, NULL); + if (err != CL_SUCCESS) + return 0; + return address_bits; +} diff --git a/poclu/poclu.h b/poclu/poclu.h index 3faaef6a54..c73c0a8994 100644 --- a/poclu/poclu.h +++ b/poclu/poclu.h @@ -377,6 +377,13 @@ POCLU_API cl_int POCLU_CALL poclu_show_program_build_log (cl_program program); POCLU_API int POCLU_CALL poclu_device_supports_il (cl_device_id device, const char *il); +/** + * \brief get the address bits of a device, which must match the addressing + * model (Physical32 or Physical64) of the SPIR-V modules it runs + * \return the address bits, or 0 on error + */ +POCLU_API cl_uint POCLU_CALL poclu_device_address_bits (cl_device_id device); + /** * \brief check a return value of CL function or print the error to stderr. * @param cl_err [in] value to be checked. diff --git a/tests/regression/CMakeLists.txt b/tests/regression/CMakeLists.txt index a17a518440..4268955668 100644 --- a/tests/regression/CMakeLists.txt +++ b/tests/regression/CMakeLists.txt @@ -31,6 +31,7 @@ set(C_PROGRAMS_TO_BUILD test_assign_loop_variable_to_privvar_makes_it_local test_issue_1711 test_issue_1794 test_issue_1747 test_issue_1958 test_unreachable_kernel test_spirv_float_controls2 + test_spirv_struct_layout test_unreachable_in_infinite_loop test_rematerialized_alloca_load_with_outside_pr_users test_peeled_wi_global_id @@ -195,6 +196,8 @@ add_test_pocl(NAME "regression/test_unreachable_kernel" WORKITEM_HANDLER "loops; add_test_pocl(NAME "regression/test_spirv_float_controls2" WORKITEM_HANDLER "loops;loopvec;cbs;" COMMAND "test_spirv_float_controls2" LABELS ${SPIRV_LABELS}) +add_test_pocl(NAME "regression/test_spirv_struct_layout" WORKITEM_HANDLER "loops;loopvec;cbs;" COMMAND "test_spirv_struct_layout" LABELS ${SPIRV_LABELS}) + add_test_pocl(NAME "regression/unreachable_in_infinite_loop" WORKITEM_HANDLER "loops;loopvec;cbs;" COMMAND "test_unreachable_in_infinite_loop") add_test_pocl(NAME "regression/peeled_wi_global_id" WORKITEM_HANDLER "loopvec;cbs;" COMMAND "test_peeled_wi_global_id" LABELS ${SPIRV_LABELS}) diff --git a/tests/regression/test_spirv_struct_layout.c b/tests/regression/test_spirv_struct_layout.c new file mode 100644 index 0000000000..9f319c1e3a --- /dev/null +++ b/tests/regression/test_spirv_struct_layout.c @@ -0,0 +1,315 @@ +// Copyright (c) 2026 PoCL developers +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +/* + SPIR-V modules use the OpenCL C layout of structs, where long and double + are 8-byte aligned, without padding the struct types explicitly. PoCL + replaces the SPIR datalayout with the host's, which on i386 aligns long and + double to 4 bytes only, so the kernels used to access fields, struct + arguments and arrays of structs at the wrong offsets, while sizeof and + offsetof (folded by the SPIR compiler) still reported the SPIR layout. + + The kernels are in test_spirv_struct_layout.cl and .ll. The host side + writes and reads the structs as bytes at the OpenCL C offsets. +*/ + +#include "pocl_opencl.h" + +#include +#include +#include +#ifndef _WIN32 +#include +#endif + +#define CHECK_ERROR(err) \ + if (err != CL_SUCCESS) { \ + printf("OpenCL Error %d at %s:%d\n", err, __FILE__, __LINE__); \ + return 1; \ + } + +#define N 3 +#define S_SIZE 24 +#define U_SIZE 56 +#define P_SIZE 32 + +static int Failures = 0; + +static void put_i32(unsigned char *buf, size_t off, cl_int v) { + memcpy(buf + off, &v, sizeof(v)); +} +static void put_i64(unsigned char *buf, size_t off, cl_long v) { + memcpy(buf + off, &v, sizeof(v)); +} +static void put_f64(unsigned char *buf, size_t off, cl_double v) { + memcpy(buf + off, &v, sizeof(v)); +} + +static void check_i64(const char *what, int idx, const unsigned char *buf, + size_t off, size_t size, cl_long expected) { + cl_long v = 0; + if (size == 1) + v = (cl_char)buf[off]; + else if (size == 4) { + cl_int i; + memcpy(&i, buf + off, sizeof(i)); + v = i; + } else + memcpy(&v, buf + off, sizeof(v)); + if (v != expected) { + printf("%s[%d]: got %lld, expected %lld\n", what, idx, (long long)v, + (long long)expected); + Failures++; + } +} + +static void check_f64(const char *what, int idx, const unsigned char *buf, + size_t off, cl_double expected) { + cl_double v; + memcpy(&v, buf + off, sizeof(v)); + if (v != expected) { + printf("%s[%d]: got %g, expected %g\n", what, idx, v, expected); + Failures++; + } +} + +/* T: d at 0, i at 8. */ +static void put_t(unsigned char *buf, size_t off, cl_double d, cl_int i) { + put_f64(buf, off, d); + put_i32(buf, off + 8, i); +} +static void check_t(const char *what, int idx, const unsigned char *buf, + size_t off, cl_double d, cl_int i) { + check_f64(what, idx, buf, off, d); + check_i64(what, idx, buf, off + 8, 4, i); +} + +static int run_layout(cl_context context, cl_command_queue queue, + cl_program program) { + cl_int err; + cl_kernel kernel = clCreateKernel(program, "layout", &err); + CHECK_ERROR(err); + + /* S: c at 0, l at 8, d at 16. */ + unsigned char sv[S_SIZE] = {0}; + sv[0] = 3; + put_i64(sv, 8, 0x100000000LL); + put_f64(sv, 16, 0.5); + + /* U: a at 0, t[2] at 8, c at 40, l at 48. */ + unsigned char uv[U_SIZE] = {0}; + put_i32(uv, 0, 100); + put_t(uv, 8, 1.25, 7); + put_t(uv, 24, 2.25, 8); + uv[40] = 9; + put_i64(uv, 48, 1000); + + cl_mem s = clCreateBuffer(context, CL_MEM_READ_WRITE, N * S_SIZE, NULL, &err); + CHECK_ERROR(err); + cl_mem u = clCreateBuffer(context, CL_MEM_READ_WRITE, N * U_SIZE, NULL, &err); + CHECK_ERROR(err); + cl_mem out = + clCreateBuffer(context, CL_MEM_READ_WRITE, 9 * sizeof(cl_long), NULL, &err); + CHECK_ERROR(err); + + CHECK_ERROR(clSetKernelArg(kernel, 0, sizeof(cl_mem), &s)); + CHECK_ERROR(clSetKernelArg(kernel, 1, S_SIZE, sv)); + CHECK_ERROR(clSetKernelArg(kernel, 2, sizeof(cl_mem), &u)); + CHECK_ERROR(clSetKernelArg(kernel, 3, U_SIZE, uv)); + CHECK_ERROR(clSetKernelArg(kernel, 4, sizeof(cl_mem), &out)); + + size_t global = N; + CHECK_ERROR(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &global, NULL, 0, + NULL, NULL)); + + unsigned char s_res[N * S_SIZE], u_res[N * U_SIZE]; + cl_long out_res[9]; + CHECK_ERROR(clEnqueueReadBuffer(queue, s, CL_TRUE, 0, sizeof(s_res), s_res, 0, + NULL, NULL)); + CHECK_ERROR(clEnqueueReadBuffer(queue, u, CL_TRUE, 0, sizeof(u_res), u_res, 0, + NULL, NULL)); + CHECK_ERROR(clEnqueueReadBuffer(queue, out, CL_TRUE, 0, sizeof(out_res), + out_res, 0, NULL, NULL)); + + /* priv[k] = {t[k % 2].d * (k + 1), t[k % 2].i + k} */ + const cl_double priv_d[3] = {1.25, 4.5, 3.75}; + const cl_int priv_i[3] = {7, 9, 9}; + for (int i = 0; i < N; i++) { + const unsigned char *si = s_res + i * S_SIZE; + check_i64("s.c", i, si, 0, 1, 3 + i); + check_i64("s.l", i, si, 8, 8, 0x100000000LL + i); + check_f64("s.d", i, si, 16, 0.5 + i); + + const unsigned char *ui = u_res + i * U_SIZE; + check_i64("u.a", i, ui, 0, 4, 100); + check_t("u.t[0]", i, ui, 8, 1.25, 7); + check_t("u.t[1]", i, ui, 24, priv_d[i % 3], priv_i[i % 3]); + check_i64("u.c", i, ui, 40, 1, 9); + check_i64("u.l", i, ui, 48, 8, 1007); + } + + /* sizeof and offsetof are folded by the SPIR compiler, so these held + before too; the last two read a constant initializer. */ + const cl_long expected_out[9] = {24, 8, 16, 16, 56, 8, 48, 5, 4}; + for (int i = 0; i < 9; i++) + check_i64("out", i, (const unsigned char *)out_res, i * sizeof(cl_long), 8, + expected_out[i]); + + clReleaseMemObject(s); + clReleaseMemObject(u); + clReleaseMemObject(out); + clReleaseKernel(kernel); + return 0; +} + +static int run_aggregate(cl_context context, cl_command_queue queue, + cl_program program) { + cl_int err; + cl_kernel kernel = clCreateKernel(program, "aggregate", &err); + CHECK_ERROR(err); + + /* P: a at 0, t at 8, l at 24. */ + unsigned char io[3 * P_SIZE] = {0}; + put_i32(io, 0, 1); + put_t(io, 8, 0.25, 2); + put_i64(io, 24, 3); + + cl_mem buf = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, + sizeof(io), io, &err); + CHECK_ERROR(err); + CHECK_ERROR(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf)); + + size_t global = 1; + CHECK_ERROR(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &global, NULL, 0, + NULL, NULL)); + CHECK_ERROR(clEnqueueReadBuffer(queue, buf, CL_TRUE, 0, sizeof(io), io, 0, + NULL, NULL)); + + check_i64("p.a", 0, io, 0, 4, 2); + check_t("p.t", 0, io, 8, 0.5, 2); + check_i64("p.l", 0, io, 24, 8, 103); + check_i64("p.a", 1, io, P_SIZE + 0, 4, 10); + check_t("p.t", 1, io, P_SIZE + 8, 1.5, 11); + check_i64("p.l", 1, io, P_SIZE + 24, 8, 12); + check_i64("p.a", 2, io, 2 * P_SIZE + 0, 4, 20); + check_t("p.t", 2, io, 2 * P_SIZE + 8, 2.5, 21); + check_i64("p.l", 2, io, 2 * P_SIZE + 24, 8, 22); + + clReleaseMemObject(buf); + clReleaseKernel(kernel); + return 0; +} + +static int run_constant_gep(cl_context context, cl_command_queue queue, + cl_program program) { + cl_int err; + cl_kernel kernel = clCreateKernel(program, "constant_gep", &err); + CHECK_ERROR(err); + cl_int out = 0; + cl_mem buf = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, + sizeof(out), &out, &err); + CHECK_ERROR(err); + CHECK_ERROR(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf)); + size_t global = 1; + CHECK_ERROR(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &global, NULL, 0, + NULL, NULL)); + CHECK_ERROR(clEnqueueReadBuffer(queue, buf, CL_TRUE, 0, sizeof(out), &out, 0, + NULL, NULL)); + check_i64("tarr[1].i", 0, (const unsigned char *)&out, 0, 4, 2); + clReleaseMemObject(buf); + clReleaseKernel(kernel); + return 0; +} + +int main(int argc, char **argv) { + cl_uint platform_index = argc > 1 ? (cl_uint)atoi(argv[1]) : 0; + cl_int err; + +#ifndef _WIN32 + alarm(300); +#endif + + cl_uint num_platforms; + CHECK_ERROR(clGetPlatformIDs(0, NULL, &num_platforms)); + if (platform_index >= num_platforms) { + printf("Platform index %u out of range\n", platform_index); + return 1; + } + cl_platform_id *platforms = malloc(sizeof(cl_platform_id) * num_platforms); + CHECK_ERROR(clGetPlatformIDs(num_platforms, platforms, NULL)); + cl_platform_id platform = platforms[platform_index]; + free(platforms); + + cl_device_id device; + CHECK_ERROR(clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, NULL)); + + if (!poclu_device_supports_il(device, "SPIR-V_1.0")) { + printf("SKIP: The test requires support for SPIR-V 1.0\n"); + return 77; + } + cl_device_fp_config fp64_config = 0; + CHECK_ERROR(clGetDeviceInfo(device, CL_DEVICE_DOUBLE_FP_CONFIG, + sizeof(fp64_config), &fp64_config, NULL)); + if (fp64_config == 0) { + printf("SKIP: The test requires double precision support\n"); + return 77; + } + + const char *path = poclu_device_address_bits(device) == 32 + ? SRCDIR "/test_spirv_struct_layout32.spv" + : SRCDIR "/test_spirv_struct_layout64.spv"; + size_t size; + char *binary = poclu_read_binfile(path, &size); + if (binary == NULL) { + printf("Failed to open %s\n", path); + return 1; + } + + cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &err); + CHECK_ERROR(err); + cl_command_queue queue = + clCreateCommandQueueWithProperties(context, device, NULL, &err); + CHECK_ERROR(err); + + cl_program program = clCreateProgramWithIL(context, binary, size, &err); + CHECK_ERROR(err); + free(binary); + err = clBuildProgram(program, 1, &device, NULL, NULL, NULL); + if (err != CL_SUCCESS) { + poclu_show_program_build_log(program); + CHECK_ERROR(err); + } + + if (run_layout(context, queue, program) || + run_aggregate(context, queue, program) || + run_constant_gep(context, queue, program)) + return 1; + + clReleaseProgram(program); + clReleaseCommandQueue(queue); + clReleaseContext(context); + + if (Failures) { + printf("FAIL: %d mismatches\n", Failures); + return 1; + } + printf("OK\n"); + return 0; +} diff --git a/tests/regression/test_spirv_struct_layout.cl b/tests/regression/test_spirv_struct_layout.cl new file mode 100644 index 0000000000..79a851f334 --- /dev/null +++ b/tests/regression/test_spirv_struct_layout.cl @@ -0,0 +1,71 @@ +/* Kernels for test_spirv_struct_layout.c. The struct types aren't padded + explicitly in SPIR, where long and double are 8-byte aligned. Built to + test_spirv_struct_layout{32,64}.spv together with + test_spirv_struct_layout.ll, for N in 32 and 64 (with spir64 for 64): + + clang --target=spir -cl-std=CL2.0 -O0 -emit-llvm -c \ + test_spirv_struct_layout.cl -o cl.bc + llvm-as test_spirv_struct_layout.ll -o ll.bc + llvm-link --suppress-warnings cl.bc ll.bc -o linked.bc + llvm-spirv --spirv-max-version=1.0 linked.bc \ + -o test_spirv_struct_layoutN.spv +*/ + +/* interior padding: c at 0, l at 8, d at 16, size 24 */ +typedef struct +{ + char c; + long l; + double d; +} S; + +/* tail padding: d at 0, i at 8, size 16 */ +typedef struct +{ + double d; + int i; +} T; + +/* nested: a at 0, t at 8, c at 40, l at 48, size 56 */ +typedef struct +{ + int a; + T t[2]; + char c; + long l; +} U; + +constant U cu = { 1, { { 2.5, 3 }, { 4.5, 5 } }, 6, 7 }; +constant long *cu_l = &cu.l; + +kernel void +layout (global S *s, S sv, global U *u, U uv, global long *out) +{ + int i = get_global_id (0); + s[i].c = sv.c + i; + s[i].l = sv.l + i; + s[i].d = sv.d + i; + + T priv[3]; + for (int k = 0; k < 3; k++) + { + priv[k].d = uv.t[k % 2].d * (k + 1); + priv[k].i = uv.t[k % 2].i + k; + } + u[i] = uv; + u[i].t[1] = priv[i % 3]; + u[i].l += *cu_l; + + if (i == 0) + { + out[0] = sizeof (S); + out[1] = __builtin_offsetof (S, l); + out[2] = __builtin_offsetof (S, d); + out[3] = sizeof (T); + out[4] = sizeof (U); + out[5] = __builtin_offsetof (U, t); + out[6] = __builtin_offsetof (U, l); + out[7] = cu.t[1].i; + out[8] = (long)cu.t[1].d; + } +} diff --git a/tests/regression/test_spirv_struct_layout.ll b/tests/regression/test_spirv_struct_layout.ll new file mode 100644 index 0000000000..b142852587 --- /dev/null +++ b/tests/regression/test_spirv_struct_layout.ll @@ -0,0 +1,47 @@ +; Aggregate SSA values, aggregate loads and stores, and typed constant GEPs, +; which OpenCL C compilers don't emit but other SPIR-V producers do. Linked into +; test_spirv_struct_layout{32,64}.spv, see test_spirv_struct_layout.cl. +; +; P: a at 0, t at 8, l at 24, size 32 + +%T = type { double, i32 } +%P = type { i32, %T, i64 } + +@cp = internal addrspace(2) constant %P { i32 10, %T { double 1.5, i32 11 }, i64 12 }, align 8 + +; a constant GEP that only steps over an array of T, whose stride changes +@tarr = internal addrspace(2) constant [2 x %T] [%T { double 1.0, i32 1 }, %T { double 2.0, i32 2 }], align 8 +@tp = internal addrspace(2) constant ptr addrspace(2) getelementptr ([2 x %T], ptr addrspace(2) @tarr, i32 0, i32 1), align 4 + +define internal spir_func %P @bump(%P %v) { + %a = extractvalue %P %v, 0 + %a1 = add i32 %a, 1 + %v1 = insertvalue %P %v, i32 %a1, 0 + %d = extractvalue %P %v1, 1, 0 + %d1 = fmul double %d, 2.0 + %v2 = insertvalue %P %v1, double %d1, 1, 0 + %l = extractvalue %P %v2, 2 + %l1 = add i64 %l, 100 + %v3 = insertvalue %P %v2, i64 %l1, 2 + ret %P %v3 +} + +define spir_kernel void @aggregate(ptr addrspace(1) align 8 %io) { + %v = load %P, ptr addrspace(1) %io, align 8 + %w = call spir_func %P @bump(%P %v) + store %P %w, ptr addrspace(1) %io, align 8 + %c = load %P, ptr addrspace(2) @cp, align 8 + %io1 = getelementptr inbounds %P, ptr addrspace(1) %io, i32 1 + store %P %c, ptr addrspace(1) %io1, align 8 + %io2 = getelementptr inbounds %P, ptr addrspace(1) %io, i32 2 + store %P { i32 20, %T { double 2.5, i32 21 }, i64 22 }, ptr addrspace(1) %io2, align 8 + ret void +} + +define spir_kernel void @constant_gep(ptr addrspace(1) align 4 %out) { + %p = load ptr addrspace(2), ptr addrspace(2) @tp, align 4 + %f = getelementptr inbounds %T, ptr addrspace(2) %p, i32 0, i32 1 + %v = load i32, ptr addrspace(2) %f, align 8 + store i32 %v, ptr addrspace(1) %out, align 4 + ret void +} diff --git a/tests/regression/test_spirv_struct_layout32.spv b/tests/regression/test_spirv_struct_layout32.spv new file mode 100644 index 0000000000000000000000000000000000000000..afa3388930ad7080b4ed1291f2176158b4eab07e GIT binary patch literal 7340 zcma)>37C~-6~{lgcUT;U)ujax#0{ND6j8!uSOjrHaMx-Y#$g;CW^foVi%cuaY&FZW zvTRRVZM8C6%=Xo?Y_YP^7E{R;G^yY3``!a@_qje#FVBC@IsbFsbI!Yb-(}|3M$Q~v z6eEgp#i(NPh@u=5i;+bgP1%yTB((b{5^}}5Q!=1f7>u?nl$ZMWG zK&|{&6di3fI;a&>;JP;y==EaHQt#|Xl)jnBlS;j%*bBLScxXfS@a$7iOMg4En+ndI zi$2^nG!(x1+NH0x?7Opb{kp!Pjh%}&^z{!fA6V8uxVo!<`M}1(?ylj!!GYy0pFAza zk;qi%YQ>E$PDAPJ?C$Rx=4RnC#< z8gtJaG3KBueiXVJZ~igrDQ2uO2UmO>x);Hi@#ro;3;`0#s)P25OpFJ-_?x|?R>cH@73|-;JKH^&V{Zz!5R`p_@PKC(w7v>?hIP!>IEVy3eX3xX~Pdcg-<{eYU1` zJjdNQjj_lMFb&pP+Mbbd#=Ecbo`bgg=zRBg8XlkZh&NWBF`m_Q;>RH!#%WJ2ttw7? z2DWqLr(y4fj2`T1Cbs$IBj?`e4t@6Y9Hf4GH0NxjLtguk(yC&#<1FNN$9^8t8bbd9 z_U8n-Cf`n4A$ofr0!E0Z1Zy~(yW_plG?9{P+Le;(3&^1HAHe8iXh zP~u&Sahs6pVPBm5_O1W&WXFD8nPS7f3fr*|7=I1Yy6%_uwaK~xr6U-pr14#E(Ui)FBK4HC`MpW_clm1q0}4hrO80vz0PBOwyQB|d#um1ywAC@?R4*RwmUG7e(US zG1hmNe&4AJ$l-J8=eWbzxo}gF(|~8HZ!Z1HO$UpCKHtC2pMl&HROep3Z(Q%bpc-3_ zvRBV#7LeZ$xCid-0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@crrEZv0+H-#lZ0@inC1@#u@Q@x09|A35S2{tMvdHhcg8 literal 0 HcmV?d00001 diff --git a/tests/regression/test_spirv_struct_layout64.spv b/tests/regression/test_spirv_struct_layout64.spv new file mode 100644 index 0000000000000000000000000000000000000000..9eac511e6015e424aa9a7ffd5d704f9dc1b15fbe GIT binary patch literal 7556 zcma)>37D2u702IUK8AhYRB+f_B9K5qMO=mfLDXb%$LebshH+w;f#Dm>qC(3Si}o^0 zixw+wwSCWu7PHN4-!0oMEn5H;`~BYU9_ICXKA)!x|2gOU&$;KEd*A!sS-!?Wvxj6^ zLpC~V%BDAD`52cC%1UU;!AUkHIXuY`Ngj_JL6lS1Z0qP*e*XL&l}#D>8kwEt7(;I7 zuLRv~SNHZ;vg~y9;2%bB>+J07=xnQW`Y{; zb73{t;B46dcX5>)mR*8UF1L5L^>mhd+q=tKI{JFbU0b)6(`LE0M~La_t@e5deJ8M2 zH-2OP)_iY_YrwAh*njk^@;G)1y*=qA^se58%xB+n{lr`!iQblCMyW5X)*Fq!GwEZ{ ztLtmb#;PZNoG~X>>v4OSwJ|eQ0hs<fw;!Z=N>uKi$2dm_|%I&&qVmt_3<>Q zF)BYJ*8YFa2}{h^;`QjJce1ZSP#A zBRJ>yydA-fMCbC($6RJuYYgyAg*_f!KI}>8=GV5DBY-k;Hlr^9j+k>Sy7zwA)jNM+ zj?dm+91+7SpZ6Q~$+>r6P8YU)IihxciB+k?+)dc7#}RS+&`-^o0q$<>u{GSi*sjkJ zbMHfs{SWSbIQPU6+ym(DizC+1L?aUm_7H6MGv*A#_8oQvHvw)_mEwIa<~}I_&OTtFizV$#bKQG45Yot zH)GF6Mi2Hh3)}qik@FaIhdz6nhtzM6<~#xEkk?+ETh$otcy{truunsp+dBG}A{&7G z1Uf$hX)k_1wQpnX(b%()_ODO71?k>tHxs=KX%<+UF}>J!$R+)#~opY%_`HeO!;G^9iSe7@Sd_ki!8Ya9ov zqtr5wUGiO;0OY+Ji?P1j)iM5XtnahD@42z_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Q^ApVf3%tI;!1>zyKyCkj zg{xQpZ}9r=2hP{7xBkDw*PH(!yuJs3^R=5nZT)}1)tmoMczq**^R?|I=KEeeg#9mY zGw^x({p#O|i?|-*N^t*4zIg8c#jaO(KfFHIYF%yTMn3PvIETvG-)|moS*3! zw-8uI+uwB~uDGsQ#MqPLG2pu78sJ>l2&BK$G{X7$kh~+lANo0wygjW?>-X~_`G{SY zo}Zr`>EnMs;^z=QN7A<-&oLyg@8?PK#rXK$%FmbdyPmk0{G3VNzqdvoe%>S>v4@x; zSNxsT&lny4UCFikcP0OZ@7j+-`b-w%_cN*`NNalLyg&Whlb=`V^FDJAjCZg6>`I^U NaZi|6K61o!_#fvnK;i%Z literal 0 HcmV?d00001 From 882afd35e259561c97f507c6c965b5e09f8cb547 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Sun, 25 Oct 2026 09:11:08 +0100 Subject: [PATCH 4/8] tests: don't run 64-bit SPIR-V inputs on 32-bit devices A 32-bit device rightly rejects Physical64 modules, so the regression tests with 64-bit SPIR-V inputs now skip there, using the poclu helper for the device's address bits, and the compiler unit tests with .spirv inputs are only registered on 64-bit hosts. spirv/printf, the test that led to SPIR-V being disabled on 32-bit hosts (#1880), and example1 get 32-bit SPIR-V twins built from the same sources. --- examples/example1/example1.spirv32 | Bin 0 -> 1760 bytes tests/compiler_unit/CMakeLists.txt | 3 ++- tests/regression/test_issue_1711.c | 5 +++++ tests/regression/test_issue_1747.c | 5 +++++ tests/regression/test_issue_1794.c | 5 +++++ tests/regression/test_issue_1958.c | 4 ++++ .../regression/test_multi_exit_barrier_region.c | 4 ++++ tests/regression/test_peeled_wi_global_id.c | 4 ++++ ...rialized_alloca_load_with_outside_pr_users.c | 5 +++++ tests/regression/test_sanitize_divrem.c | 4 ++++ tests/regression/test_spirv_float_controls2.c | 4 ++++ tests/regression/test_spirv_intel_subgroups.c | 4 ++++ tests/regression/test_unreachable_kernel.c | 4 ++++ tests/spirv/printf-kernels.cl | 3 +++ tests/spirv/printf-kernels32.spv | Bin 0 -> 15940 bytes tests/spirv/printf.cc | 10 +++++++++- 16 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 examples/example1/example1.spirv32 create mode 100644 tests/spirv/printf-kernels32.spv diff --git a/examples/example1/example1.spirv32 b/examples/example1/example1.spirv32 new file mode 100644 index 0000000000000000000000000000000000000000..e1d3b979edee2948ad965ca73d69ddc2b702cb50 GIT binary patch literal 1760 zcma)*NpBND5QW>GkOZ>t>^KQoOd#w@0KtJsSeB3?e!SD=U4PBFsvD8Zex=+;wND6Dv>)Xs>EXxS zv!dga7x`FK@fkO!D$Y&HI$06ty{vQIE_{ty@rd7(MgHep{=K3zsyY|PXL+}G5x+n0 zCPg!CB-wE*X{HxhyH#|vw5e8}yWzR*q?LY-vvv}np7heV`z4RVhT=5bl&@R=&)Uq@ z(7m|JviC>4KOz5iiKn!0%HTBgLWY^y@I(2tC7#wE@(mjw9P(!d_+ZY_f_a#|KhMAC z7uDa1{^1=A+a18+9kvGehK&yn`P&10u-$n{H|M*k$yhrjUg$%&A{@zw!(J0+RB+fiyDOhK_vV{1Z6C|$P9gV+FmdCWwoetK4(ImP&*T&To3_tO4qVH75#-Tlm_{!Z mhey8U?a8-(f6{he9C+lLwg>WwvrOAp^3j0V(H0DEP}|?Khqwa( literal 0 HcmV?d00001 diff --git a/tests/compiler_unit/CMakeLists.txt b/tests/compiler_unit/CMakeLists.txt index 418067ea97..5f6d18ed3a 100644 --- a/tests/compiler_unit/CMakeLists.txt +++ b/tests/compiler_unit/CMakeLists.txt @@ -42,7 +42,8 @@ function(add_llvm_check) set(WORKITEM_HANDLER "loopvec") endif() if (POCL_UTEST_SPIRV_NAME) - if (ENABLE_SPIRV) + # the .spirv inputs are 64-bit + if (ENABLE_SPIRV AND HOST_DEVICE_ADDRESS_BITS EQUAL 64) add_test_pocl(NAME "kernel_compiler_unit_tests/${POCL_UTEST_SPIRV_NAME}" COMMAND "poclcc" -s -o ${POCL_UTEST_SPIRV_NAME}.out "${CMAKE_CURRENT_SOURCE_DIR}/${POCL_UTEST_SPIRV_NAME}.spirv" diff --git a/tests/regression/test_issue_1711.c b/tests/regression/test_issue_1711.c index 9191dcfb7e..578c703482 100644 --- a/tests/regression/test_issue_1711.c +++ b/tests/regression/test_issue_1711.c @@ -97,6 +97,11 @@ int main(int argc, char** argv) { printf ("SKIP: The test requires support for SPIR-V 1.0\n"); exit (77); } + if (poclu_device_address_bits (device) != 64) + { + printf ("SKIP: The test's SPIR-V module is 64-bit\n"); + exit (77); + } // Rest of the code remains the same... cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &err); diff --git a/tests/regression/test_issue_1747.c b/tests/regression/test_issue_1747.c index 1aa5a2b7df..d227a5a68a 100644 --- a/tests/regression/test_issue_1747.c +++ b/tests/regression/test_issue_1747.c @@ -140,6 +140,11 @@ main (int argc, char **argv) printf ("SKIP: The test requires support for SPIR-V 1.0\n"); exit (77); } + if (poclu_device_address_bits (device) != 64) + { + printf ("SKIP: The test's SPIR-V module is 64-bit\n"); + exit (77); + } // Rest of the code remains the same... cl_context context = clCreateContext (NULL, 1, &device, NULL, NULL, &err); diff --git a/tests/regression/test_issue_1794.c b/tests/regression/test_issue_1794.c index db7936b144..dedecd1777 100644 --- a/tests/regression/test_issue_1794.c +++ b/tests/regression/test_issue_1794.c @@ -141,6 +141,11 @@ main (int argc, char **argv) printf ("SKIP: The test requires support for SPIR-V 1.1\n"); exit (77); } + if (poclu_device_address_bits (device) != 64) + { + printf ("SKIP: The test's SPIR-V module is 64-bit\n"); + exit (77); + } // Rest of the code remains the same... cl_context context = clCreateContext (NULL, 1, &device, NULL, NULL, &err); diff --git a/tests/regression/test_issue_1958.c b/tests/regression/test_issue_1958.c index 06646a2714..665efaa2ec 100644 --- a/tests/regression/test_issue_1958.c +++ b/tests/regression/test_issue_1958.c @@ -86,6 +86,10 @@ int main(int argc, char **argv) { printf("SKIP: The test requires support for SPIR-V 1.0\n"); return 77; } + if (poclu_device_address_bits(device) != 64) { + printf("SKIP: The test's SPIR-V module is 64-bit\n"); + return 77; + } cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &err); CHECK_ERROR(err); diff --git a/tests/regression/test_multi_exit_barrier_region.c b/tests/regression/test_multi_exit_barrier_region.c index 40849b8ef0..08932ecf8a 100644 --- a/tests/regression/test_multi_exit_barrier_region.c +++ b/tests/regression/test_multi_exit_barrier_region.c @@ -97,6 +97,10 @@ int main(int argc, char **argv) { printf("SKIP: The test requires support for SPIR-V 1.0\n"); return 77; } + if (poclu_device_address_bits(device) != 64) { + printf("SKIP: The test's SPIR-V module is 64-bit\n"); + return 77; + } cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &err); CHECK_ERROR(err); diff --git a/tests/regression/test_peeled_wi_global_id.c b/tests/regression/test_peeled_wi_global_id.c index 7ee4dc4cde..9116f88c00 100644 --- a/tests/regression/test_peeled_wi_global_id.c +++ b/tests/regression/test_peeled_wi_global_id.c @@ -74,6 +74,10 @@ int main(int argc, char **argv) { printf("SKIP: The test requires support for SPIR-V 1.0\n"); return 77; } + if (poclu_device_address_bits(device) != 64) { + printf("SKIP: The test's SPIR-V module is 64-bit\n"); + return 77; + } // The reduced kernel's barrier lowers to a sub_group_barrier, so the program // only links on devices whose builtin library has the subgroup builtins. diff --git a/tests/regression/test_rematerialized_alloca_load_with_outside_pr_users.c b/tests/regression/test_rematerialized_alloca_load_with_outside_pr_users.c index 63b120ce4d..53580f8df5 100644 --- a/tests/regression/test_rematerialized_alloca_load_with_outside_pr_users.c +++ b/tests/regression/test_rematerialized_alloca_load_with_outside_pr_users.c @@ -128,6 +128,11 @@ main (int argc, char **argv) printf ("SKIP: The test requires support for SPIR-V 1.0\n"); exit (77); } + if (poclu_device_address_bits (device) != 64) + { + printf ("SKIP: The test's SPIR-V module is 64-bit\n"); + exit (77); + } // Get device name char device_name[128]; diff --git a/tests/regression/test_sanitize_divrem.c b/tests/regression/test_sanitize_divrem.c index ecc87c49a3..bd2f02fc90 100644 --- a/tests/regression/test_sanitize_divrem.c +++ b/tests/regression/test_sanitize_divrem.c @@ -70,6 +70,10 @@ int main(int argc, char **argv) { printf("SKIP: The test requires support for SPIR-V 1.0\n"); return 77; } + if (poclu_device_address_bits(device) != 64) { + printf("SKIP: The test's SPIR-V module is 64-bit\n"); + return 77; + } cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &err); CHECK_ERROR(err); diff --git a/tests/regression/test_spirv_float_controls2.c b/tests/regression/test_spirv_float_controls2.c index 69afd3d5d9..ab8a529502 100644 --- a/tests/regression/test_spirv_float_controls2.c +++ b/tests/regression/test_spirv_float_controls2.c @@ -116,6 +116,10 @@ int main(int argc, char **argv) { printf("SKIP: The test requires support for SPIR-V 1.0\n"); return 77; } + if (poclu_device_address_bits(device) != 64) { + printf("SKIP: The test's SPIR-V module is 64-bit\n"); + return 77; + } size_t extensions_size; CHECK_ERROR(clGetDeviceInfo(device, CL_DEVICE_SPIRV_EXTENSIONS_KHR, 0, NULL, diff --git a/tests/regression/test_spirv_intel_subgroups.c b/tests/regression/test_spirv_intel_subgroups.c index 339a7f9c2d..a853065780 100644 --- a/tests/regression/test_spirv_intel_subgroups.c +++ b/tests/regression/test_spirv_intel_subgroups.c @@ -81,6 +81,10 @@ int main(int argc, char **argv) { printf("SKIP: The test requires support for SPIR-V 1.1\n"); return 77; } + if (poclu_device_address_bits(device) != 64) { + printf("SKIP: The test's SPIR-V module is 64-bit\n"); + return 77; + } if (!poclu_supports_extension(device, "cl_intel_subgroups") || !poclu_supports_extension(device, "cl_intel_required_subgroup_size")) { printf("SKIP: The test requires cl_intel_subgroups and " diff --git a/tests/regression/test_unreachable_kernel.c b/tests/regression/test_unreachable_kernel.c index dd8efffe41..a9c73cefed 100644 --- a/tests/regression/test_unreachable_kernel.c +++ b/tests/regression/test_unreachable_kernel.c @@ -102,6 +102,10 @@ int main(int argc, char **argv) { printf("SKIP: The test requires support for SPIR-V 1.0\n"); return 77; } + if (poclu_device_address_bits(device) != 64) { + printf("SKIP: The test's SPIR-V module is 64-bit\n"); + return 77; + } cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &err); CHECK_ERROR(err); diff --git a/tests/spirv/printf-kernels.cl b/tests/spirv/printf-kernels.cl index 2fe0945763..d6f6f2ce8e 100644 --- a/tests/spirv/printf-kernels.cl +++ b/tests/spirv/printf-kernels.cl @@ -30,6 +30,9 @@ // llvm-spirv printf-kernels.bc // // spirv-val printf-kernels.spv +// +// printf-kernels32.spv is built the same way, with -triple=spir-unknown-unknown +// and llvm-spirv --spirv-max-version=1.0 -o printf-kernels32.spv. global char hello_g[] = "HELLO GLOBAL\n"; global char strings_g[] = "STRiNGS\n"; diff --git a/tests/spirv/printf-kernels32.spv b/tests/spirv/printf-kernels32.spv new file mode 100644 index 0000000000000000000000000000000000000000..b0dc6207779a021b17a5e4e9d6dada7f61c4f75c GIT binary patch literal 15940 zcmcJV37B4Gb;oZqUnVTs2q3b_gnbzX5<-9mFzh>FlP%yd%uJFYlbK;=62cB5LI{iO z`z9(%txK)7*1FVMYpq+Yb*r_asMS`j&m)LhZGXS}-80{r&zS^$9`Ey==RN=PKkqr` zJ@0$(cfVv>rtUVqD5ey%iq_(-Q;PE1s+d~T&>W{#V{0|;#keI_U6&5^4jgl8$H-_; z!TgreHWmBqVmi@^;(lbXyT22M&Vj+suHh9UaGRIhF*lt?ZJ0;>3cYf z8X4*vURzeYwre;tc6JXAjEr^>erR}b#cXBKK1nUjrI)=)R)sYu%hl;k2yNdw`+K~>&ni-@%sZ6WZInJw&it(c3xvbVo~uyX}?TCo$j3W}vD zeRgByL<}>Ocz%UDP@HoRxE`asbExt;EPNK!=PVA4vw4>UURcM+1wOcrPYJxJj?WEz zNF6T=d}tka1tziaIlg7h9rF(?ao-r8U*c6`ctMF*kKuz#JUWIKmiXE+d~k_x8pDf9 zeDfGSq{O$3;X_NjeheR0;thcp)a$!@3|n7I@c_7Qu)dZD(YX(XuVi#>4>5Lk_4jwM zsAuK0x&|B*Vs$i+`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uVx-0Bnc_0GyC`g#{wTkh+d z!PZ)&(x1ov2)aFfl+iU<$7ASsGsgZt4(3zVA?F Date: Sun, 25 Oct 2026 09:14:04 +0100 Subject: [PATCH 5/8] tests: add a SPIR-V test of the address- and ABI-dependent builtins Call the builtins whose SPIR wrappers depend on the address bits (size_t parameters of vloadN/vstoreN, vload_half/vstore_half, async copies and prefetch) or on the calling convention (64-bit vectors that i386 coerces to integers, wide vectors that x86-64 passes in memory, vec3), plus scoped atomics, work_group_barrier and sub-groups, from 32-bit and 64-bit SPIR-V built from the same sources. Double precision and sub-groups are in separate modules so that devices without them still run the rest. --- tests/regression/CMakeLists.txt | 3 + tests/regression/test_spirv_builtins.c | 322 ++++++++++++++++++ tests/regression/test_spirv_builtins.cl | 66 ++++ tests/regression/test_spirv_builtins32.spv | Bin 0 -> 8960 bytes tests/regression/test_spirv_builtins64.spv | Bin 0 -> 9100 bytes tests/regression/test_spirv_builtins_fp64.cl | 11 + .../regression/test_spirv_builtins_fp6432.spv | Bin 0 -> 1852 bytes .../regression/test_spirv_builtins_fp6464.spv | Bin 0 -> 1876 bytes .../test_spirv_builtins_subgroups.cl | 11 + .../test_spirv_builtins_subgroups32.spv | Bin 0 -> 1696 bytes .../test_spirv_builtins_subgroups64.spv | Bin 0 -> 1788 bytes 11 files changed, 413 insertions(+) create mode 100644 tests/regression/test_spirv_builtins.c create mode 100644 tests/regression/test_spirv_builtins.cl create mode 100644 tests/regression/test_spirv_builtins32.spv create mode 100644 tests/regression/test_spirv_builtins64.spv create mode 100644 tests/regression/test_spirv_builtins_fp64.cl create mode 100644 tests/regression/test_spirv_builtins_fp6432.spv create mode 100644 tests/regression/test_spirv_builtins_fp6464.spv create mode 100644 tests/regression/test_spirv_builtins_subgroups.cl create mode 100644 tests/regression/test_spirv_builtins_subgroups32.spv create mode 100644 tests/regression/test_spirv_builtins_subgroups64.spv diff --git a/tests/regression/CMakeLists.txt b/tests/regression/CMakeLists.txt index 4268955668..3b8c53a57c 100644 --- a/tests/regression/CMakeLists.txt +++ b/tests/regression/CMakeLists.txt @@ -31,6 +31,7 @@ set(C_PROGRAMS_TO_BUILD test_assign_loop_variable_to_privvar_makes_it_local test_issue_1711 test_issue_1794 test_issue_1747 test_issue_1958 test_unreachable_kernel test_spirv_float_controls2 + test_spirv_builtins test_spirv_struct_layout test_unreachable_in_infinite_loop test_rematerialized_alloca_load_with_outside_pr_users @@ -196,6 +197,8 @@ add_test_pocl(NAME "regression/test_unreachable_kernel" WORKITEM_HANDLER "loops; add_test_pocl(NAME "regression/test_spirv_float_controls2" WORKITEM_HANDLER "loops;loopvec;cbs;" COMMAND "test_spirv_float_controls2" LABELS ${SPIRV_LABELS}) +add_test_pocl(NAME "regression/test_spirv_builtins" COMMAND "test_spirv_builtins" LABELS ${SPIRV_LABELS}) + add_test_pocl(NAME "regression/test_spirv_struct_layout" WORKITEM_HANDLER "loops;loopvec;cbs;" COMMAND "test_spirv_struct_layout" LABELS ${SPIRV_LABELS}) add_test_pocl(NAME "regression/unreachable_in_infinite_loop" WORKITEM_HANDLER "loops;loopvec;cbs;" COMMAND "test_unreachable_in_infinite_loop") diff --git a/tests/regression/test_spirv_builtins.c b/tests/regression/test_spirv_builtins.c new file mode 100644 index 0000000000..5b34a5960d --- /dev/null +++ b/tests/regression/test_spirv_builtins.c @@ -0,0 +1,322 @@ +// Copyright (c) 2026 PoCL developers +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +/* + Calls builtins from SPIR-V whose SPIR wrappers depend on the device's + address bits (size_t parameters) or on the host calling convention (small + vectors coerced to integers, wide vectors passed in memory, vec3), plus + scoped atomics, work_group_barrier and sub-groups, which the old 32-bit + wrapper lacked. The kernels are in test_spirv_builtins*.cl; the SPIR-V + modules come in 32-bit and 64-bit variants. +*/ + +#include "pocl_opencl.h" + +#include +#include +#include +#ifndef _WIN32 +#include +#endif + +#define CHECK_ERROR(err) \ + if (err != CL_SUCCESS) { \ + printf("OpenCL Error %d at %s:%d\n", err, __FILE__, __LINE__); \ + return 1; \ + } + +static int Failures = 0; + +#define EXPECT(what, i, got, expected) \ + if ((got) != (expected)) { \ + printf("%s[%d]: got %g, expected %g\n", what, (int)(i), (double)(got), \ + (double)(expected)); \ + Failures++; \ + } + +static cl_context Context; +static cl_device_id Device; +static cl_command_queue Queue; + +static cl_program build(const char *name) { + char path[1024]; + snprintf(path, sizeof(path), "%s/%s%u.spv", SRCDIR, name, + poclu_device_address_bits(Device)); + size_t size; + char *binary = poclu_read_binfile(path, &size); + if (binary == NULL) { + printf("Failed to open %s\n", path); + return NULL; + } + cl_int err; + cl_program program = clCreateProgramWithIL(Context, binary, size, &err); + free(binary); + if (err != CL_SUCCESS) { + printf("clCreateProgramWithIL(%s) failed: %d\n", path, err); + return NULL; + } + err = clBuildProgram(program, 1, &Device, NULL, NULL, NULL); + if (err != CL_SUCCESS) { + printf("clBuildProgram(%s) failed: %d\n", path, err); + poclu_show_program_build_log(program); + return NULL; + } + return program; +} + +static cl_mem buffer(size_t size, void *data) { + cl_int err; + cl_mem buf = clCreateBuffer( + Context, CL_MEM_READ_WRITE | (data ? CL_MEM_COPY_HOST_PTR : 0), size, + data, &err); + if (err != CL_SUCCESS) + printf("clCreateBuffer failed: %d\n", err); + return buf; +} + +/* Sets the arguments (buffers, or a NULL buffer for a local argument of + local_size bytes), runs the kernel and reads the buffers back. */ +static int run(cl_program program, const char *name, size_t global, + size_t local, size_t local_size, int nargs, cl_mem *args, + void **results, size_t *sizes) { + cl_int err; + cl_kernel kernel = clCreateKernel(program, name, &err); + CHECK_ERROR(err); + for (int i = 0; i < nargs; i++) { + if (args[i]) + err = clSetKernelArg(kernel, i, sizeof(cl_mem), &args[i]); + else + err = clSetKernelArg(kernel, i, local_size, NULL); + CHECK_ERROR(err); + } + CHECK_ERROR(clEnqueueNDRangeKernel(Queue, kernel, 1, NULL, &global, + local ? &local : NULL, 0, NULL, NULL)); + for (int i = 0; i < nargs; i++) + if (args[i] && results[i]) + CHECK_ERROR(clEnqueueReadBuffer(Queue, args[i], CL_TRUE, 0, sizes[i], + results[i], 0, NULL, NULL)); + for (int i = 0; i < nargs; i++) + if (args[i]) + clReleaseMemObject(args[i]); + clReleaseKernel(kernel); + return 0; +} + +static int test_size_t_args(cl_program program) { + cl_float f[16], out[11] = {0}; + for (int i = 0; i < 16; i++) + f[i] = (cl_float)i; + cl_half h[4] = {0, 0, 0x3e00 /* 1.5 */, 0}, ho[4] = {0}; + + cl_mem args[] = {buffer(sizeof(f), f), buffer(sizeof(h), h), + buffer(sizeof(ho), ho), buffer(sizeof(out), out), NULL}; + void *results[] = {NULL, NULL, ho, out, NULL}; + size_t sizes[] = {0, 0, sizeof(ho), sizeof(out), 0}; + if (run(program, "size_t_args", 1, 1, 8 * sizeof(cl_float), 5, args, + results, sizes)) + return 1; + + for (int i = 4; i < 8; i++) + EXPECT("vstore4", i, out[i], 2.0f * i); + EXPECT("vload_half", 0, out[8], 1.5f); + EXPECT("vstore_half", 0, ho[3], 0x4100 /* 2.5 */); + EXPECT("async_work_group_copy", 0, out[9], 7.0f); + EXPECT("async_work_group_strided_copy", 0, out[10], 6.0f); + return 0; +} + +static int test_small_vectors(cl_program program) { + cl_char c[24] = {100, 100, -100, -100, 1, 2, 3, 4, + 100, -50, -100, 50, 5, 6, 7, 8}; + cl_short s[12] = {1, -2, 3, -4, -1, 2, -3, 4}; + cl_int i[6] = {7, -7, 2, -2}; + + cl_mem args[] = {buffer(sizeof(c), c), buffer(sizeof(s), s), + buffer(sizeof(i), i)}; + void *results[] = {c, s, i}; + size_t sizes[] = {sizeof(c), sizeof(s), sizeof(i)}; + if (run(program, "small_vectors", 1, 0, 0, 3, args, results, sizes)) + return 1; + + const cl_char c_exp[8] = {127, 50, -128, -50, 6, 8, 10, 12}; + for (int k = 0; k < 8; k++) + EXPECT("add_sat(char8)", k, c[16 + k], c_exp[k]); + for (int k = 0; k < 4; k++) + EXPECT("max(short4)", k, s[8 + k], k + 1); + EXPECT("hadd(int2)", 0, i[4], 4); + EXPECT("hadd(int2)", 1, i[5], -5); + return 0; +} + +static int test_wide_vectors(cl_program program) { + cl_float f8[32], f16[48], f3[10] = {1, 2, 3, 4, 5, 6}; + for (int k = 0; k < 8; k++) { + f8[k] = (cl_float)k; + f8[8 + k] = 2.0f; + f8[16 + k] = 1.0f; + } + for (int k = 0; k < 16; k++) { + f16[k] = (cl_float)k; + f16[16 + k] = (cl_float)(15 - k); + } + + cl_mem args[] = {buffer(sizeof(f8), f8), buffer(sizeof(f16), f16), + buffer(sizeof(f3), f3)}; + void *results[] = {f8, f16, f3}; + size_t sizes[] = {sizeof(f8), sizeof(f16), sizeof(f3)}; + if (run(program, "wide_vectors", 1, 0, 0, 3, args, results, sizes)) + return 1; + + for (int k = 0; k < 8; k++) + EXPECT("fma(float8)", k, f8[24 + k], 2.0f * k + 1.0f); + for (int k = 0; k < 16; k++) + EXPECT("fmax(float16)", k, f16[32 + k], k > 7 ? k : 15 - k); + const cl_float cross_exp[3] = {-3, 6, -3}; + for (int k = 0; k < 3; k++) + EXPECT("cross(float3)", k, f3[6 + k], cross_exp[k]); + EXPECT("dot(float3)", 0, f3[9], 32.0f); + return 0; +} + +static int test_sync(cl_program program) { + cl_int counter = 0, out[16] = {0}; + cl_mem args[] = {buffer(sizeof(counter), &counter), NULL, + buffer(sizeof(out), out)}; + void *results[] = {&counter, NULL, out}; + size_t sizes[] = {sizeof(counter), 0, sizeof(out)}; + if (run(program, "sync", 16, 8, 8 * sizeof(cl_int), 3, args, results, + sizes)) + return 1; + + for (int k = 0; k < 16; k++) + EXPECT("work_group_barrier", k, out[k], (k % 8 + 1) % 8); + EXPECT("atomic_fetch_add_explicit", 0, counter, 16); + return 0; +} + +static int test_subgroups(cl_program program) { + cl_int out[32]; + memset(out, 0xff, sizeof(out)); + cl_mem args[] = {buffer(sizeof(out), out)}; + void *results[] = {out}; + size_t sizes[] = {sizeof(out)}; + if (run(program, "subgroups", 16, 16, 0, 1, args, results, sizes)) + return 1; + + for (int k = 0; k < 16; k++) { + EXPECT("sub_group_reduce_add", k, out[2 * k], 0); + EXPECT("sub_group_broadcast", k, out[2 * k + 1], 0); + } + return 0; +} + +static int test_fp64(cl_program program) { + cl_double d4[16], d3[9] = {1, 2, 3, 4, 5, 6}; + for (int k = 0; k < 4; k++) { + d4[k] = k + 1; + d4[4 + k] = 2.0; + d4[8 + k] = 0.5; + } + + cl_mem args[] = {buffer(sizeof(d4), d4), buffer(sizeof(d3), d3)}; + void *results[] = {d4, d3}; + size_t sizes[] = {sizeof(d4), sizeof(d3)}; + if (run(program, "fp64", 1, 0, 0, 2, args, results, sizes)) + return 1; + + for (int k = 0; k < 4; k++) + EXPECT("fma(double4)", k, d4[12 + k], 2.0 * (k + 1) + 0.5); + const cl_double cross_exp[3] = {-3, 6, -3}; + for (int k = 0; k < 3; k++) + EXPECT("cross(double3)", k, d3[6 + k], cross_exp[k]); + return 0; +} + +int main(int argc, char **argv) { + cl_uint platform_index = argc > 1 ? (cl_uint)atoi(argv[1]) : 0; + cl_int err; + +#ifndef _WIN32 + alarm(300); +#endif + + cl_uint num_platforms; + CHECK_ERROR(clGetPlatformIDs(0, NULL, &num_platforms)); + if (platform_index >= num_platforms) { + printf("Platform index %u out of range\n", platform_index); + return 1; + } + cl_platform_id *platforms = malloc(sizeof(cl_platform_id) * num_platforms); + CHECK_ERROR(clGetPlatformIDs(num_platforms, platforms, NULL)); + cl_platform_id platform = platforms[platform_index]; + free(platforms); + + CHECK_ERROR(clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &Device, NULL)); + + if (!poclu_device_supports_il(Device, "SPIR-V_1.0")) { + printf("SKIP: The test requires support for SPIR-V 1.0\n"); + return 77; + } + + Context = clCreateContext(NULL, 1, &Device, NULL, NULL, &err); + CHECK_ERROR(err); + Queue = clCreateCommandQueueWithProperties(Context, Device, NULL, &err); + CHECK_ERROR(err); + + cl_program program = build("test_spirv_builtins"); + if (program == NULL) + return 1; + if (test_size_t_args(program) || test_small_vectors(program) || + test_wide_vectors(program) || test_sync(program)) + return 1; + clReleaseProgram(program); + + cl_uint max_sub_groups = 0; + CHECK_ERROR(clGetDeviceInfo(Device, CL_DEVICE_MAX_NUM_SUB_GROUPS, + sizeof(max_sub_groups), &max_sub_groups, NULL)); + if (max_sub_groups > 0) { + program = build("test_spirv_builtins_subgroups"); + if (program == NULL || test_subgroups(program)) + return 1; + clReleaseProgram(program); + } else + printf("The device doesn't support sub-groups, skipping those.\n"); + + cl_device_fp_config fp64_config = 0; + CHECK_ERROR(clGetDeviceInfo(Device, CL_DEVICE_DOUBLE_FP_CONFIG, + sizeof(fp64_config), &fp64_config, NULL)); + if (fp64_config != 0) { + program = build("test_spirv_builtins_fp64"); + if (program == NULL || test_fp64(program)) + return 1; + clReleaseProgram(program); + } else + printf("The device doesn't support doubles, skipping those.\n"); + + clReleaseCommandQueue(Queue); + clReleaseContext(Context); + + if (Failures) { + printf("FAIL: %d mismatches\n", Failures); + return 1; + } + printf("OK\n"); + return 0; +} diff --git a/tests/regression/test_spirv_builtins.cl b/tests/regression/test_spirv_builtins.cl new file mode 100644 index 0000000000..c2e912dd19 --- /dev/null +++ b/tests/regression/test_spirv_builtins.cl @@ -0,0 +1,66 @@ +/* Kernels for test_spirv_builtins.c, calling builtins whose SPIR wrappers + depend on the address bits or the calling convention of the host. Built + to test_spirv_builtins{32,64}.spv, with spir and spir64 respectively: + + clang --target=spir -cl-std=CL2.0 -O0 \ + -Xclang -finclude-default-header -emit-llvm -c \ + test_spirv_builtins.cl -o builtins.bc + llvm-spirv --spirv-max-version=1.0 builtins.bc \ + -o test_spirv_builtins32.spv + + The double precision and sub-group kernels are in + test_spirv_builtins_{fp64,subgroups}.cl, so that devices without these + features still run the others. +*/ + +/* size_t parameters */ +kernel void +size_t_args (global const float *f, global const half *h, global half *ho, + global float *out, local float *l) +{ + float4 v = vload4 (1, f); + vstore4 (v * 2.0f, 1, out); + out[8] = vload_half (2, h); + vstore_half (out[8] + 1.0f, 3, ho); + + prefetch (f, 4); + event_t e = async_work_group_copy (l, f, 8, 0); + wait_group_events (1, &e); + out[9] = l[7]; + e = async_work_group_strided_copy (l, f, 4, 2, 0); + wait_group_events (1, &e); + out[10] = l[3]; +} + +/* 64-bit vector arguments, coerced to i64 on i386 */ +kernel void +small_vectors (global char8 *c, global short4 *s, global int2 *i) +{ + c[2] = add_sat (c[0], c[1]); + s[2] = max (s[0], s[1]); + i[2] = hadd (i[0], i[1]); +} + +/* vectors that x86-64 passes in memory, and vec3 */ +kernel void +wide_vectors (global float8 *f8, global float16 *f16, global float *f3) +{ + f8[3] = fma (f8[0], f8[1], f8[2]); + f16[2] = fmax (f16[0], f16[1]); + float3 a = vload3 (0, f3); + float3 b = vload3 (1, f3); + vstore3 (cross (a, b), 2, f3); + f3[9] = dot (a, b); +} + +/* scoped atomics and barriers */ +kernel void +sync (global atomic_int *counter, local int *tmp, global int *out) +{ + int lid = get_local_id (0); + tmp[lid] = lid; + work_group_barrier (CLK_LOCAL_MEM_FENCE, memory_scope_work_group); + out[get_global_id (0)] = tmp[(lid + 1) % get_local_size (0)]; + atomic_fetch_add_explicit (counter, 1, memory_order_relaxed, + memory_scope_device); +} diff --git a/tests/regression/test_spirv_builtins32.spv b/tests/regression/test_spirv_builtins32.spv new file mode 100644 index 0000000000000000000000000000000000000000..45d1399cc1c1822a28eff7e321ed17cc2e5a5d25 GIT binary patch literal 8960 zcmai(2bi5z5r*$(H$9sW(jWn{Aq7H08YF-StRRFa7$Yc%$|cRPve^y0n?R@mr72)k z?7fR5gd!y>Md|k53t~s?4GZOc|D54Dd$`e?XPz_PH*;p@%sJ=3H~Tjam^!#tYpRW` z4XQ0_s#TxSwE?vjG{=Ey9F#_!D}G2C$ER^d8uwuw&MZSMUAMaHsN?4J_N}TBzq#TD zz>gxA@kSxN9p|jB_tls8tmy?0uK2U%*DmkutZ!Jovah?RxANU#y8->Ij#aBO6Z3{t z^O{K7yRmB}E>+#;u-;wBZLY~kbM>!QYj17F$4YCpdcAjDN6&`(k?T7;`<8Sa*S&Ii z=aQ}s41FElT}!Cmc*Ck3h3`q-J!h=x>0ZC?1lF;`Z+Mln@LSy3z2aFx%|Eruzp`_A z*P43w%Fg;3t9!cY9c$Os^Tt&9hu1FMsc-*g8TXEz`4-I^SQ}a!N#E-AMm6kc=Hgmw z)u)+N%>Umj_kJ;bwzr;-#hfPf;mD*4kEnXtAl|e38L`~Uh^20<-K$uwRlgg=YS{CL z=edY@>c-onir2z$Dyla8SBpm)@3p}B~)}6`EW1$5^JC4^81tCZ6OJ{_D6sc9_usd`vkI(l?!SM5=M;Euffpof@2z)XVc(dr z&mHaO6!_c%UyyL@$)*Bd+z+=_cWdW8?SH?RTGen_iV-zkUf?SVd}YE>(^Un&y1+Lk z+{WmdZ%Vj5;hPhVc()e#_5yG3hg+*>#7@^-JSUi1)o^Eu(U$OC3AZPFcfwKAJq5nE z!1opS!Gz-+JXGKTT;TkiH5a(0z=I1sw7|pq;o;S@aHlcpUk>t8IuMaW|u9&yTo=(Z2bamHZDuC(JYWXmsO*{aAEk1YU;ToZ%DE z-OI3_ith6=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p=6FAH zH4-`8qx=UD_h>)XF)s3d5W89a55en;J&Mf}xm~{&{9(j14&FV=eoOF9PUy6TEsn?$2!JE{`HBEHPPdB@cLqpV)H~?`F!1yd^e+g zrfxvrn(Ujl0|7uRG9pBJq6Pg?)F1r(xfduy@K>b4M?7##Z z`7Ao-@*s9TmxnU!TprHwqu7rX`0<3Dk-4lL`;arAJ>;A@?IpOF+vniS5xjTBd43+z z7x(#k>@OtV*bXFed=a}@jxWLMi~DSjFC+40j<3Kq%kfosecoB?nd57SeB|(VH~Ft4 zJ`-Ca_G&F-qt9<(H>>eYczw$e=O;E-geW4n;Z z@m=g@Ilc$4FJ@(q?<4Y&!)IUq2Z;OJ3bBrHk^c$oX8C^zuP>f`v3Vl5>%Ff(LcA;T z?lJyP^J8p%&iWDbPY`?X{o%g#w<62{A)OSwmSR zmZkapHu;`L`-%NWp5MV)EAspvTdvIW2RMCY9`AzZ@JGblCnDA~K4$kP>}Iq3GrYd| zKhIyV&9NRapLfKV==B-we9wOc%ay(U4NhO#YvlPmzI@OB0Lztmo`us_=DCV<83X@M z#9GG1UjK!i@6~71`|QT_bt9gu*!9+IL&|r%-zDqw?{>b={rjBXJ!t#4Ilp%Z-tQcI zw~t2qZuf6`e(x}f^y* z0ru~g`h2gQ!Z{v|o&nZpZF>_N?;Wy^F*D)x<-F%H3$b5$&pG0^hs)y!$Y#tA@cO*N zuHO+chrIR0)`~h$uWPMkCK K`zduiTmJ@_#PmY| literal 0 HcmV?d00001 diff --git a/tests/regression/test_spirv_builtins_fp64.cl b/tests/regression/test_spirv_builtins_fp64.cl new file mode 100644 index 0000000000..ff98c314af --- /dev/null +++ b/tests/regression/test_spirv_builtins_fp64.cl @@ -0,0 +1,11 @@ +/* Double precision kernels for test_spirv_builtins.c, built like + test_spirv_builtins.cl to test_spirv_builtins_fp64{32,64}.spv. */ + +kernel void +fp64 (global double4 *d4, global double *d3) +{ + d4[3] = fma (d4[0], d4[1], d4[2]); + double3 a = vload3 (0, d3); + double3 b = vload3 (1, d3); + vstore3 (cross (a, b), 2, d3); +} diff --git a/tests/regression/test_spirv_builtins_fp6432.spv b/tests/regression/test_spirv_builtins_fp6432.spv new file mode 100644 index 0000000000000000000000000000000000000000..6bee0ec4e87cdfa7336113ac268c80f0afc9eb79 GIT binary patch literal 1852 zcmaKr+fGwa5QbN&qSyi=0-h~aK}GRgK;)n(-k9_eb`0VnVr|qL6W>T5&>IuKuU%ud zO+(2r^Z#>PYt62XG>@fJNfT)_?WX>3DvhKgnChchk7j)$>jiWTZw1}%?ss-xEr0#? zCQ+x_<3`{o@tb!XdE0G0MB()>rS0)5-m!EFyD0V!UU%LVpZ5-mkNaOb#fMMbA}73L zk}+a#Aq_l1z1Q$BVtb!~J-c@}4J$tzcZxknO=r`uZt&kXR08`ZVq@m9 zSb$y~Ieq5T(eiTQiH!Bz<1E^IMgKXp@$%w3XzwiiKE8fusK6R`KihH}NQ-Ws$2_(1 zE5tg3JD_cU-~TreHS{_aoz)#MUhJ&yfOwN^edb%!UUK@a6Wj)s?Q;?_zRcTm3Na`6 zHR82r5O>%-WBzcuRV2=$&$#kg+_5-|`{h|?(Qy`ctb7)CEU@?Nj+L=HCiYzBT0iEL zGv7YJ#aS=H86W&EvHkZ>NuPUZtamn#G!SFeQR52suo_q4^)+*>HLfA@gEbc5hSj(Z zuWu2FIsA_0qeh)=vGz@*f_Oj9YA<7B&L!+&J#NG6^PBRn#MX-X=KKE3i1#ROzwi8a z$L}KgoWq^Ihd9Si#QW3lH_&DS&3k|t)2)|$rrAj0qD5#k#=kG463^R(cG&9efp zFXmarj(L0w{pESqz{VUl&tv@VnDc0x6Z6E(>u}B-@AL#)F5=qxem3Fs`Mvv#^GBU6 zID18%ZEU&0I#1#B4c4jiCHM}{5Np3j>}hz#>6-N E7b9mg!fYj|p-Ms3PC4Kroy*8+E1MILmm|YM+l8BQH?XJJmF$Q_Wv>8)}i;JmGWnH^9&ccnCw4a0PFRp$E?hM23GHADl3aEbfvn;j+ zwW#KKjFaoXhOa%i6Ux?iAO7IsZf=s%Ufl`()$P@tP~Rq6oAHrbOuKmk+aj}dPD1(@ zacj;%#st2Bzw#X9P8+AsUrx6U#aXoJS3HY57iV$bJj*;h&f?A$&*IL7?wsAZqVCSA zdoE+mAAO1$Z=Jy6tQW!b4}2Hj;eDs1%{|rE`&onn%UPJ*C6q7 zjwP^BIj)0iTZWbwN+;W=dP50EwWkGtGK9yPlc;M$y>^_A^Uf9AvYT^H-T1fSimoIReJ1F+pwCHH6fH=9=(W@L z2YZ9zC#U|%$BK&ATv=$&ElCEWqvL)y>J4OrB{H`liTs~)Z>y2wAUc;MgI=e9lDr#r zy2D0V?`B8MZX-R(TFqf6OBXYO0>&A2kQUn}$`-qGPrsX?2_F zagw#V$>(-IO*&tCNp6U`usQ3_f1Z~;)ioc189T?^pahGw>#6G9312IN0E9 zdz_k|`4pU)a~m#qVz}7gf>qZ`s7l|H@FwujPWVfHZ)4umcc(VrzdF%h^1ONc3%UHd z_;^#Xgx_xPFOS{7{&o3LE+5NgHmkoS8=MXGQ-_U?up%4DoVx@0ILeAnZ1ILm)BE#!q~jpF4$rUE270 zPw?Zj3+~mxu2>fc1^-w$nhSS6At2ryHFU{ZYstb z;TKEbqvnQ$Gg+dy+p;;g)f&c4#o)F0kAQJoG2R{deZ|=K9SJz(I4?e2 z)@zu2PkGGwFvnfRnS(qtTm7!=e7(i_u6Rp^Z}Z((j2`k9+mj7GIr=&81IetJA1a>b ivzZ?$&dlV$g*`l$O+1#^9-hbsn;d(( literal 0 HcmV?d00001 diff --git a/tests/regression/test_spirv_builtins_subgroups64.spv b/tests/regression/test_spirv_builtins_subgroups64.spv new file mode 100644 index 0000000000000000000000000000000000000000..9fead61510d2b34b299025616a76cf391b24ae77 GIT binary patch literal 1788 zcma)*+fGwK6o#klS}3I;0^-@Wpn_FAbBNIpNo<;s7{deXl-iKSx?6kT!Ye~~8Q;(w z6aR0Rm28`8oSl_*{?}n9K$0z;ns5g)d=8PyWiu~u?ele0AMCamo&};Wk<9DNW zXIM{ao$hg?Q%_F2&Bn0ZP3kJ6xV*<0i#-Zuj@sW^iYfXUe~CF1-Z-psX5EtSq1kC9 zCvmsgi9fgcN!jgj01iU|HG9312ILP3v zdmOetu`k1!IJe=FYq-eZ(o;<@VqW}_h_`{h7$~R)c2u=vu;afhPOjLhaBhpgRvh)fp(Z*x>?f^r zPw1QKio83bZDmo9e~AZztqXD$m(Msug|?xpLb^UxqIrPvkUIt`oTwz)ukWye?!D>u$M$1r6J!G;p6;J zEVjEM_JWT$@>O;0{orG6YL-OAv-g=y&d01tE{ix75%tMk7qK6UKNAM_dm?i1+wSg5 zW)5O)r^G%GQP(ie0|x)mM)3F54gQBB?C%xBeN;u@VyAy}Y8#gI$v>8^F&*aGlAXEm z^X4u7iR5&=*`LbJTQhu{_nB8I&9lVe{X$LQ5PuH^@ypo+A;Qt=>vMm{V aMPz%~k&NB;vMZTd*x3s@{aD}jMt=h{{GE{i literal 0 HcmV?d00001 From ea818ce9ee95d1ab78909bfe0150c9c018212926 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Sun, 25 Oct 2026 09:18:29 +0100 Subject: [PATCH 6/8] Enable SPIR-V on 32-bit x86 CPU hosts SPIR-V was disabled on 32-bit hosts in #1883 after spirv/printf crashed on Debian's i386, armel and armhf builds (#1880), until the 32-bit support was finished. The crash itself (a double free on the error path for 64-bit modules) has since been fixed, and with the generated i386 SPIR wrapper and the preserved struct layouts, SPIR-V works on i386 System V hosts. ARM32, RISC-V32 and 32-bit Windows stay disabled: the wrapper generator doesn't know their ABIs. --- CMakeLists.txt | 6 ++++-- doc/sphinx/source/notes_7_3.rst | 9 +++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6c208aaa15..4c481932a1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1323,12 +1323,14 @@ endif() find_package(Python3 3.8 COMPONENTS Interpreter) # Determine whether we can use SPIRV on the host CPU device -# - we don't have a useful SPIRV wrapper for 32bit SPIRV +# - of the 32bit targets, the SPIRV wrapper generator only knows +# the ABI of i386 System V (not ARM32, RISC-V32 or 32bit Windows) # - on Windows/MSVC there's a mangling mismatch between # Clang (compiling the kernellib with MSVC function names) # and the SPIRV wrapper (only supporting Itanium mangling) set(HOST_CPU_ENABLE_SPIRV OFF) -if(ENABLE_HOST_CPU_DEVICES AND ENABLE_SPIRV AND (NOT MSVC) AND (HOST_DEVICE_ADDRESS_BITS MATCHES "64")) +if(ENABLE_HOST_CPU_DEVICES AND ENABLE_SPIRV AND (NOT MSVC) AND + ((HOST_DEVICE_ADDRESS_BITS MATCHES "64") OR (I386 AND NOT WIN32))) set(HOST_CPU_ENABLE_SPIRV ON) endif() diff --git a/doc/sphinx/source/notes_7_3.rst b/doc/sphinx/source/notes_7_3.rst index b5296e142f..0d8cb1b504 100644 --- a/doc/sphinx/source/notes_7_3.rst +++ b/doc/sphinx/source/notes_7_3.rst @@ -94,6 +94,15 @@ CPU driver * Fixed use of an uninitialised kernel-library fallback name when `LLC_HOST_CPU` is set. +* SPIR-V is now supported on 32-bit x86 (i386 System V, e.g. i686 Linux), + using a generated SPIR builtin wrapper instead of the old scalar-only one. + Other 32-bit hosts still have SPIR-V disabled. + +* Struct types in SPIR-V modules keep the OpenCL C layout (8-byte aligned + `long` and `double`) on hosts whose ABI aligns these types less, such as + i386. Previously, field offsets, struct sizes and array strides silently + followed the host layout. + =================================== Deprecation/feature removal notices =================================== From 0d3d50eb0ce4184518c2718e9681bc1cd0f43bad Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Sun, 25 Oct 2026 15:05:41 +0100 Subject: [PATCH 7/8] cmake: only look for SVML on x86-64 The search for the static SVML and IRC libraries in the oneAPI compiler directory also ran on 32-bit x86 (I386 and X32 set X86 too), where it finds the x86-64 archives, as oneAPI no longer ships ia32 libraries. These were then linked into the 32-bit kernels, which crashed in vectorized math builtins. --- CMakeLists.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4c481932a1..aaab62309a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1046,7 +1046,8 @@ file(RELATIVE_PATH POCL_INSTALL_FROM_LIB_TO_PRIVATE_LIBDIR ###################################################################################### set(HAVE_LIBSVML 0) -if(X86) +# oneAPI only ships SVML for x86-64; linking it into 32-bit kernels crashes them +if(X86_64) set(ORIG_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES}) # use static libraries, so that the poclbinary is independent of system set(CMAKE_FIND_LIBRARY_SUFFIXES .a) From 991a6afba9b82cf0421c1fb92501d3ed173bf933 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Sun, 25 Oct 2026 09:35:46 +0100 Subject: [PATCH 8/8] ci: build and test on i686 Linux Run the CPU tests in an i386 Debian container on a GitHub-hosted runner. Debian testing, because the CPU JIT needs LLVM 21 on i386 (R_386_GOT32X support in JITLink), and with -msse2 because Debian's i386 baseline lacks the SSE the FTZ handling needs (#2097). The tests that fail on i686 regardless of SPIR-V are excluded. --- .github/workflows/build_linux_i686.yml | 78 ++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 .github/workflows/build_linux_i686.yml diff --git a/.github/workflows/build_linux_i686.yml b/.github/workflows/build_linux_i686.yml new file mode 100644 index 0000000000..e6bab89ab4 --- /dev/null +++ b/.github/workflows/build_linux_i686.yml @@ -0,0 +1,78 @@ +--- +name: Linux / CPU i686 on GH tests + +permissions: + contents: read + +on: + push: + branches: + - 'main' + - 'release*' + workflow_dispatch: + pull_request: + paths-ignore: + - 'doc/**' + - 'CHANGES' + - 'COPYING' + - 'CREDITS' + - 'LICENSE' + - 'README.*' + - 'tools/docker/**' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref || github.run_id }} + cancel-in-progress: true + +jobs: + # Builds and tests 32-bit x86 PoCL in an i386 Debian container; setarch + # makes uname report i686, which CMake uses as the system processor. + # Debian testing because its LLVM is new enough for the CPU JIT on i386 + # (JITLink supports R_386_GOT32X since LLVM 21). + i686_test: + name: LLVM ${{ matrix.llvm }} - i686 + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + llvm: [21] + + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + + - name: Build and test PoCL + timeout-minutes: 120 + env: + LLVM_VERSION: ${{ matrix.llvm }} + # Fail on i686 independently of this job: printf of LONG_MIN, + # signal handlers (SIGFPE avoidance is x86-64 only), allocations + # beyond the 32-bit address space and image conversion rounding. + KNOWN_FAILURES: "kernel/test_printf_(loopvec|cbs)$|regression/test_issue_2005|regression/test_signal_handlers|runtime/test_image_normalized_conv" + run: | + cat > ${{ runner.temp }}/build.sh <<'EOF' + set -ex + apt-get update -y + apt-get install -y --no-install-recommends \ + build-essential cmake ninja-build pkg-config python3 zlib1g-dev \ + libhwloc-dev clang-$LLVM_VERSION llvm-$LLVM_VERSION-dev \ + libclang-$LLVM_VERSION-dev libclang-cpp$LLVM_VERSION-dev \ + libpolly-$LLVM_VERSION-dev libllvmspirvlib-$LLVM_VERSION-dev \ + llvm-spirv-$LLVM_VERSION + # Debian's i386 baseline has no SSE, which the FTZ handling + # requires (#2097). + cmake -S /pocl -B /build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo \ + -DCMAKE_C_FLAGS=-msse2 -DCMAKE_CXX_FLAGS=-msse2 \ + -DWITH_LLVM_CONFIG=/usr/bin/llvm-config-$LLVM_VERSION \ + -DENABLE_ICD=OFF -DKERNELLIB_HOST_CPU_VARIANTS=distro + grep -q "define HOST_CPU_ENABLE_SPIRV" /build/config.h + ninja -C /build + cd /build + export POCL_CACHE_DIR=/tmp/pocl_cache + /pocl/tools/scripts/run_cpu_tests -j$(nproc) --output-on-failure \ + -E "$KNOWN_FAILURES" + EOF + docker run --rm --platform linux/386 \ + -v ${{ github.workspace }}:/pocl -v ${{ runner.temp }}:/scripts \ + -e LLVM_VERSION -e KNOWN_FAILURES \ + i386/debian:testing setarch i686 bash /scripts/build.sh