diff --git a/README.md b/README.md index 9d914d4..6af3f1a 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,39 @@ std::vector binary; int err = translator.translate(binary, &srcgen); ``` +Diagnostics are printed to stderr, unless a handler is installed with +`translator.set_diagnostic_handler`. + +## C API + +For use from C, or from languages that can call C but not C++, the build also +produces a shared library, `libspirv2clc`, with the C API declared in +`libspirv2clc.h`. It exports nothing but that API, with the translator and +SPIRV-Tools linked in, so it has no dependencies besides the C and C++ runtime +libraries: + +``` +#include "libspirv2clc.h" + +SPIRV2CLCTranslateOptions options = { + 1, 4, /* validate as SPIR-V 1.4 */ + 300 /* emit OpenCL C 3.0 */ +}; +char *source, *message; +if (SPIRV2CLCTranslate(binary, size_in_bytes, &options, NULL, NULL, &source, + &message)) { + fprintf(stderr, "%s\n", message); + SPIRV2CLCDisposeMessage(message); +} else { + /* use source */ + SPIRV2CLCDisposeMessage(source); +} +``` + +Pass a callback to receive the diagnostics (including warnings) instead of +having them printed to stderr. `cmake --install . --component c_api` installs +only the library and its header. + ## Installation To install the library, first check you're building with the right CMake variables set: diff --git a/include/libspirv2clc.h b/include/libspirv2clc.h new file mode 100644 index 0000000..314340e --- /dev/null +++ b/include/libspirv2clc.h @@ -0,0 +1,80 @@ +/* Copyright 2020-2022 The spirv2clc authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* The C API of spirv2clc, for using the translator in-process from languages + * that can't call C++, as an alternative to running the `spirv2clc` tool. + * + * Conventions follow llvm-c: status as the return value (0 = success), the + * result and an error message returned through out-pointers and freed with + * SPIRV2CLCDisposeMessage, and diagnostics delivered through an optional + * callback. Calls are independent of each other and may run concurrently. */ + +#ifndef LIBSPIRV2CLC_H +#define LIBSPIRV2CLC_H + +#include + +#if defined(_WIN32) +#define SPIRV2CLC_API __declspec(dllexport) +#else +#define SPIRV2CLC_API __attribute__((visibility("default"))) +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + SPIRV2CLCDSError = 0, + SPIRV2CLCDSWarning = 1, + SPIRV2CLCDSRemark = 2 +} SPIRV2CLCDiagnosticSeverity; + +/* Receives every diagnostic the translator emits, one message per call, + * without a trailing newline. NULL means: print them to stderr. Errors are + * also collected into the failure message returned by SPIRV2CLCTranslate. */ +typedef void (*SPIRV2CLCDiagnosticCallback)( + SPIRV2CLCDiagnosticSeverity Severity, const char *Message, void *Context); + +typedef struct { + /* SPIR-V version whose rules the module is validated against, e.g. 1 and 4 + * (`--spirv-version=1.4`). 0/0 selects the OpenCL 1.2 environment, which is + * also the tool's default. */ + unsigned SPIRVVersionMajor, SPIRVVersionMinor; + /* OpenCL C version to emit for, encoded as in CL_TARGET_OPENCL_VERSION: + * 120, 200 or 300 (`--cl-std=CL1.2` etc.). 0 selects 120. Constructs that + * need a higher version are diagnosed as errors. */ + unsigned OpenCLCVersion; +} SPIRV2CLCTranslateOptions; + +/* Translate a SPIR-V module (a binary of `Length` bytes at `SPIRV`) to OpenCL + * C source. `Options` may be NULL to select the defaults. On success returns + * 0 and sets `*OutSource` to the NUL-terminated source. On failure returns + * nonzero, sets `*OutSource` to NULL and, if `OutMessage` is not NULL, sets + * `*OutMessage` to a description of the error(s). Both strings are freed with + * SPIRV2CLCDisposeMessage. */ +SPIRV2CLC_API int SPIRV2CLCTranslate(const char *SPIRV, size_t Length, + const SPIRV2CLCTranslateOptions *Options, + SPIRV2CLCDiagnosticCallback Handler, + void *HandlerContext, char **OutSource, + char **OutMessage); + +SPIRV2CLC_API void SPIRV2CLCDisposeMessage(char *Message); + +#ifdef __cplusplus +} +#endif + +#endif /* LIBSPIRV2CLC_H */ diff --git a/include/spirv2clc.h b/include/spirv2clc.h index 174b6b6..059132d 100644 --- a/include/spirv2clc.h +++ b/include/spirv2clc.h @@ -15,6 +15,7 @@ #pragma once #include +#include #include #include #include @@ -26,6 +27,12 @@ namespace spirv2clc { struct translator_impl; +enum class severity { error, warning, remark }; + +// Receives each diagnostic as one message, without a trailing newline. +using diagnostic_handler = + std::function; + struct translator { // `opencl_c_version` selects the OpenCL C language version to emit for, @@ -39,6 +46,9 @@ struct translator { LIBSPIRV2CLC_EXPORT translator &operator=(translator &&); LIBSPIRV2CLC_EXPORT ~translator(); + // Diagnostics are printed to stderr unless a handler is set. + LIBSPIRV2CLC_EXPORT void set_diagnostic_handler(diagnostic_handler handler); + LIBSPIRV2CLC_EXPORT int translate(const std::string &assembly, std::string *srcout); LIBSPIRV2CLC_EXPORT int translate(const std::vector &binary, diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index 45366c7..9646c64 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -25,38 +25,93 @@ set(SPIRV2CLC_UNITY_SOURCES groups.cpp instns_ext.cpp) -add_library(libspirv2clc - translator.cpp - translator.h - cexpr.cpp - cexpr.h - ${SPIRV2CLC_UNITY_SOURCES} - "${PROJECT_SOURCE_DIR}/include/spirv2clc.h") -add_library(spirv2clc::libspirv2clc ALIAS libspirv2clc) - set_source_files_properties(${SPIRV2CLC_UNITY_SOURCES} PROPERTIES HEADER_FILE_ONLY ON) -set_target_properties(libspirv2clc PROPERTIES - POSITION_INDEPENDENT_CODE ON +# A library target named `name` with the translator and its C++ API, of the +# type given as the optional second argument (by default, per +# BUILD_SHARED_LIBS). +function(spirv2clc_add_translator name) + add_library(${name} ${ARGN} + translator.cpp + translator.h + cexpr.cpp + cexpr.h + ${SPIRV2CLC_UNITY_SOURCES} + "${PROJECT_SOURCE_DIR}/include/spirv2clc.h") + + set_target_properties(${name} PROPERTIES + POSITION_INDEPENDENT_CODE ON + CXX_VISIBILITY_PRESET hidden + VISIBILITY_INLINES_HIDDEN ON) + + target_include_directories(${name} + PUBLIC + "${PROJECT_SOURCE_DIR}/include" + "${CMAKE_CURRENT_BINARY_DIR}" # For the generated export header + PRIVATE + "${OPENCL_HEADERS_DIR}" + "${SPIRV_TOOLS_DIR}" + "${SPIRV_TOOLS_DIR}/source" + "${SPIRV_TOOLS_BINARY_DIR}") + + target_link_libraries(${name} + PUBLIC SPIRV-Tools-opt + PRIVATE spirv2clc::warnings) +endfunction() + +spirv2clc_add_translator(libspirv2clc) +add_library(spirv2clc::libspirv2clc ALIAS libspirv2clc) + +generate_export_header(libspirv2clc) + +# The C API (include/libspirv2clc.h), as a shared library that exports nothing +# else: the translator, SPIRV-Tools and the C++ standard library templates +# they instantiate are linked in and kept local, so that the library can be +# loaded into a process that has its own copies of them, and no C++ type +# crosses its interface. +# +# That needs the translator as a static library, so build a second copy of it +# when the C++ library is shared. +if(BUILD_SHARED_LIBS) + spirv2clc_add_translator(libspirv2clc-static STATIC) + target_compile_definitions(libspirv2clc-static + PUBLIC LIBSPIRV2CLC_STATIC_DEFINE) + set(_c_api_translator libspirv2clc-static) +else() + set(_c_api_translator libspirv2clc) +endif() + +add_library(libspirv2clc-c SHARED + libspirv2clc.cpp + "${PROJECT_SOURCE_DIR}/include/libspirv2clc.h") +add_library(spirv2clc::c ALIAS libspirv2clc-c) + +set_target_properties(libspirv2clc-c PROPERTIES + OUTPUT_NAME spirv2clc CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN ON) -target_include_directories(libspirv2clc - PUBLIC - "${PROJECT_SOURCE_DIR}/include" - "${CMAKE_CURRENT_BINARY_DIR}" # For the generated export header - PRIVATE - "${OPENCL_HEADERS_DIR}" - "${SPIRV_TOOLS_DIR}" - "${SPIRV_TOOLS_DIR}/source" - "${SPIRV_TOOLS_BINARY_DIR}") +target_include_directories(libspirv2clc-c + PUBLIC "${PROJECT_SOURCE_DIR}/include") -target_link_libraries(libspirv2clc - PUBLIC SPIRV-Tools-opt - PRIVATE spirv2clc::warnings) +target_link_libraries(libspirv2clc-c + PRIVATE + ${_c_api_translator} + spirv2clc::warnings) -generate_export_header(libspirv2clc) +# On Windows, only the functions declared with SPIRV2CLC_API are exported. +if(APPLE) + target_link_options(libspirv2clc-c PRIVATE + "LINKER:-exported_symbol,_SPIRV2CLC*") +elseif(NOT WIN32) + set(_version_script "${CMAKE_CURRENT_BINARY_DIR}/libspirv2clc.map") + file(WRITE "${_version_script}" "{ global: SPIRV2CLC*; local: *; };\n") + target_link_options(libspirv2clc-c PRIVATE + "LINKER:--version-script=${_version_script}") + set_property(TARGET libspirv2clc-c APPEND PROPERTY + LINK_DEPENDS "${_version_script}") +endif() # --------------------------------------------------------------------------- # Installation @@ -78,3 +133,13 @@ install(DIRECTORY "${SPIRV-Headers_SOURCE_DIR}/include" DESTINATION . COMPONENT headers FILES_MATCHING PATTERN "spirv/unified1/spirv.h") + +# The C API gets a component of its own: it is self-contained, so it can be +# shipped (e.g. next to the tool) without the static library and its headers. +install(TARGETS libspirv2clc-c + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" COMPONENT c_api + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" COMPONENT c_api + ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" COMPONENT c_api) +install(FILES "${PROJECT_SOURCE_DIR}/include/libspirv2clc.h" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" + COMPONENT c_api) diff --git a/lib/groups.cpp b/lib/groups.cpp index 90e7a08..c2ae48b 100644 --- a/lib/groups.cpp +++ b/lib/groups.cpp @@ -103,11 +103,11 @@ translator_impl::translate_group_instruction(const Instruction &inst, const bool uniform = inst.opcode() >= spv::Op::OpGroupAll && inst.opcode() <= spv::Op::OpGroupSMax; if (*scope != SpvScopeSubgroup && !(uniform && *scope == SpvScopeWorkgroup)) { - std::cerr << "UNIMPLEMENTED group execution scope " << *scope << std::endl; + error() << "UNIMPLEMENTED group execution scope " << *scope; return false; } if (m_opencl_c_version < 200) { - std::cerr << "UNIMPLEMENTED: group operations require OpenCL C 2.0\n"; + error() << "UNIMPLEMENTED: group operations require OpenCL C 2.0"; return false; } if (*scope == SpvScopeSubgroup) { @@ -146,13 +146,13 @@ translator_impl::translate_group_instruction(const Instruction &inst, break; case SpvGroupOperationClusteredReduce: if (uniform || ballot) { - std::cerr << "UNIMPLEMENTED clustered uniform or ballot operation\n"; + error() << "UNIMPLEMENTED clustered uniform or ballot operation"; return false; } name += "clustered_reduce"; break; default: - std::cerr << "UNIMPLEMENTED group operation " << operation << std::endl; + error() << "UNIMPLEMENTED group operation " << operation; return false; } if (!ballot) { @@ -166,7 +166,7 @@ translator_impl::translate_group_instruction(const Instruction &inst, if (ty->AsVector() || (uniform && *scope == SpvScopeWorkgroup && ty->AsInteger() && ty->AsInteger()->width() < 32)) { - std::cerr << "UNIMPLEMENTED group arithmetic operand type\n"; + error() << "UNIMPLEMENTED group arithmetic operand type"; return false; } if (uniform && *scope == SpvScopeSubgroup && ty->AsInteger() && @@ -189,7 +189,7 @@ translator_impl::translate_group_instruction(const Instruction &inst, } else if (*scope == SpvScopeWorkgroup && (ty->AsVector() || (ty->AsInteger() && ty->AsInteger()->width() < 32))) { - std::cerr << "UNIMPLEMENTED work-group broadcast operand type\n"; + error() << "UNIMPLEMENTED work-group broadcast operand type"; return false; } } @@ -201,7 +201,7 @@ translator_impl::translate_group_instruction(const Instruction &inst, auto ty = type_for_val(inst.GetSingleWordOperand(first_arg)); if (ty->AsVector() && inst.opcode() != spv::Op::OpGroupBroadcast && inst.opcode() != spv::Op::OpGroupNonUniformBroadcast) { - std::cerr << "UNIMPLEMENTED subgroup operand type\n"; + error() << "UNIMPLEMENTED subgroup operand type"; return false; } } diff --git a/lib/instns.cpp b/lib/instns.cpp index 2901719..acd9ca5 100644 --- a/lib/instns.cpp +++ b/lib/instns.cpp @@ -49,8 +49,7 @@ bool translator_impl::emit_access_chain(const Instruction &inst, auto cstmgr = m_ir->get_constant_mgr(); auto idx_cst = cstmgr->FindDeclaredConstant(idx); if (idx_cst == nullptr) { - std::cerr << "UNIMPLEMENTED struct access with non-constant index" - << std::endl; + error() << "UNIMPLEMENTED struct access with non-constant index"; return false; } uint32_t struct_idx = idx_cst->GetU32(); @@ -60,8 +59,7 @@ bool translator_impl::emit_access_chain(const Instruction &inst, break; } default: - std::cerr << "UNIMPLEMENTED access chain type " << cty->kind() - << std::endl; + error() << "UNIMPLEMENTED access chain type " << cty->kind(); return false; } } @@ -111,7 +109,7 @@ std::optional translator_impl::constant_operand(uint32_t id, const char *what) const { auto cst = m_ir->get_constant_mgr()->FindDeclaredConstant(id); if (cst == nullptr) { - std::cerr << "UNIMPLEMENTED non-constant " << what << std::endl; + error() << "UNIMPLEMENTED non-constant " << what; return std::nullopt; } return cst->GetU32(); @@ -131,7 +129,7 @@ c::expr_ref translator_impl::memory_scope(uint32_t scope) const { case SpvScopeInvocation: return c::name("memory_scope_work_group"); default: - std::cerr << "UNIMPLEMENTED memory scope " << scope << std::endl; + error() << "UNIMPLEMENTED memory scope " << scope; return nullptr; } } @@ -297,7 +295,7 @@ bool translator_impl::emit_image_access(const Instruction &inst, } } if (suffix.empty()) { - std::cerr << "UNIMPLEMENTED image texel type " << texel_tyid << std::endl; + error() << "UNIMPLEMENTED image texel type " << texel_tyid; return false; } @@ -308,7 +306,7 @@ bool translator_impl::emit_image_access(const Instruction &inst, SpvImageOperandsSignExtendMask | SpvImageOperandsZeroExtendMask; if ((operands & ~extend) || (operands == extend) || (operands && suffix != "i")) { - std::cerr << "UNIMPLEMENTED image operands " << operands << std::endl; + error() << "UNIMPLEMENTED image operands " << operands; return false; } @@ -325,8 +323,7 @@ bool translator_impl::emit_image_access(const Instruction &inst, unsigned ncoords = coord_vec ? coord_vec->element_count() : 1; if (coord_elem->kind() != Type::Kind::kInteger || !(ncoords == dims || (dims == 3 && ncoords == 4))) { - std::cerr << "UNIMPLEMENTED image coordinate type " << type_id_for(coord_ty) - << std::endl; + error() << "UNIMPLEMENTED image coordinate type " << type_id_for(coord_ty); return false; } auto as_int = [](unsigned n, c::expr_ref e) { @@ -705,17 +702,17 @@ bool translator_impl::translate_instruction(const Instruction &inst, // are atomic for every work-item accessing the memory, which is as wide as // any scope gets without shared virtual memory. if (order_of(*mem_sem) != memory_order::relaxed) { - std::cerr << "UNIMPLEMENTED: ordered atomics require OpenCL C 2.0 " - "(targeting " - << opencl_c_version_str(m_opencl_c_version) << ").\n"; + error() << "UNIMPLEMENTED: ordered atomics require OpenCL C 2.0 " + "(targeting " + << opencl_c_version_str(m_opencl_c_version) << ")."; return false; } if (opcode == spv::Op::OpAtomicFAddEXT || opcode == spv::Op::OpAtomicFMinEXT || opcode == spv::Op::OpAtomicFMaxEXT) { - std::cerr << "UNIMPLEMENTED: floating-point atomics require OpenCL C " - "2.0 (targeting " - << opencl_c_version_str(m_opencl_c_version) << ").\n"; + error() << "UNIMPLEMENTED: floating-point atomics require OpenCL C " + "2.0 (targeting " + << opencl_c_version_str(m_opencl_c_version) << ")."; return false; } static std::unordered_map fns{ @@ -781,9 +778,9 @@ bool translator_impl::translate_instruction(const Instruction &inst, } if (order_of(*sem_equal) != memory_order::relaxed || order_of(*sem_unequal) != memory_order::relaxed) { - std::cerr << "UNIMPLEMENTED: ordered atomics require OpenCL C 2.0 " - "(targeting " - << opencl_c_version_str(m_opencl_c_version) << ").\n"; + error() << "UNIMPLEMENTED: ordered atomics require OpenCL C 2.0 " + "(targeting " + << opencl_c_version_str(m_opencl_c_version) << ")."; return false; } val = call_values(atomic_builtin("cmpxchg", ptr), {ptr, cmp, desired}); @@ -793,9 +790,9 @@ bool translator_impl::translate_instruction(const Instruction &inst, case spv::Op::OpAtomicStore: { // OpenCL C 1.x has no atomic loads and stores. if (m_opencl_c_version < 200) { - std::cerr << "UNIMPLEMENTED: atomic load/store require OpenCL C 2.0 " - "(targeting " - << opencl_c_version_str(m_opencl_c_version) << ").\n"; + error() << "UNIMPLEMENTED: atomic load/store require OpenCL C 2.0 " + "(targeting " + << opencl_c_version_str(m_opencl_c_version) << ")."; return false; } bool is_load = opcode == spv::Op::OpAtomicLoad; @@ -853,9 +850,9 @@ bool translator_impl::translate_instruction(const Instruction &inst, break; } if (order_of(*mem_sem) != memory_order::relaxed) { - std::cerr << "UNIMPLEMENTED: ordered atomics require OpenCL C 2.0 " - "(targeting " - << opencl_c_version_str(m_opencl_c_version) << ").\n"; + error() << "UNIMPLEMENTED: ordered atomics require OpenCL C 2.0 " + "(targeting " + << opencl_c_version_str(m_opencl_c_version) << ")."; return false; } // OpenCL C 1.x has no flags, but the flag is a 32-bit integer that only @@ -1282,14 +1279,14 @@ bool translator_impl::translate_instruction(const Instruction &inst, work_group = true; } else if (*exec_scope == SpvScopeSubgroup) { if (m_opencl_c_version < 200) { - std::cerr << "UNIMPLEMENTED: subgroup barriers require OpenCL C 2.0\n"; + error() << "UNIMPLEMENTED: subgroup barriers require OpenCL C 2.0"; return false; } enable_extension("cl_khr_subgroups"); work_group = false; } else { - std::cerr << "UNIMPLEMENTED OpControlBarrier execution scope " - << *exec_scope << std::endl; + error() << "UNIMPLEMENTED OpControlBarrier execution scope " + << *exec_scope; return false; } @@ -1302,9 +1299,9 @@ bool translator_impl::translate_instruction(const Instruction &inst, break; } if (m_opencl_c_version < 200) { - std::cerr << "UNIMPLEMENTED: barriers fencing beyond the work-group " - "require OpenCL C 2.0 (targeting " - << opencl_c_version_str(m_opencl_c_version) << ").\n"; + error() << "UNIMPLEMENTED: barriers fencing beyond the work-group " + "require OpenCL C 2.0 (targeting " + << opencl_c_version_str(m_opencl_c_version) << ")."; return false; } auto scope_arg = memory_scope(*mem_scope); @@ -1345,9 +1342,9 @@ bool translator_impl::translate_instruction(const Instruction &inst, // mem_fence orders memory within the work-group. if (m_opencl_c_version < 200) { if (scope_width(*scope) > scope_width(SpvScopeWorkgroup)) { - std::cerr << "UNIMPLEMENTED: fences beyond the work-group require " - "OpenCL C 2.0 (targeting " - << opencl_c_version_str(m_opencl_c_version) << ").\n"; + error() << "UNIMPLEMENTED: fences beyond the work-group require " + "OpenCL C 2.0 (targeting " + << opencl_c_version_str(m_opencl_c_version) << ")."; return false; } fb.expression(c::call("mem_fence", {fence_flags(*mem_sem)})); @@ -1394,16 +1391,15 @@ bool translator_impl::translate_instruction(const Instruction &inst, auto exec_scope_cst = cstmgr->FindDeclaredConstant(execution_scope); if (exec_scope_cst == nullptr) { - std::cerr - << "UNIMPLEMENTED OpGroupAsyncCopy with non-constant execution scope" - << execution_scope << std::endl; + error() << "UNIMPLEMENTED OpGroupAsyncCopy with non-constant execution " + "scope " + << execution_scope; return false; } if (exec_scope_cst->GetU32() != SpvScopeWorkgroup) { - std::cerr - << "UNIMPLEMENTED OpGroupAsyncCopy with non-workgroup execution scope" - << std::endl; + error() << "UNIMPLEMENTED OpGroupAsyncCopy with non-workgroup execution " + "scope"; return false; } @@ -1428,16 +1424,14 @@ bool translator_impl::translate_instruction(const Instruction &inst, auto exec_scope_cst = cstmgr->FindDeclaredConstant(execution_scope); if (exec_scope_cst == nullptr) { - std::cerr - << "UNIMPLEMENTED OpGroupWaitEvents with non-constant execution scope" - << std::endl; + error() << "UNIMPLEMENTED OpGroupWaitEvents with non-constant execution " + "scope"; return false; } if (exec_scope_cst->GetU32() != SpvScopeWorkgroup) { - std::cerr << "UNIMPLEMENTED OpGroupWaitEvents with non-workgroup " - "execution scope" - << std::endl; + error() << "UNIMPLEMENTED OpGroupWaitEvents with non-workgroup " + "execution scope"; return false; } @@ -1459,7 +1453,7 @@ bool translator_impl::translate_instruction(const Instruction &inst, } break; } - std::cerr << "UNIMPLEMENTED instruction " << opcode << std::endl; + error() << "UNIMPLEMENTED instruction " << opcode; return false; } diff --git a/lib/instns_ext.cpp b/lib/instns_ext.cpp index c4f2c03..9b24f08 100644 --- a/lib/instns_ext.cpp +++ b/lib/instns_ext.cpp @@ -322,8 +322,7 @@ bool translator_impl::translate_extended_instruction(const Instruction &inst, break; } default: - std::cerr << "UNIMPLEMENTED extended instruction " << instruction - << std::endl; + error() << "UNIMPLEMENTED extended instruction " << instruction; return false; } } diff --git a/lib/libspirv2clc.cpp b/lib/libspirv2clc.cpp new file mode 100644 index 0000000..661c5cb --- /dev/null +++ b/lib/libspirv2clc.cpp @@ -0,0 +1,182 @@ +// Copyright 2020-2022 The spirv2clc authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "libspirv2clc.h" +#include "spirv2clc.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +char *make_message(const char *str, size_t len) { + char *p = static_cast(std::malloc(len + 1)); + if (p) { + std::memcpy(p, str, len); + p[len] = '\0'; + } + return p; +} + +char *make_message(const std::string &str) { + return make_message(str.data(), str.size()); +} + +// The validation environment for SPIR-V version `major`.`minor`, or +// SPV_ENV_MAX if there is none. +spv_target_env target_env(unsigned major, unsigned minor) { + if (major == 0 && minor == 0) { + return SPV_ENV_OPENCL_1_2; + } + if (major != 1) { + return SPV_ENV_MAX; + } + switch (minor) { + case 0: + return SPV_ENV_UNIVERSAL_1_0; + case 1: + return SPV_ENV_UNIVERSAL_1_1; + case 2: + return SPV_ENV_UNIVERSAL_1_2; + case 3: + return SPV_ENV_UNIVERSAL_1_3; + case 4: + return SPV_ENV_UNIVERSAL_1_4; + case 5: + return SPV_ENV_UNIVERSAL_1_5; + case 6: + return SPV_ENV_UNIVERSAL_1_6; + } + return SPV_ENV_MAX; +} + +} // namespace + +extern "C" { + +int SPIRV2CLCTranslate(const char *SPIRV, size_t Length, + const SPIRV2CLCTranslateOptions *Options, + SPIRV2CLCDiagnosticCallback Handler, + void *HandlerContext, char **OutSource, + char **OutMessage) { + if (OutSource) { + *OutSource = nullptr; + } + if (OutMessage) { + *OutMessage = nullptr; + } + auto fail = [&](const char *message, size_t len) { + if (OutMessage) { + *OutMessage = make_message(message, len); + } + return 1; + }; + auto fail_with = [&](const std::string &message) { + return fail(message.data(), message.size()); + }; + + // No C++ exception may unwind into the caller, so any (e.g. a failed + // allocation) fails the translation instead. + try { + if (!OutSource) { + return fail_with("no output pointer given"); + } + if (Length % sizeof(uint32_t) != 0 || (!SPIRV && Length != 0)) { + return fail_with("the input is not a SPIR-V binary (its size is not a " + "multiple of 4 bytes)"); + } + + SPIRV2CLCTranslateOptions defaults = {}; + if (!Options) { + Options = &defaults; + } + spv_target_env env = + target_env(Options->SPIRVVersionMajor, Options->SPIRVVersionMinor); + if (env == SPV_ENV_MAX) { + return fail_with("unsupported SPIR-V version " + + std::to_string(Options->SPIRVVersionMajor) + "." + + std::to_string(Options->SPIRVVersionMinor)); + } + unsigned opencl_c_version = + Options->OpenCLCVersion ? Options->OpenCLCVersion : 120; + if (opencl_c_version != 120 && opencl_c_version != 200 && + opencl_c_version != 300) { + return fail_with("unsupported OpenCL C version " + + std::to_string(opencl_c_version)); + } + + // The input need not be aligned for uint32_t. + std::vector binary(Length / sizeof(uint32_t)); + if (Length != 0) { + std::memcpy(binary.data(), SPIRV, Length); + } + + std::string errors; + spirv2clc::translator translator(env, opencl_c_version); + translator.set_diagnostic_handler( + [&](spirv2clc::severity sev, const std::string &message) { + SPIRV2CLCDiagnosticSeverity severity = SPIRV2CLCDSRemark; + const char *prefix = "remark"; + switch (sev) { + case spirv2clc::severity::error: + severity = SPIRV2CLCDSError; + prefix = "error"; + if (!errors.empty()) { + errors += '\n'; + } + errors += message; + break; + case spirv2clc::severity::warning: + severity = SPIRV2CLCDSWarning; + prefix = "warning"; + break; + case spirv2clc::severity::remark: + break; + } + if (Handler) { + Handler(severity, message.c_str(), HandlerContext); + } else { + std::fprintf(stderr, "%s: %s\n", prefix, message.c_str()); + } + }); + + std::string source; + if (translator.translate(binary, &source) != 0) { + return fail_with(errors.empty() ? "failed to translate the module" + : errors); + } + *OutSource = make_message(source); + if (!*OutSource) { + throw std::bad_alloc(); + } + return 0; + } catch (const std::bad_alloc &) { + static const char message[] = "out of memory"; + return fail(message, sizeof(message) - 1); + } catch (const std::exception &e) { + return fail(e.what(), std::strlen(e.what())); + } catch (...) { + static const char message[] = "unknown internal error"; + return fail(message, sizeof(message) - 1); + } +} + +void SPIRV2CLCDisposeMessage(char *Message) { std::free(Message); } + +} // extern "C" diff --git a/lib/translator.cpp b/lib/translator.cpp index ed2f3e0..5e9a2af 100644 --- a/lib/translator.cpp +++ b/lib/translator.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include using namespace spvtools; @@ -59,38 +60,60 @@ std::string rounding_mode(SpvFPRoundingMode mode) { return "UNKNOWN ROUNDING MODE"; } -const spvtools::MessageConsumer spvtools_message_consumer = - [](spv_message_level_t level, const char *, const spv_position_t &position, - const char *message) { - const char *levelstr = "UNKNOWN"; - switch (level) { - case SPV_MSG_FATAL: - levelstr = "FATAL"; - break; - case SPV_MSG_INTERNAL_ERROR: - levelstr = "INTERNAL ERROR"; - break; - case SPV_MSG_ERROR: - levelstr = "ERROR"; - break; - case SPV_MSG_WARNING: - levelstr = "WARNING"; - break; - case SPV_MSG_INFO: - levelstr = "INFO"; - break; - case SPV_MSG_DEBUG: - levelstr = "DEBUG"; - break; - } - printf("spvtools says '%s' (%s) at position %zu", message, levelstr, - position.index); - }; +void print_diagnostic(spirv2clc::severity sev, const std::string &message) { + switch (sev) { + case spirv2clc::severity::error: + std::cerr << "error: "; + break; + case spirv2clc::severity::warning: + std::cerr << "warning: "; + break; + case spirv2clc::severity::remark: + std::cerr << "remark: "; + break; + } + std::cerr << message << std::endl; +} } // namespace namespace spirv2clc { +// Defined here rather than in translator.h so that the operator<< overloads +// above are found when streaming SPIR-V enums into it. +class diagnostic { +public: + diagnostic(const diagnostic_handler &handler, severity sev, bool &failed) + : m_handler(handler), m_severity(sev), m_failed(failed) {} + diagnostic(const diagnostic &) = delete; + + // No exception may leave a destructor, and SPIRV-Tools reports messages from + // its own destructors too, so a diagnostic that can't be delivered fails the + // translation instead. + ~diagnostic() { + try { + std::string message = m_message.str(); + while (!message.empty() && message.back() == '\n') { + message.pop_back(); + } + m_handler(m_severity, message); + } catch (...) { + m_failed = true; + } + } + + template diagnostic &operator<<(const T &value) { + m_message << value; + return *this; + } + +private: + const diagnostic_handler &m_handler; + severity m_severity; + bool &m_failed; + std::ostringstream m_message; +}; + translator::translator(spv_target_env env, unsigned opencl_c_version) : m_impl(std::make_unique(env, opencl_c_version)) {} @@ -98,6 +121,11 @@ translator::~translator() = default; translator::translator(translator &&) = default; translator &translator::operator=(translator &&) = default; +void translator::set_diagnostic_handler(diagnostic_handler handler) { + m_impl->m_diagnostic_handler = + handler ? std::move(handler) : diagnostic_handler(print_diagnostic); +} + int translator::translate(const std::string &assembly, std::string *srcout) { return m_impl->translate(assembly, srcout); } @@ -108,12 +136,47 @@ int translator::translate(const std::vector &binary, } translator_impl::translator_impl(spv_target_env env, unsigned opencl_c_version) - : m_target_env(env), m_opencl_c_version(opencl_c_version) {} + : m_diagnostic_handler(print_diagnostic), m_target_env(env), + m_opencl_c_version(opencl_c_version) {} translator_impl::~translator_impl() = default; +diagnostic translator_impl::error() const { + return diagnostic(m_diagnostic_handler, severity::error, + m_translation_failed); +} + +void translator_impl::report_spvtools_message(spv_message_level_t level, + const spv_position_t &position, + const char *message, + bool text_input) const { + severity sev = severity::remark; + switch (level) { + case SPV_MSG_FATAL: + case SPV_MSG_INTERNAL_ERROR: + case SPV_MSG_ERROR: + sev = severity::error; + break; + case SPV_MSG_WARNING: + sev = severity::warning; + break; + case SPV_MSG_INFO: + case SPV_MSG_DEBUG: + break; + } + // Positions as spvDiagnosticPrint shows them: line and column of the + // assembly, or the word offset into the binary. + diagnostic diag(m_diagnostic_handler, sev, m_translation_failed); + if (text_input) { + diag << position.line + 1 << ":" << position.column + 1 << ": "; + } else if (position.index > 0) { + diag << position.index << ": "; + } + diag << message; +} + std::string translator_impl::note_unsupported(const std::string &what) const { - std::cerr << "UNIMPLEMENTED " << what << std::endl; + error() << "UNIMPLEMENTED " << what; m_translation_failed = true; return "UNIMPLEMENTED"; } @@ -140,8 +203,9 @@ bool translator_impl::translate_capabilities() { // require it; refuse below 2.0 rather than emit an invalid pragma. auto require_subgroups = [&](const char *what) { if (m_opencl_c_version < 200) { - std::cerr << "UNIMPLEMENTED: " << what << " require OpenCL C 2.0 (targeting " - << opencl_c_version_str(m_opencl_c_version) << ").\n"; + error() << "UNIMPLEMENTED: " << what + << " require OpenCL C 2.0 (targeting " + << opencl_c_version_str(m_opencl_c_version) << ")."; return false; } enable_extension("cl_khr_subgroups"); @@ -192,9 +256,9 @@ bool translator_impl::translate_capabilities() { // The generic address space is core in OpenCL C 2.0; see the matching // mapping of SpvStorageClassGeneric in src_pointer_type (types.cpp). if (m_opencl_c_version < 200) { - std::cerr << "UNIMPLEMENTED: generic address space requires OpenCL C " - "2.0 (targeting " - << opencl_c_version_str(m_opencl_c_version) << ").\n"; + error() << "UNIMPLEMENTED: generic address space requires OpenCL C " + "2.0 (targeting " + << opencl_c_version_str(m_opencl_c_version) << ")."; return false; } break; @@ -203,16 +267,16 @@ bool translator_impl::translate_capabilities() { // __opencl_c_read_write_images); see also the ReadWrite qualifier in // translate_type (types.cpp). if (m_opencl_c_version < 200) { - std::cerr << "UNIMPLEMENTED: read_write images require OpenCL C 2.0 " - "(targeting " - << opencl_c_version_str(m_opencl_c_version) << ").\n"; + error() << "UNIMPLEMENTED: read_write images require OpenCL C 2.0 " + "(targeting " + << opencl_c_version_str(m_opencl_c_version) << ")."; return false; } break; case SpvCapabilityGroups: // Groups also covers work-group collectives, which do not need subgroups. if (m_opencl_c_version < 200) { - std::cerr << "UNIMPLEMENTED: group operations require OpenCL C 2.0\n"; + error() << "UNIMPLEMENTED: group operations require OpenCL C 2.0"; return false; } break; @@ -267,7 +331,7 @@ bool translator_impl::translate_capabilities() { enable_extension("cl_ext_float_atomics"); break; default: - std::cerr << "UNIMPLEMENTED capability " << cap << ".\n"; + error() << "UNIMPLEMENTED capability " << cap << "."; return false; } } @@ -288,7 +352,7 @@ bool translator_impl::translate_extensions() const { auto &op_ext = inst.GetOperand(0); auto ext = op_ext.AsString(); if (!handled.count(ext)) { - std::cerr << "UNIMPLEMENTED extension " << ext << ".\n"; + error() << "UNIMPLEMENTED extension " << ext << "."; return false; } } @@ -300,7 +364,7 @@ bool translator_impl::translate_extended_instructions_imports() const { assert(inst.opcode() == spv::Op::OpExtInstImport); auto name = inst.GetOperand(1).AsString(); if (name != "OpenCL.std") { - std::cerr << "UNIMPLEMENTED extended instruction set.\n"; + error() << "UNIMPLEMENTED extended instruction set."; return false; } } @@ -368,7 +432,7 @@ bool translator_impl::translate_execution_modes() { case SpvExecutionModeLocalSizeHint: break; default: - std::cerr << "UNIMPLEMENTED execution mode " << mode << ".\n"; + error() << "UNIMPLEMENTED execution mode " << mode << "."; return false; } } @@ -384,8 +448,7 @@ bool translator_impl::translate_debug_instructions() { case spv::Op::OpString: break; default: - std::cerr << "UNIMPLEMENTED debug instructions in 7a " << opcode - << std::endl; + error() << "UNIMPLEMENTED debug instructions in 7a " << opcode; return false; } } @@ -400,15 +463,14 @@ bool translator_impl::translate_debug_instructions() { break; } default: - std::cerr << "UNIMPLEMENTED debug instructions " << opcode << ".\n"; + error() << "UNIMPLEMENTED debug instructions " << opcode << "."; return false; } } // Debug 3 for (auto &inst : m_ir->module()->debugs3()) { - std::cerr << "UNIMPLEMENTED debug instruction " << inst.opcode() - << " in 7c.\n"; + error() << "UNIMPLEMENTED debug instruction " << inst.opcode() << " in 7c."; return false; } @@ -446,8 +508,7 @@ bool translator_impl::translate_annotations() { m_byval_params.insert(target); break; default: - std::cerr << "UNIMPLEMENTED FuncParamAttr " << param_attr - << std::endl; + error() << "UNIMPLEMENTED FuncParamAttr " << param_attr; return false; } break; @@ -480,16 +541,16 @@ bool translator_impl::translate_annotations() { // cl_khr_subgroups (OpenCL C 2.0+), including when no dispatch // capability is declared. if (m_opencl_c_version < 200) { - std::cerr << "UNIMPLEMENTED: subgroup builtins require OpenCL C 2.0 " - "(targeting " - << opencl_c_version_str(m_opencl_c_version) << ").\n"; + error() << "UNIMPLEMENTED: subgroup builtins require OpenCL C 2.0 " + "(targeting " + << opencl_c_version_str(m_opencl_c_version) << ")."; return false; } enable_extension("cl_khr_subgroups"); m_builtin_variables[target] = static_cast(builtin); break; default: - std::cerr << "UNIMPLEMENTED builtin " << builtin << std::endl; + error() << "UNIMPLEMENTED builtin " << builtin; return false; } break; @@ -549,7 +610,7 @@ bool translator_impl::translate_annotations() { // Pointer access-range hints; nothing to emit. break; default: - std::cerr << "UNIMPLEMENTED decoration " << decoration << std::endl; + error() << "UNIMPLEMENTED decoration " << decoration; return false; } break; @@ -604,8 +665,7 @@ bool translator_impl::translate_annotations() { break; } default: - std::cerr << "UNIMPLEMENTED annotation instruction " << opcode - << std::endl; + error() << "UNIMPLEMENTED annotation instruction " << opcode; return false; } } @@ -972,8 +1032,6 @@ bool translator_impl::translate_function(Function &func) { int translator_impl::translate() { - reset(); - // 1. Capabilities if (!translate_capabilities()) { return 1; @@ -1050,24 +1108,36 @@ int translator_impl::translate() { bool translator_impl::validate_module( const std::vector &binary) const { - spv_diagnostic diag; + spv_diagnostic diag = nullptr; spv_context ctx = spvContextCreate(m_target_env); spv_result_t res = spvValidateBinary(ctx, binary.data(), binary.size(), &diag); spvContextDestroy(ctx); - spvDiagnosticPrint(diag); - spvDiagnosticDestroy(diag); - if (res != SPV_SUCCESS) { - return false; + if (diag) { + report_spvtools_message(res == SPV_SUCCESS ? SPV_MSG_WARNING + : SPV_MSG_ERROR, + diag->position, diag->error, false); + spvDiagnosticDestroy(diag); + } else if (res != SPV_SUCCESS) { + error() << "invalid SPIR-V module"; } - // std::cout << "Module valid.\n"; - return true; + return res == SPV_SUCCESS; } int translator_impl::translate(const std::string &assembly, std::string *srcout) { - m_ir = BuildModule(m_target_env, spvtools_message_consumer, assembly); + reset(); + m_ir = BuildModule( + m_target_env, + [this](spv_message_level_t level, const char *, + const spv_position_t &position, const char *message) { + report_spvtools_message(level, position, message, true); + }, + assembly); + if (!m_ir) { + return 1; + } std::vector module_bin; m_ir->module()->ToBinary(&module_bin, false); @@ -1087,8 +1157,17 @@ int translator_impl::translate(const std::string &assembly, int translator_impl::translate(const std::vector &binary, std::string *srcout) { - m_ir = BuildModule(m_target_env, spvtools_message_consumer, - binary.data(), binary.size()); + reset(); + m_ir = BuildModule( + m_target_env, + [this](spv_message_level_t level, const char *, + const spv_position_t &position, const char *message) { + report_spvtools_message(level, position, message, false); + }, + binary.data(), binary.size()); + if (!m_ir) { + return 1; + } if (!validate_module(binary)) { return 1; diff --git a/lib/translator.h b/lib/translator.h index d34b68e..584fd2c 100644 --- a/lib/translator.h +++ b/lib/translator.h @@ -27,6 +27,7 @@ #include #include "cexpr.h" +#include "spirv2clc.h" #include #include @@ -47,6 +48,8 @@ class Type; namespace spirv2clc { +class diagnostic; + // Hands out C identifiers, unique across the whole program and clear of C and // OpenCL C keywords and type names. Every identifier the translator emits comes // from here, both those derived from the module (linkage names, OpName) and @@ -129,6 +132,8 @@ struct translator_impl { int translate(const std::string &assembly, std::string *srcout); int translate(const std::vector &binary, std::string *srcout); + diagnostic_handler m_diagnostic_handler; + private: uint32_t type_id_for(uint32_t val) const; @@ -426,6 +431,15 @@ struct translator_impl { bool validate_module(const std::vector &binary) const; int translate(); + // An error message, streamed into like std::cerr and reported when the + // statement ends. + diagnostic error() const; + + // Reports what SPIRV-Tools says while parsing the module. + void report_spvtools_message(spv_message_level_t level, + const spv_position_t &position, + const char *message, bool text_input) const; + // Record that `what` can't be translated: emit a diagnostic, flag the failure // so translate() returns an error rather than silently producing a // placeholder marker in the output, and return that marker for the caller to diff --git a/lib/types.cpp b/lib/types.cpp index 3f2f3cc..bf8e68d 100644 --- a/lib/types.cpp +++ b/lib/types.cpp @@ -77,8 +77,7 @@ bool translator_impl::composite_member(const spvtools::opt::Instruction &inst, tyid = type_id_for(type->AsStruct()->element_types()[idx]); break; default: - std::cerr << "UNIMPLEMENTED composite member access, type " - << type->kind() << std::endl; + error() << "UNIMPLEMENTED composite member access, type " << type->kind(); return false; } } @@ -327,7 +326,7 @@ bool translator_impl::translate_type(const Instruction &inst) { signedtypestr = "long"; break; default: - std::cerr << "UNIMPLEMENTED OpTypeInt width " << width << std::endl; + error() << "UNIMPLEMENTED OpTypeInt width " << width; return false; } break; @@ -345,7 +344,7 @@ bool translator_impl::translate_type(const Instruction &inst) { typestr = "double"; break; default: - std::cerr << "UNIMPLEMENTED OpTypeFloat width " << width << std::endl; + error() << "UNIMPLEMENTED OpTypeFloat width " << width; return false; } break; @@ -414,9 +413,9 @@ bool translator_impl::translate_type(const Instruction &inst) { auto qual = inst.GetSingleWordOperand(8); if ((depth != 0) || (arrayed != 0) || (ms != 0) || (sampled != 0)) { - std::cerr << "UNIMPLEMENTED image type (depth = " << depth - << ", arrayed = " << arrayed << ", ms = " << ms - << "sampled = " << sampled << ")" << std::endl; + error() << "UNIMPLEMENTED image type (depth = " << depth + << ", arrayed = " << arrayed << ", ms = " << ms + << "sampled = " << sampled << ")"; return false; } @@ -431,16 +430,16 @@ bool translator_impl::translate_type(const Instruction &inst) { // Checked here as well as at the ImageReadWrite capability, since the // ReadWrite qualifier only requires Kernel. if (m_opencl_c_version < 200) { - std::cerr << "UNIMPLEMENTED: read_write images require OpenCL C 2.0 " - "(targeting " - << opencl_c_version_str(m_opencl_c_version) << ").\n"; + error() << "UNIMPLEMENTED: read_write images require OpenCL C 2.0 " + "(targeting " + << opencl_c_version_str(m_opencl_c_version) << ")."; return false; } typestr = "read_write"; m_read_write_images = true; break; default: - std::cerr << "UNIMPLEMENTED image access qualifier " << qual << std::endl; + error() << "UNIMPLEMENTED image access qualifier " << qual; return false; } @@ -464,7 +463,7 @@ bool translator_impl::translate_type(const Instruction &inst) { } break; default: - std::cerr << "UNIMPLEMENTED image dimensionality " << dim << std::endl; + error() << "UNIMPLEMENTED image dimensionality " << dim; return false; } @@ -493,7 +492,7 @@ bool translator_impl::translate_type(const Instruction &inst) { typestr = "event_t"; break; default: - std::cerr << "UNIMPLEMENTED type instuction " << opcode << std::endl; + error() << "UNIMPLEMENTED type instuction " << opcode; return false; } @@ -545,8 +544,7 @@ bool translator_impl::translate_types_values() { auto w = w1 << 32 | w0; m_bindings[result] = cast_to(rtype, c::literal(std::to_string(w))); } else { - std::cerr << "UNIMPLEMENTED integer constant width " << tint->width() - << std::endl; + error() << "UNIMPLEMENTED integer constant width " << tint->width(); return false; } break; @@ -574,8 +572,7 @@ bool translator_impl::translate_types_values() { out.precision(53); out << std::fixed << val; } else { - std::cerr << "UNIMPLEMENTED float constant width " << width - << std::endl; + error() << "UNIMPLEMENTED float constant width " << width; return false; } if (std::isinf(val) || std::isnan(val)) { @@ -598,8 +595,7 @@ bool translator_impl::translate_types_values() { break; } default: - std::cerr << "UNIMPLEMENTED OpConstant type " << type->kind() - << std::endl; + error() << "UNIMPLEMENTED OpConstant type " << type->kind(); return false; } break; @@ -691,8 +687,7 @@ bool translator_impl::translate_types_values() { c::compound_literal(src_type(rtype), {c::init_list(elems)}); break; default: - std::cerr << "UNIMPLEMENTED OpConstantComposite type " << type->kind() - << std::endl; + error() << "UNIMPLEMENTED OpConstantComposite type " << type->kind(); return false; } break; @@ -718,9 +713,8 @@ bool translator_impl::translate_types_values() { // Single-index element offset on a pointer: base + index. (Further // struct/array indices are not produced by these constant initializers.) if (inst.NumOperands() != 5) { - std::cerr << "UNIMPLEMENTED OpSpecConstantOp PtrAccessChain with " - "multiple indices" - << std::endl; + error() << "UNIMPLEMENTED OpSpecConstantOp PtrAccessChain with " + "multiple indices"; return false; } auto base = inst.GetSingleWordOperand(3); @@ -730,8 +724,8 @@ bool translator_impl::translate_types_values() { break; } default: - std::cerr << "UNIMPLEMENTED OpSpecConstantOp sub-opcode " - << static_cast(subop) << std::endl; + error() << "UNIMPLEMENTED OpSpecConstantOp sub-opcode " + << static_cast(subop); return false; } break; @@ -744,8 +738,7 @@ bool translator_impl::translate_types_values() { auto tyvar = type_for(rtype); auto tykind = tyvar->kind(); if (tykind != Type::Kind::kPointer) { - std::cerr << "UNIMPLEMENTED global variable with type " << tykind - << std::endl; + error() << "UNIMPLEMENTED global variable with type " << tykind; return false; } @@ -800,9 +793,9 @@ bool translator_impl::translate_types_values() { // Program-scope global variable. Legal only from OpenCL C 2.0 on; below // that, program-scope variables must live in the constant address space. if (m_opencl_c_version < 200) { - std::cerr << "UNIMPLEMENTED: program-scope global variable requires " - "OpenCL C 2.0 (targeting " - << opencl_c_version_str(m_opencl_c_version) << ").\n"; + error() << "UNIMPLEMENTED: program-scope global variable requires " + "OpenCL C 2.0 (targeting " + << opencl_c_version_str(m_opencl_c_version) << ")."; return false; } // As with UniformConstant, declare the storage as a value and make every @@ -818,15 +811,15 @@ bool translator_impl::translate_types_values() { m_out.globals << ";" << std::endl; m_bindings[result] = c::address_of(c::name(storagename)); } else { - std::cerr << "UNIMPLEMENTED global variable with storage class " - << storage << std::endl; + error() << "UNIMPLEMENTED global variable with storage class " + << storage; return false; } break; } default: - std::cerr << "UNIMPLEMENTED type/value instruction " << opcode << ".\n"; + error() << "UNIMPLEMENTED type/value instruction " << opcode << "."; return false; } } diff --git a/lib/utils.cpp b/lib/utils.cpp index af60881..f5d2c22 100644 --- a/lib/utils.cpp +++ b/lib/utils.cpp @@ -23,15 +23,14 @@ uint32_t translator_impl::array_type_get_length(uint32_t tyid) const { auto const &length_info = tarray->length_info(); if (length_info.words[0] != spvtools::opt::analysis::Array::LengthInfo::kConstant) { - std::cerr << "UNIMPLEMENTED array type with non-constant length" - << std::endl; + error() << "UNIMPLEMENTED array type with non-constant length"; return 0; } if (length_info.words.size() > 2) { for (unsigned i = 2; i < length_info.words.size(); i++) { if (length_info.words[i] != 0) { - std::cerr << "UNIMPLEMENTED array type with huge size" << std::endl; + error() << "UNIMPLEMENTED array type with huge size"; return 0; } } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 9adb15b..2d5eb53 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -17,6 +17,8 @@ if(NOT WIN32) add_subdirectory(testlayer) endif() +add_subdirectory(capi) + # --------------------------------------------------------------------------- # lit-based regression tests # diff --git a/tests/capi/CMakeLists.txt b/tests/capi/CMakeLists.txt new file mode 100644 index 0000000..f0b325a --- /dev/null +++ b/tests/capi/CMakeLists.txt @@ -0,0 +1,40 @@ +# Copyright 2020-2022 The spirv2clc authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# The C API test is written in C, so that it also checks the header is valid C. +# It assembles its inputs with the SPIRV-Tools C API, a copy of which it links +# next to the one hidden inside the library. +add_executable(capi_test capi_test.c) +target_include_directories(capi_test PRIVATE "${SPIRV_TOOLS_DIR}/include") +target_link_libraries(capi_test + PRIVATE + spirv2clc::c + SPIRV-Tools-static + spirv2clc::warnings) +set_target_properties(capi_test PROPERTIES + C_STANDARD 99 + C_STANDARD_REQUIRED ON + # SPIRV-Tools is C++ + LINKER_LANGUAGE CXX) +add_test(NAME capi COMMAND capi_test) + +# The library exports the C API and nothing else. +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + find_program(NM_EXECUTABLE NAMES nm) + if(NM_EXECUTABLE) + add_test(NAME capi_exports + COMMAND sh -c "! '${NM_EXECUTABLE}' -D --defined-only \"$0\" | grep -v ' SPIRV2CLC'" + "$") + endif() +endif() diff --git a/tests/capi/capi_test.c b/tests/capi/capi_test.c new file mode 100644 index 0000000..d9e4f04 --- /dev/null +++ b/tests/capi/capi_test.c @@ -0,0 +1,214 @@ +/* Copyright 2020-2022 The spirv2clc authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "libspirv2clc.h" +#include + +static int failures = 0; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + fprintf(stderr, "%s:%d: check failed: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ + } while (0) + +static const char copy_kernel[] = "OpCapability Addresses\n" + "OpCapability Kernel\n" + "OpMemoryModel Physical64 OpenCL\n" + "OpEntryPoint Kernel %k \"copy\"\n" + "%void = OpTypeVoid\n" + "%uint = OpTypeInt 32 0\n" + "%pg = OpTypePointer CrossWorkgroup %uint\n" + "%fnty = OpTypeFunction %void %pg %pg\n" + "%k = OpFunction %void None %fnty\n" + "%dst = OpFunctionParameter %pg\n" + "%src = OpFunctionParameter %pg\n" + "%entry = OpLabel\n" + "%v = OpLoad %uint %src\n" + "OpStore %dst %v\n" + "OpReturn\n" + "OpFunctionEnd\n"; + +/* Uses an ordered atomic, which needs OpenCL C 2.0. */ +static const char atomic_kernel[] = "OpCapability Addresses\n" + "OpCapability Kernel\n" + "OpMemoryModel Physical64 OpenCL\n" + "OpEntryPoint Kernel %k \"clear\"\n" + "%void = OpTypeVoid\n" + "%uint = OpTypeInt 32 0\n" + "%pg = OpTypePointer CrossWorkgroup %uint\n" + "%device = OpConstant %uint 1\n" + "%release = OpConstant %uint 4\n" + "%fnty = OpTypeFunction %void %pg\n" + "%k = OpFunction %void None %fnty\n" + "%flag = OpFunctionParameter %pg\n" + "%entry = OpLabel\n" + "OpAtomicFlagClear %flag %device %release\n" + "OpReturn\n" + "OpFunctionEnd\n"; + +/* Fails validation with a message that quotes the instruction. */ +static const char invalid_kernel[] = "OpCapability Addresses\n" + "OpCapability Kernel\n" + "OpMemoryModel Physical64 OpenCL\n" + "%u0 = OpTypeInt 0 0\n"; + +static spv_binary assemble(const char *text) { + spv_context context = spvContextCreate(SPV_ENV_UNIVERSAL_1_0); + spv_binary binary = NULL; + spv_diagnostic diagnostic = NULL; + if (spvTextToBinary(context, text, strlen(text), &binary, &diagnostic) != + SPV_SUCCESS) { + spvDiagnosticPrint(diagnostic); + exit(EXIT_FAILURE); + } + spvDiagnosticDestroy(diagnostic); + spvContextDestroy(context); + return binary; +} + +typedef struct { + int errors, others; + char last_error[256]; +} diagnostics; + +static void collect(SPIRV2CLCDiagnosticSeverity severity, const char *message, + void *context) { + diagnostics *diags = (diagnostics *)context; + size_t length = strlen(message); + CHECK(length > 0 && message[length - 1] != '\n'); + if (severity == SPIRV2CLCDSError) { + diags->errors++; + snprintf(diags->last_error, sizeof(diags->last_error), "%s", message); + } else { + diags->others++; + } +} + +/* Translates `size` bytes at `data`, checking the invariants of the result. */ +static int translate(const void *data, size_t size, + const SPIRV2CLCTranslateOptions *options, + diagnostics *diags, char **source, char **message) { + int status = SPIRV2CLCTranslate((const char *)data, size, options, collect, + diags, source, message); + CHECK((status == 0) == (*source != NULL)); + CHECK((status == 0) == (*message == NULL)); + return status; +} + +int main(void) { + spv_binary copy = assemble(copy_kernel); + spv_binary atomic = assemble(atomic_kernel); + size_t copy_size = copy->wordCount * sizeof(uint32_t); + size_t atomic_size = atomic->wordCount * sizeof(uint32_t); + char *source, *message; + + /* Success, with the default options. */ + { + diagnostics diags = {0}; + CHECK(translate(copy->code, copy_size, NULL, &diags, &source, &message) == + 0); + CHECK(source && strstr(source, "void kernel copy(")); + CHECK(diags.errors == 0); + SPIRV2CLCDisposeMessage(source); + } + + /* An unsupported construct: the error is reported to the callback and + * returned as the message. */ + { + SPIRV2CLCTranslateOptions options = {1, 0, 120}; + diagnostics diags = {0}; + CHECK(translate(atomic->code, atomic_size, &options, &diags, &source, + &message) != 0); + CHECK(diags.errors == 1); + CHECK(strstr(diags.last_error, "ordered atomics require OpenCL C 2.0")); + CHECK(message && strcmp(message, diags.last_error) == 0); + SPIRV2CLCDisposeMessage(message); + } + + /* ... which translates for OpenCL C 2.0. */ + { + SPIRV2CLCTranslateOptions options = {1, 0, 200}; + diagnostics diags = {0}; + CHECK(translate(atomic->code, atomic_size, &options, &diags, &source, + &message) == 0); + CHECK(source && strstr(source, "atomic_flag_clear_explicit")); + SPIRV2CLCDisposeMessage(source); + } + + /* Input that isn't SPIR-V, at an address that isn't word-aligned. */ + { + char garbage[] = "this is not SPIR-V at all"; + diagnostics diags = {0}; + CHECK(translate(garbage + 1, 24, NULL, &diags, &source, &message) != 0); + CHECK(message && strstr(message, "Invalid SPIR-V magic number")); + SPIRV2CLCDisposeMessage(message); + + CHECK(translate(garbage, 3, NULL, &diags, &source, &message) != 0); + CHECK(message && strstr(message, "not a multiple of 4 bytes")); + SPIRV2CLCDisposeMessage(message); + + CHECK(translate(NULL, 0, NULL, &diags, &source, &message) != 0); + CHECK(message != NULL); + SPIRV2CLCDisposeMessage(message); + } + + /* A module that doesn't validate. */ + { + spv_binary invalid = assemble(invalid_kernel); + diagnostics diags = {0}; + CHECK(translate(invalid->code, invalid->wordCount * sizeof(uint32_t), NULL, + &diags, &source, &message) != 0); + CHECK(diags.errors == 1); + CHECK(message && strstr(message, "Invalid number of bits (0)")); + SPIRV2CLCDisposeMessage(message); + spvBinaryDestroy(invalid); + } + + /* Invalid options. */ + { + SPIRV2CLCTranslateOptions spirv_version = {2, 0, 0}; + SPIRV2CLCTranslateOptions opencl_c_version = {0, 0, 210}; + diagnostics diags = {0}; + CHECK(translate(copy->code, copy_size, &spirv_version, &diags, &source, + &message) != 0); + CHECK(message && strstr(message, "unsupported SPIR-V version 2.0")); + SPIRV2CLCDisposeMessage(message); + CHECK(translate(copy->code, copy_size, &opencl_c_version, &diags, &source, + &message) != 0); + CHECK(message && strstr(message, "unsupported OpenCL C version 210")); + SPIRV2CLCDisposeMessage(message); + } + + /* Without a message pointer, a failure is still reported. */ + CHECK(SPIRV2CLCTranslate("abc", 3, NULL, collect, &(diagnostics){0}, &source, + NULL) != 0); + CHECK(source == NULL); + + spvBinaryDestroy(copy); + spvBinaryDestroy(atomic); + + if (failures) { + fprintf(stderr, "%d check(s) failed\n", failures); + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +} diff --git a/tests/cases/invalid_input.spt b/tests/cases/invalid_input.spt new file mode 100644 index 0000000..bae74fe --- /dev/null +++ b/tests/cases/invalid_input.spt @@ -0,0 +1,9 @@ +; Input that isn't a SPIR-V module is rejected, not translated or crashed on. +; RUN: not %spirv2clc --asm %s 2>&1 | %FileCheck %s --check-prefix=ASM +; ASM: Expected or at the beginning of an instruction, found 'bogus' +; ASM: Failed to translate module. +; RUN: echo -n abc > %t.spv +; RUN: not %spirv2clc %t.spv 2>&1 | %FileCheck %s --check-prefix=SIZE +; SIZE: is not a SPIR-V binary (its size is not a multiple of 4 bytes) + OpCapability Kernel + bogus diff --git a/tools/spirv2clc.cpp b/tools/spirv2clc.cpp index 7839b40..964de93 100644 --- a/tools/spirv2clc.cpp +++ b/tools/spirv2clc.cpp @@ -141,6 +141,11 @@ int main(int argc, char *argv[]) { file.seekg(0, std::ios::end); uint32_t size = file.tellg(); file.seekg(0, std::ios::beg); + if (size % sizeof(uint32_t) != 0) { + std::cerr << fname << " is not a SPIR-V binary (its size is not a " + << "multiple of 4 bytes)" << std::endl; + exit(EXIT_FAILURE); + } std::vector binary(size / sizeof(uint32_t)); file.read(reinterpret_cast(binary.data()), size); err = translator.translate(binary, &srcgen);