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 diff --git a/CMakeLists.txt b/CMakeLists.txt index 6c208aaa15..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) @@ -1323,12 +1324,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/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/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 =================================== diff --git a/examples/example1/example1.spirv32 b/examples/example1/example1.spirv32 new file mode 100644 index 0000000000..e1d3b979ed Binary files /dev/null and b/examples/example1/example1.spirv32 differ 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/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 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) 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/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/CMakeLists.txt b/tests/regression/CMakeLists.txt index a17a518440..3b8c53a57c 100644 --- a/tests/regression/CMakeLists.txt +++ b/tests/regression/CMakeLists.txt @@ -31,6 +31,8 @@ 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 test_peeled_wi_global_id @@ -195,6 +197,10 @@ 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") 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_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_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 0000000000..45d1399cc1 Binary files /dev/null and b/tests/regression/test_spirv_builtins32.spv differ diff --git a/tests/regression/test_spirv_builtins64.spv b/tests/regression/test_spirv_builtins64.spv new file mode 100644 index 0000000000..a6626b7359 Binary files /dev/null and b/tests/regression/test_spirv_builtins64.spv differ 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 0000000000..6bee0ec4e8 Binary files /dev/null and b/tests/regression/test_spirv_builtins_fp6432.spv differ diff --git a/tests/regression/test_spirv_builtins_fp6464.spv b/tests/regression/test_spirv_builtins_fp6464.spv new file mode 100644 index 0000000000..09575d77b4 Binary files /dev/null and b/tests/regression/test_spirv_builtins_fp6464.spv differ diff --git a/tests/regression/test_spirv_builtins_subgroups.cl b/tests/regression/test_spirv_builtins_subgroups.cl new file mode 100644 index 0000000000..3ec7dfc082 --- /dev/null +++ b/tests/regression/test_spirv_builtins_subgroups.cl @@ -0,0 +1,11 @@ +/* Sub-group kernels for test_spirv_builtins.c, built like + test_spirv_builtins.cl to test_spirv_builtins_subgroups{32,64}.spv. */ + +kernel void +subgroups (global int *out) +{ + int gid = get_global_id (0); + out[2 * gid] = sub_group_reduce_add (1) - (int)get_sub_group_size (); + out[2 * gid + 1] = sub_group_broadcast (gid, 0) + - (gid - (int)get_sub_group_local_id ()); +} diff --git a/tests/regression/test_spirv_builtins_subgroups32.spv b/tests/regression/test_spirv_builtins_subgroups32.spv new file mode 100644 index 0000000000..0d78368c9b Binary files /dev/null and b/tests/regression/test_spirv_builtins_subgroups32.spv differ diff --git a/tests/regression/test_spirv_builtins_subgroups64.spv b/tests/regression/test_spirv_builtins_subgroups64.spv new file mode 100644 index 0000000000..9fead61510 Binary files /dev/null and b/tests/regression/test_spirv_builtins_subgroups64.spv differ 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_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 0000000000..afa3388930 Binary files /dev/null and b/tests/regression/test_spirv_struct_layout32.spv differ diff --git a/tests/regression/test_spirv_struct_layout64.spv b/tests/regression/test_spirv_struct_layout64.spv new file mode 100644 index 0000000000..9eac511e60 Binary files /dev/null and b/tests/regression/test_spirv_struct_layout64.spv differ 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 0000000000..b0dc620777 Binary files /dev/null and b/tests/spirv/printf-kernels32.spv differ diff --git a/tests/spirv/printf.cc b/tests/spirv/printf.cc index 538e32995a..ed159b62f8 100644 --- a/tests/spirv/printf.cc +++ b/tests/spirv/printf.cc @@ -86,7 +86,15 @@ int main(int, char **) { if (Err != CL_SUCCESS) return EXIT_FAILURE; - std::ifstream File(SRCDIR "/printf-kernels.spv", std::ios::binary | std::ios::ate); + cl_uint AddressBits; + Err = clGetDeviceInfo (Device, CL_DEVICE_ADDRESS_BITS, sizeof (AddressBits), + &AddressBits, NULL); + if (Err != CL_SUCCESS) + return EXIT_FAILURE; + + std::ifstream File(AddressBits == 32 ? SRCDIR "/printf-kernels32.spv" + : SRCDIR "/printf-kernels.spv", + std::ios::binary | std::ios::ate); std::streamsize Binsize = File.tellg(); File.seekg(0, std::ios::beg);