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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,39 @@ std::vector<uint32_t> 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:
Expand Down
80 changes: 80 additions & 0 deletions include/libspirv2clc.h
Original file line number Diff line number Diff line change
@@ -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 <stddef.h>

#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 */
10 changes: 10 additions & 0 deletions include/spirv2clc.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#pragma once

#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <vector>
Expand All @@ -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<void(severity, const std::string &message)>;

struct translator {

// `opencl_c_version` selects the OpenCL C language version to emit for,
Expand All @@ -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<uint32_t> &binary,
Expand Down
113 changes: 89 additions & 24 deletions lib/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
14 changes: 7 additions & 7 deletions lib/groups.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand All @@ -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() &&
Expand All @@ -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;
}
}
Expand All @@ -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;
}
}
Expand Down
Loading
Loading