[llvm] [Offload] generate LLVMOffloadKernel library (PR #211694)
Sophia Herrmann via llvm-commits
llvm-commits at lists.llvm.org
Mon Aug 10 13:49:00 PDT 2026
https://github.com/jellytabby updated https://github.com/llvm/llvm-project/pull/211694
>From 9493ef073072f6b330bf22011d567c7a38308aa0 Mon Sep 17 00:00:00 2001
From: Sophia Herrmann <herrmann15 at llnl.gov>
Date: Wed, 22 Jul 2026 16:57:48 -0700
Subject: [PATCH 1/4] generate LLVMOffloadKernel library
Co-authored-by: Johannes Doerfert <jdoerfert.llvm at gmail.com>
Co-authored-by: Jonas Greifenhain <cadivus at daverkomp.de>
remove old cmake variable
---
offload/CMakeLists.txt | 1 +
offload/languages/CMakeLists.txt | 1 +
offload/languages/kernel/CMakeLists.txt | 35 ++++
offload/languages/kernel/exports | 8 +
.../languages/kernel/include/ExportedAPI.h | 41 ++++
offload/languages/kernel/include/State.h | 106 ++++++++++
offload/languages/kernel/include/Types.h | 28 +++
offload/languages/kernel/src/ExportedAPI.cpp | 99 +++++++++
offload/languages/kernel/src/State.cpp | 198 ++++++++++++++++++
9 files changed, 517 insertions(+)
create mode 100644 offload/languages/CMakeLists.txt
create mode 100644 offload/languages/kernel/CMakeLists.txt
create mode 100644 offload/languages/kernel/exports
create mode 100644 offload/languages/kernel/include/ExportedAPI.h
create mode 100644 offload/languages/kernel/include/State.h
create mode 100644 offload/languages/kernel/include/Types.h
create mode 100644 offload/languages/kernel/src/ExportedAPI.cpp
create mode 100644 offload/languages/kernel/src/State.cpp
diff --git a/offload/CMakeLists.txt b/offload/CMakeLists.txt
index 2885b20f9c1d8..2dd4446979c05 100644
--- a/offload/CMakeLists.txt
+++ b/offload/CMakeLists.txt
@@ -340,6 +340,7 @@ if(BUILD_LIBOMPTARGET)
endif()
add_subdirectory(liboffload)
+add_subdirectory(languages)
# Add tests.
if(OFFLOAD_INCLUDE_TESTS)
diff --git a/offload/languages/CMakeLists.txt b/offload/languages/CMakeLists.txt
new file mode 100644
index 0000000000000..08b2a68082d80
--- /dev/null
+++ b/offload/languages/CMakeLists.txt
@@ -0,0 +1 @@
+add_subdirectory(kernel)
diff --git a/offload/languages/kernel/CMakeLists.txt b/offload/languages/kernel/CMakeLists.txt
new file mode 100644
index 0000000000000..3b0823a44faf1
--- /dev/null
+++ b/offload/languages/kernel/CMakeLists.txt
@@ -0,0 +1,35 @@
+add_llvm_library(
+ LLVMOffloadKernel SHARED
+
+ src/State.cpp
+ src/ExportedAPI.cpp
+
+ LINK_COMPONENTS
+ Support
+ Offload
+ )
+
+if(LIBOMP_HAVE_VERSION_SCRIPT_FLAG)
+ target_link_libraries(LLVMOffloadKernel PRIVATE "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/exports")
+endif()
+
+target_include_directories(LLVMOffloadKernel PUBLIC
+ ${CMAKE_CURRENT_SOURCE_DIR}/include
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../liboffload/include
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../liboffload/include/generated
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../include
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../plugins-nextgen/common/include)
+
+target_compile_options(LLVMOffloadKernel PRIVATE ${offload_compile_flags})
+target_link_options(LLVMOffloadKernel PRIVATE ${offload_link_flags})
+
+target_compile_definitions(LLVMOffloadKernel PRIVATE
+ TARGET_NAME="libLLVMOffloadKernel"
+ DEBUG_PREFIX="LLVMOffloadKernel"
+)
+
+set_target_properties(LLVMOffloadKernel PROPERTIES
+ POSITION_INDEPENDENT_CODE ON
+ INSTALL_RPATH "$ORIGIN"
+ BUILD_RPATH "$ORIGIN:${CMAKE_CURRENT_BINARY_DIR}/..")
+install(TARGETS LLVMOffloadKernel LIBRARY COMPONENT offload DESTINATION "${OFFLOAD_INSTALL_LIBDIR}")
diff --git a/offload/languages/kernel/exports b/offload/languages/kernel/exports
new file mode 100644
index 0000000000000..4bc5a4ab9710c
--- /dev/null
+++ b/offload/languages/kernel/exports
@@ -0,0 +1,8 @@
+VERS1.0 {
+ global:
+
+ olK*;
+
+ local:
+ *;
+};
diff --git a/offload/languages/kernel/include/ExportedAPI.h b/offload/languages/kernel/include/ExportedAPI.h
new file mode 100644
index 0000000000000..a4ce168d78fda
--- /dev/null
+++ b/offload/languages/kernel/include/ExportedAPI.h
@@ -0,0 +1,41 @@
+/*===---- ExportedAPI.h - Kernel language runtime - exported api ----------===
+ *
+ * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+ * See https://llvm.org/LICENSE.txt for license information.
+ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+ *
+ *===-----------------------------------------------------------------------===
+ */
+
+#pragma once
+
+#include "OffloadAPI.h"
+#include "Types.h"
+
+extern "C" {
+ol_device_handle_t olKGetDefaultDevice();
+
+ol_device_handle_t olKGetHostDevice();
+
+int olKGetDeviceCount();
+
+ol_device_handle_t olKGetDevice(int *DeviceNo);
+
+ol_device_handle_t olKSetDefaultDevice(int DeviceNo);
+
+ol_queue_handle_t olKGetDefaultQueue();
+
+CallConfigurationTy *olKGetCallConfiguration();
+
+void olKRegisterKernel(const void *ID, ol_symbol_handle_t Kernel);
+
+void olKUnregisterKernel(const void *ID);
+
+ol_symbol_handle_t olKGetKernel(const void *ID);
+
+void olKRegisterProgram(const void *ID, ol_program_handle_t Program);
+
+ol_program_handle_t olKUnregisterProgram(const void *ID);
+
+ol_program_handle_t olKGetProgram(const void *ID);
+}
diff --git a/offload/languages/kernel/include/State.h b/offload/languages/kernel/include/State.h
new file mode 100644
index 0000000000000..90f323d160a04
--- /dev/null
+++ b/offload/languages/kernel/include/State.h
@@ -0,0 +1,106 @@
+//===------- State.h - Kernel Language (CUDA/HIP) persistent state --------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+//===----------------------------------------------------------------------===//
+
+#pragma once
+
+#include "OffloadAPI.h"
+#include "Types.h"
+
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallVector.h"
+
+namespace llvm {
+namespace offload {
+
+using KernelIDTy = const void *;
+
+struct ThreadStateTy {
+ ~ThreadStateTy();
+
+ static ThreadStateTy &get();
+
+ static ol_queue_handle_t getDefaultQueue();
+ static ol_device_handle_t getDefaultDevice();
+ static CallConfigurationTy &getCallConfiguration();
+ void setDefaultDevice(ol_device_handle_t Device);
+
+private:
+ void createDefaultQueue(ol_device_handle_t Device);
+
+ ol_device_handle_t DefaultDevice = nullptr;
+ ol_queue_handle_t DefaultQueue = nullptr;
+
+ CallConfigurationTy CC = {};
+
+ ThreadStateTy();
+};
+
+struct StateTy {
+ ~StateTy();
+
+ friend struct ThreadStateTy;
+
+ static StateTy &get();
+ static StateTy *tryGet();
+
+ static ol_device_handle_t getHostDevice() { return get().HostDevice; }
+
+ ArrayRef<ol_device_handle_t> getDevices() const { return Devices; }
+
+ void addDevice(ol_device_handle_t Device) { Devices.push_back(Device); }
+ void setHostDevice(ol_device_handle_t Device) {
+ if (!HostDevice)
+ HostDevice = Device;
+ }
+
+ void addKernel(KernelIDTy KernelID, ol_symbol_handle_t Kernel) {
+ KernelMap[KernelID] = Kernel;
+ }
+
+ void removeKernel(KernelIDTy KernelID) { KernelMap.erase(KernelID); }
+
+ ol_symbol_handle_t getKernel(KernelIDTy KernelID) {
+ return KernelMap[KernelID];
+ }
+
+ void addProgram(const void *Binary, ol_program_handle_t Program) {
+ BinaryRegisterMap[Binary] = Program;
+ }
+
+ ol_program_handle_t removeProgram(const void *Binary) {
+ auto It = BinaryRegisterMap.find(Binary);
+ if (It == BinaryRegisterMap.end())
+ return nullptr;
+ ol_program_handle_t Program = It->second;
+ BinaryRegisterMap.erase(It);
+ return Program;
+ }
+
+ ol_program_handle_t getProgram(const void *Binary) {
+ assert(BinaryRegisterMap.count(Binary));
+ return BinaryRegisterMap[Binary];
+ }
+
+ void destroyRegisteredPrograms();
+
+private:
+ DenseMap<const void *, ol_program_handle_t> BinaryRegisterMap;
+ DenseMap<KernelIDTy, ol_symbol_handle_t> KernelMap;
+ SmallVector<ol_device_handle_t, 8> Devices;
+
+ ol_queue_handle_t DefaultQueue = nullptr;
+ ol_device_handle_t HostDevice = nullptr;
+
+ StateTy();
+};
+
+} // namespace offload
+} // namespace llvm
diff --git a/offload/languages/kernel/include/Types.h b/offload/languages/kernel/include/Types.h
new file mode 100644
index 0000000000000..6c5a0ec19a8f7
--- /dev/null
+++ b/offload/languages/kernel/include/Types.h
@@ -0,0 +1,28 @@
+//===------- Types.h - Kernel Language (CUDA/HIP) api types ---------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+//===----------------------------------------------------------------------===//
+
+#pragma once
+
+#include "Types.h"
+#include <cstddef>
+#include <cstdint>
+
+struct uint3 {
+ unsigned x = 0, y = 0, z = 0;
+};
+
+using dim3 = uint3;
+
+struct CallConfigurationTy {
+ dim3 GridSize;
+ dim3 BlockSize;
+ size_t SharedMemory;
+ void *Stream;
+};
diff --git a/offload/languages/kernel/src/ExportedAPI.cpp b/offload/languages/kernel/src/ExportedAPI.cpp
new file mode 100644
index 0000000000000..5c65d3d66b89b
--- /dev/null
+++ b/offload/languages/kernel/src/ExportedAPI.cpp
@@ -0,0 +1,99 @@
+//===------ ExportedAPI.cpp - Kernel Language runtime - exported api ------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+//===----------------------------------------------------------------------===//
+
+#include "ExportedAPI.h"
+
+#include "State.h"
+#include "Types.h"
+
+#include "OffloadAPI.h"
+#include "llvm/ADT/ArrayRef.h"
+
+#include <cstdio>
+#include <stdint.h>
+
+using namespace llvm;
+using namespace offload;
+
+/// Runtime API
+///{
+ol_device_handle_t olKGetDefaultDevice() {
+ ol_device_handle_t DefaultDevice = ThreadStateTy::getDefaultDevice();
+ return DefaultDevice;
+}
+
+ol_device_handle_t olKGetHostDevice() {
+ ol_device_handle_t HostDevice = StateTy::getHostDevice();
+ return HostDevice;
+}
+
+int olKGetDeviceCount() {
+ int DeviceCount = StateTy::get().getDevices().size();
+ return DeviceCount;
+}
+
+ol_device_handle_t olKGetDevice(int *DeviceNo) {
+ ol_device_handle_t DefaultDevice = ThreadStateTy::getDefaultDevice();
+ int DeviceCount = StateTy::get().getDevices().size();
+ ArrayRef<ol_device_handle_t> Devices = StateTy::get().getDevices();
+ for (int i = 0; i < DeviceCount; i++) {
+ if (Devices[i] == DefaultDevice) {
+ *DeviceNo = i;
+ return Devices[i];
+ }
+ }
+ return nullptr;
+}
+
+ol_device_handle_t olKSetDefaultDevice(int DeviceNo) {
+ ArrayRef<ol_device_handle_t> Devices = StateTy::get().getDevices();
+ if (DeviceNo < 0 || DeviceNo >= static_cast<int>(Devices.size()))
+ return nullptr;
+ ol_device_handle_t Device = Devices[DeviceNo];
+ ThreadStateTy::get().setDefaultDevice(Device);
+ return Device;
+}
+
+ol_queue_handle_t olKGetDefaultQueue() {
+ ol_queue_handle_t DefaultQueue = ThreadStateTy::getDefaultQueue();
+ return DefaultQueue;
+}
+
+CallConfigurationTy *olKGetCallConfiguration() {
+ return &ThreadStateTy::getCallConfiguration();
+}
+
+void olKRegisterKernel(const void *ID, ol_symbol_handle_t Kernel) {
+ StateTy::get().addKernel(ID, Kernel);
+}
+
+void olKUnregisterKernel(const void *ID) {
+ if (StateTy *State = StateTy::tryGet())
+ State->removeKernel(ID);
+}
+
+ol_symbol_handle_t olKGetKernel(const void *ID) {
+ return StateTy::get().getKernel(ID);
+}
+
+void olKRegisterProgram(const void *ID, ol_program_handle_t Program) {
+ StateTy::get().addProgram(ID, Program);
+}
+
+ol_program_handle_t olKUnregisterProgram(const void *ID) {
+ if (StateTy *State = StateTy::tryGet())
+ return State->removeProgram(ID);
+ return nullptr;
+}
+
+ol_program_handle_t olKGetProgram(const void *ID) {
+ return StateTy::get().getProgram(ID);
+}
+///}
diff --git a/offload/languages/kernel/src/State.cpp b/offload/languages/kernel/src/State.cpp
new file mode 100644
index 0000000000000..eff3c31257e93
--- /dev/null
+++ b/offload/languages/kernel/src/State.cpp
@@ -0,0 +1,198 @@
+//===------ State.cpp - Kernel Language (CUDA/HIP) persistent state -------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+//===----------------------------------------------------------------------===//
+
+#include "State.h"
+#include "Types.h"
+
+#include "OffloadAPI.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Support/raw_ostream.h"
+
+#include <atomic>
+#include <cstdio>
+#include <mutex>
+
+#define CHECK_FATAL(Result, ...) \
+ if (Result && Result->Code) { \
+ fprintf(stderr, __VA_ARGS__); \
+ abort(); \
+ }
+
+using namespace llvm;
+using namespace offload;
+
+std::atomic<uint32_t> AnyNonDefaultDevice = 0;
+__attribute__((weak)) uint32_t PerThreadQueue = 0;
+
+thread_local CallConfigurationTy CC = {};
+
+static std::mutex StateLock;
+static std::atomic<StateTy *> StatePtr = nullptr;
+
+static thread_local ThreadStateTy *ThreadState = nullptr;
+
+static std::mutex ThreadStatesLock;
+using ThreadStatesTy = SmallVector<ThreadStateTy *, 64>;
+static ThreadStatesTy *ThreadStatesPtr = nullptr;
+
+static void deleteThreadState() {
+ std::lock_guard<std::mutex> LG(ThreadStatesLock);
+ ThreadStatesTy *ThreadStates = ThreadStatesPtr;
+ ThreadStatesPtr = nullptr;
+ if (!ThreadStates)
+ return;
+
+ for (auto *TS : *ThreadStates)
+ delete (TS);
+ delete ThreadStates;
+ ThreadState = nullptr;
+}
+
+static void deleteState() {
+ StateTy *ST = StatePtr.load();
+ StatePtr.store(nullptr);
+ delete (ST);
+}
+
+static void destroyQueue(ol_queue_handle_t &Queue) {
+ if (!Queue)
+ return;
+
+ olSyncQueue(Queue);
+ olDestroyQueue(Queue);
+ Queue = nullptr;
+}
+
+ThreadStateTy::ThreadStateTy() {
+ if (PerThreadQueue) [[unlikely]]
+ createDefaultQueue(getDefaultDevice());
+ atexit(deleteThreadState);
+}
+ThreadStateTy::~ThreadStateTy() { destroyQueue(DefaultQueue); }
+
+ThreadStateTy &ThreadStateTy::get() {
+ auto *TS = ThreadState;
+ if (!TS) {
+ TS = new ThreadStateTy();
+ ThreadState = TS;
+ std::lock_guard<std::mutex> LG(ThreadStatesLock);
+ if (!ThreadStatesPtr)
+ ThreadStatesPtr = new ThreadStatesTy;
+ ThreadStatesPtr->push_back(TS);
+ }
+ return *TS;
+}
+
+ol_device_handle_t ThreadStateTy::getDefaultDevice() {
+ ol_device_handle_t DD = ThreadStateTy::get().DefaultDevice;
+ if (DD)
+ return DD;
+ for (ol_device_handle_t Device : StateTy::get().getDevices()) {
+ DD = Device;
+ break;
+ }
+ if (AnyNonDefaultDevice.load(std::memory_order_relaxed)) [[unlikely]] {
+ ol_device_handle_t TDD = ThreadStateTy::get().DefaultDevice;
+ if (TDD)
+ DD = TDD;
+ }
+ return DD;
+}
+
+ol_queue_handle_t ThreadStateTy::getDefaultQueue() {
+ if (!PerThreadQueue) [[likely]]
+ return StateTy::get().DefaultQueue;
+ return ThreadStateTy::get().DefaultQueue;
+}
+
+CallConfigurationTy &ThreadStateTy::getCallConfiguration() {
+ return ThreadStateTy::get().CC;
+}
+
+void ThreadStateTy::setDefaultDevice(ol_device_handle_t Device) {
+ DefaultDevice = Device;
+ createDefaultQueue(Device);
+}
+
+void ThreadStateTy::createDefaultQueue(ol_device_handle_t Device) {
+ if (DefaultQueue)
+ olDestroyQueue(DefaultQueue);
+ CHECK_FATAL(olCreateQueue(Device, &DefaultQueue),
+ "Failed to create per-thread default queue");
+}
+
+StateTy &StateTy::get() {
+ StateTy *ST = StatePtr.load();
+ if (!ST) [[unlikely]] {
+ std::lock_guard<std::mutex> LG(StateLock);
+ ST = StatePtr.load();
+ if (!ST) {
+ ST = new StateTy();
+ StatePtr.store(ST);
+ }
+ }
+ return *ST;
+}
+
+StateTy *StateTy::tryGet() { return StatePtr.load(); }
+
+static bool addDevices(ol_device_handle_t Device, void *Payload) {
+ StateTy &State = *reinterpret_cast<StateTy *>(Payload);
+ ol_platform_handle_t Platform;
+ ol_result_t Result;
+
+ Result = olGetDeviceInfo(Device, OL_DEVICE_INFO_PLATFORM, sizeof(Platform),
+ &Platform);
+ if (Result && Result->Code)
+ return true;
+
+ ol_platform_backend_t Backend;
+ Result = olGetPlatformInfo(Platform, OL_PLATFORM_INFO_BACKEND,
+ sizeof(Backend), &Backend);
+ if (Result && Result->Code)
+ return true;
+
+ if (Backend == OL_PLATFORM_BACKEND_HOST)
+ State.setHostDevice(Device);
+ else
+ State.addDevice(Device);
+ return true;
+}
+
+StateTy::StateTy() {
+ CHECK_FATAL(olInit(nullptr), "Failed to initialize the LLVMOffload");
+ CHECK_FATAL(olIterateDevices(addDevices, this), "Failed to identify devices");
+
+ if (!PerThreadQueue) [[likely]]
+ if (!Devices.empty()) [[likely]]
+ CHECK_FATAL(olCreateQueue(Devices.front(), &DefaultQueue),
+ "Failed to create default queue");
+
+ atexit(deleteState);
+}
+
+StateTy::~StateTy() {
+ deleteThreadState();
+ destroyQueue(DefaultQueue);
+ destroyRegisteredPrograms();
+ olShutDown();
+}
+
+void StateTy::destroyRegisteredPrograms() {
+ SmallPtrSet<ol_program_handle_t, 8> Programs;
+ for (auto &It : BinaryRegisterMap)
+ Programs.insert(It.second);
+
+ KernelMap.clear();
+ BinaryRegisterMap.clear();
+
+ for (ol_program_handle_t Program : Programs)
+ olDestroyProgram(Program);
+}
>From cca06271115b71bf9d727b32c778d68b51f64cc3 Mon Sep 17 00:00:00 2001
From: Sophia Herrmann <herrmann15 at llnl.gov>
Date: Fri, 24 Jul 2026 10:20:18 -0700
Subject: [PATCH 2/4] Build one offload language runtime library
Co-authored-by: Johannes Doerfert <jdoerfert.llvm at gmail.com>
Co-authored-by: Jonas Greifenhain <cadivus at daverkomp.de>
---
offload/languages/CMakeLists.txt | 2 +
offload/languages/README.md | 27 ++
offload/languages/cuda/CMakeLists.txt | 1 +
offload/languages/hip/CMakeLists.txt | 1 +
offload/languages/include/cuda/cuda_runtime.h | 24 ++
offload/languages/include/hip/hip_runtime.h | 61 ++++
.../include/kernel/DefineLanguageNames.inc | 51 +++
.../include/kernel/LanguageRuntime.h | 222 ++++++++++++
.../include/kernel/UndefineLanguageNames.inc | 48 +++
offload/languages/kernel/CMakeLists.txt | 59 +++-
offload/languages/kernel/exports | 9 +-
.../languages/kernel/include/ExportedAPI.h | 41 ---
.../kernel/include/LanguageAliases.inc | 70 ++++
.../languages/kernel/include/LanguageLaunch.h | 40 +++
.../kernel/include/LanguageRegistration.h | 64 ++++
offload/languages/kernel/include/State.h | 134 +++++---
offload/languages/kernel/include/Types.h | 10 +-
offload/languages/kernel/src/ExportedAPI.cpp | 99 ------
.../languages/kernel/src/LanguageCommon.cpp | 18 +
.../languages/kernel/src/LanguageLaunch.cpp | 83 +++++
.../kernel/src/LanguageRegistration.cpp | 318 ++++++++++++++++++
.../languages/kernel/src/LanguageRuntime.cpp | 223 ++++++++++++
offload/languages/kernel/src/State.cpp | 138 +++++++-
23 files changed, 1529 insertions(+), 214 deletions(-)
create mode 100644 offload/languages/README.md
create mode 100644 offload/languages/cuda/CMakeLists.txt
create mode 100644 offload/languages/hip/CMakeLists.txt
create mode 100644 offload/languages/include/cuda/cuda_runtime.h
create mode 100644 offload/languages/include/hip/hip_runtime.h
create mode 100644 offload/languages/include/kernel/DefineLanguageNames.inc
create mode 100644 offload/languages/include/kernel/LanguageRuntime.h
create mode 100644 offload/languages/include/kernel/UndefineLanguageNames.inc
delete mode 100644 offload/languages/kernel/include/ExportedAPI.h
create mode 100644 offload/languages/kernel/include/LanguageAliases.inc
create mode 100644 offload/languages/kernel/include/LanguageLaunch.h
create mode 100644 offload/languages/kernel/include/LanguageRegistration.h
delete mode 100644 offload/languages/kernel/src/ExportedAPI.cpp
create mode 100644 offload/languages/kernel/src/LanguageCommon.cpp
create mode 100644 offload/languages/kernel/src/LanguageLaunch.cpp
create mode 100644 offload/languages/kernel/src/LanguageRegistration.cpp
create mode 100644 offload/languages/kernel/src/LanguageRuntime.cpp
diff --git a/offload/languages/CMakeLists.txt b/offload/languages/CMakeLists.txt
index 08b2a68082d80..fbd774e645e21 100644
--- a/offload/languages/CMakeLists.txt
+++ b/offload/languages/CMakeLists.txt
@@ -1 +1,3 @@
add_subdirectory(kernel)
+add_subdirectory(cuda)
+add_subdirectory(hip)
diff --git a/offload/languages/README.md b/offload/languages/README.md
new file mode 100644
index 0000000000000..8361648df1779
--- /dev/null
+++ b/offload/languages/README.md
@@ -0,0 +1,27 @@
+# Offload Language Runtimes
+
+This directory contains the CUDA and HIP runtime layer for LLVM offload. It
+builds one shared library, `LLVMOffloadKernel`.
+
+The installed language headers are the user-facing part of this directory. CUDA
+programs include the CUDA header, HIP programs include the HIP header, and both
+see normal language names such as `cudaMalloc` or `hipMalloc`.
+
+Clang also depends on a small set of runtime entry points for kernel launch and
+device image registration. These symbols are external because generated host
+code calls them, but they are for compiler-generated code rather than for users
+to call directly.
+
+The rest of the runtime is internal. This includes device lookup, queues,
+registered programs, registered kernels, and error conversion.
+
+Some source files are shared by CUDA and HIP. CMake compiles those files once
+with `LANGUAGE=cuda` and once with `LANGUAGE=hip`. The language-name includes
+rename the generic declarations and definitions to the CUDA or HIP spelling for
+that object file.
+
+Source files that do not depend on CUDA or HIP spelling are compiled once and
+shared by both languages.
+
+The `cuda/` and `hip/` directories are kept in case there is ever a need for
+language-specific behavior.
diff --git a/offload/languages/cuda/CMakeLists.txt b/offload/languages/cuda/CMakeLists.txt
new file mode 100644
index 0000000000000..f09e9b46ef038
--- /dev/null
+++ b/offload/languages/cuda/CMakeLists.txt
@@ -0,0 +1 @@
+install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/../include/cuda/cuda_runtime.h DESTINATION ${CMAKE_INSTALL_PREFIX}/include/offload/cuda/)
diff --git a/offload/languages/hip/CMakeLists.txt b/offload/languages/hip/CMakeLists.txt
new file mode 100644
index 0000000000000..ea41dd59adf5c
--- /dev/null
+++ b/offload/languages/hip/CMakeLists.txt
@@ -0,0 +1 @@
+install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/../include/hip/hip_runtime.h DESTINATION ${CMAKE_INSTALL_PREFIX}/include/offload/hip/)
diff --git a/offload/languages/include/cuda/cuda_runtime.h b/offload/languages/include/cuda/cuda_runtime.h
new file mode 100644
index 0000000000000..a140ce1a1aca0
--- /dev/null
+++ b/offload/languages/include/cuda/cuda_runtime.h
@@ -0,0 +1,24 @@
+//===-- cuda_runtime.h - CUDA runtime API declarations --------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OFFLOAD_LANGUAGES_INCLUDE_CUDA_CUDA_RUNTIME_H
+#define LLVM_OFFLOAD_LANGUAGES_INCLUDE_CUDA_CUDA_RUNTIME_H
+
+#define LANGUAGE cuda
+
+#include "../kernel/DefineLanguageNames.inc"
+
+#include "../kernel/LanguageRuntime.h"
+
+#include "../kernel/UndefineLanguageNames.inc"
+
+#undef LANGUAGE
+
+using cudaDeviceProp = cudaDeviceProp_t;
+
+#endif // LLVM_OFFLOAD_LANGUAGES_INCLUDE_CUDA_CUDA_RUNTIME_H
diff --git a/offload/languages/include/hip/hip_runtime.h b/offload/languages/include/hip/hip_runtime.h
new file mode 100644
index 0000000000000..b56e295c904e3
--- /dev/null
+++ b/offload/languages/include/hip/hip_runtime.h
@@ -0,0 +1,61 @@
+//===-- hip_runtime.h - HIP runtime API declarations ----------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OFFLOAD_LANGUAGES_INCLUDE_HIP_HIP_RUNTIME_H
+#define LLVM_OFFLOAD_LANGUAGES_INCLUDE_HIP_HIP_RUNTIME_H
+
+#define LANGUAGE hip
+
+#include "../kernel/DefineLanguageNames.inc"
+
+#include "../kernel/LanguageRuntime.h"
+
+#include "../kernel/UndefineLanguageNames.inc"
+
+#undef LANGUAGE
+
+#define hipHostMallocDefault hipHostAllocDefault
+#define hipHostMallocPortable hipHostAllocPortable
+#define hipHostMallocMapped hipHostAllocMapped
+#define hipHostMallocWriteCombined hipHostAllocWriteCombined
+#define hipHostMallocNonCoherent 0x80000000
+
+inline hipError_t hipHostMalloc(void **Ptr, size_t Size, unsigned int Flags) {
+ return hipHostAlloc(Ptr, Size, Flags);
+}
+
+inline hipError_t hipHostFree(void *Ptr) { return ::hipFreeHost(Ptr); }
+
+#ifdef __cplusplus
+template <class T>
+static inline hipError_t hipHostMalloc(T **Ptr, size_t Size,
+ unsigned int Flags) {
+ return ::hipHostMalloc((void **)Ptr, Size, Flags);
+}
+
+template <class T> static inline hipError_t hipHostFree(T *Ptr) {
+ return ::hipHostFree((void *)Ptr);
+}
+#endif
+
+#if defined(__AMDGPU__) || defined(__NVPTX__)
+#define HIP_KERNEL_NAME(...) __VA_ARGS__
+
+extern "C" hipError_t hipLaunchKernel(const char *Kernel, dim3 GridDim,
+ dim3 BlockDim, void **KernelArgs,
+ size_t DynamicSharedMem, void *Stream);
+
+template <typename... AT, typename FT = void (*)(AT...)>
+static inline void hipLaunchKernelGGL(FT Kernel, dim3 GridDim, dim3 BlockDim,
+ size_t DynamicSharedMem, void *Stream,
+ AT... KernelArgs) {
+ Kernel<<<GridDim, BlockDim, DynamicSharedMem, Stream>>>(KernelArgs...);
+}
+#endif
+
+#endif // LLVM_OFFLOAD_LANGUAGES_INCLUDE_HIP_HIP_RUNTIME_H
diff --git a/offload/languages/include/kernel/DefineLanguageNames.inc b/offload/languages/include/kernel/DefineLanguageNames.inc
new file mode 100644
index 0000000000000..7f2b0776a03ff
--- /dev/null
+++ b/offload/languages/include/kernel/DefineLanguageNames.inc
@@ -0,0 +1,51 @@
+//===-- DefineLanguageNames.inc - Kernel language API name definitions ----===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#define COMBINE2(X, Y) X##Y
+#define COMBINE(X, Y) COMBINE2(X, Y)
+
+#define Error_t COMBINE(LANGUAGE, Error_t)
+#define DeviceProp_t COMBINE(LANGUAGE, DeviceProp_t)
+#define Malloc COMBINE(LANGUAGE, Malloc)
+#define Free COMBINE(LANGUAGE, Free)
+#define Memcpy COMBINE(LANGUAGE, Memcpy)
+#define DeviceSynchronize COMBINE(LANGUAGE, DeviceSynchronize)
+#define Success COMBINE(LANGUAGE, Success)
+#define ErrorInvalidValue COMBINE(LANGUAGE, ErrorInvalidValue)
+#define MemcpyKind COMBINE(LANGUAGE, MemcpyKind)
+#define MemcpyHostToHost COMBINE(LANGUAGE, MemcpyHostToHost)
+#define MemcpyHostToDevice COMBINE(LANGUAGE, MemcpyHostToDevice)
+#define MemcpyDeviceToHost COMBINE(LANGUAGE, MemcpyDeviceToHost)
+#define MemcpyDeviceToDevice COMBINE(LANGUAGE, MemcpyDeviceToDevice)
+#define MemcpyDefault COMBINE(LANGUAGE, MemcpyDefault)
+#define GetLastError COMBINE(LANGUAGE, GetLastError)
+#define PeekAtLastError COMBINE(LANGUAGE, PeekAtLastError)
+#define GetErrorName COMBINE(LANGUAGE, GetErrorName)
+#define GetErrorString COMBINE(LANGUAGE, GetErrorString)
+#define GetDevice COMBINE(LANGUAGE, GetDevice)
+#define GetDeviceCount COMBINE(LANGUAGE, GetDeviceCount)
+#define SetDevice COMBINE(LANGUAGE, SetDevice)
+#define HostAlloc COMBINE(LANGUAGE, HostAlloc)
+#define HostAllocDefault COMBINE(LANGUAGE, HostAllocDefault)
+#define HostAllocPortable COMBINE(LANGUAGE, HostAllocPortable)
+#define HostAllocMapped COMBINE(LANGUAGE, HostAllocMapped)
+#define HostAllocWriteCombined COMBINE(LANGUAGE, HostAllocWriteCombined)
+#define MallocHost COMBINE(LANGUAGE, MallocHost)
+#define FreeHost COMBINE(LANGUAGE, FreeHost)
+#define DriverGetVersion COMBINE(LANGUAGE, DriverGetVersion)
+#define GetDeviceProperties COMBINE(LANGUAGE, GetDeviceProperties)
+#define OccupancyMaxPotentialBlockSizeVariableSMem \
+ COMBINE(LANGUAGE, OccupancyMaxPotentialBlockSizeVariableSMem)
+#define Stream_t COMBINE(LANGUAGE, Stream_t)
+#define StreamCreate COMBINE(LANGUAGE, StreamCreate)
+#define StreamCreateWithFlags COMBINE(LANGUAGE, StreamCreateWithFlags)
+#define StreamDestroy COMBINE(LANGUAGE, StreamDestroy)
+#define StreamSynchronize COMBINE(LANGUAGE, StreamSynchronize)
+#define StreamCreateWithFlagsFlags COMBINE(LANGUAGE, StreamCreateWithFlagsFlags)
+#define StreamDefault COMBINE(LANGUAGE, StreamDefault)
+#define StreamNonBlocking COMBINE(LANGUAGE, StreamNonBlocking)
diff --git a/offload/languages/include/kernel/LanguageRuntime.h b/offload/languages/include/kernel/LanguageRuntime.h
new file mode 100644
index 0000000000000..dc00ae4ad5a1c
--- /dev/null
+++ b/offload/languages/include/kernel/LanguageRuntime.h
@@ -0,0 +1,222 @@
+//===-- LanguageRuntime.h - Kernel language runtime API declarations ------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OFFLOAD_LANGUAGES_INCLUDE_KERNEL_LANGUAGE_RUNTIME_H
+#define LLVM_OFFLOAD_LANGUAGES_INCLUDE_KERNEL_LANGUAGE_RUNTIME_H
+
+#include <cstdio>
+#include <cstdlib>
+#include <stddef.h>
+#include <stdint.h>
+
+enum Error_t : uint32_t {
+ Success = 0,
+ ErrorInvalidValue = 1,
+};
+
+struct DeviceProp_t {
+ char name[256];
+ size_t totalGlobalMem;
+ int warpSize;
+ int multiProcessorCount;
+ int major;
+ int minor;
+ int ECCEnabled;
+ int pciBusID;
+ int pciDeviceID;
+ int pciDomainID;
+ int memoryBusWidth;
+};
+
+enum MemcpyKind {
+ MemcpyHostToHost = 0,
+ MemcpyHostToDevice = 1,
+ MemcpyDeviceToHost = 2,
+ MemcpyDeviceToDevice = 3,
+ MemcpyDefault = 4
+};
+
+enum HostAllocFlags : unsigned int {
+ HostAllocDefault = 0x00,
+ HostAllocPortable = 0x01,
+ HostAllocMapped = 0x02,
+ HostAllocWriteCombined = 0x04,
+};
+
+enum StreamCreateWithFlagsFlags : unsigned int {
+ StreamDefault = 0x00,
+ StreamNonBlocking = 0x01,
+};
+
+typedef struct Stream_st *Stream_t;
+
+/// Malloc, with type template overlay.
+///{
+Error_t Malloc(void **Dev_Ptr, size_t Size);
+
+template <class T> static inline Error_t Malloc(T **dev_Ptr, size_t Size) {
+ return ::Malloc((void **)dev_Ptr, Size);
+}
+
+Error_t HostAlloc(void **Ptr, size_t Size, unsigned int Flags);
+
+template <class T>
+static inline Error_t HostAlloc(T **Ptr, size_t Size, unsigned int Flags) {
+ return ::HostAlloc((void **)Ptr, Size, Flags);
+}
+
+Error_t MallocHost(void **Ptr, size_t Size);
+
+template <class T> static inline Error_t MallocHost(T **Ptr, size_t Size) {
+ return ::MallocHost((void **)Ptr, Size);
+}
+///}
+
+/// Free, no type template necessary.
+Error_t Free(void *Dev_Ptr);
+
+/// Memcpy, with type template overlay.
+///{
+Error_t Memcpy(void *Dst, const void *Src, size_t Size, MemcpyKind Kind);
+
+template <class T>
+static inline Error_t Memcpy(T *Dst, const T *Src, size_t Size,
+ MemcpyKind Kind) {
+ return ::Memcpy((void *)Dst, (const void *)Src, Size, Kind);
+}
+///}
+
+Error_t DeviceSynchronize();
+
+Error_t GetLastError();
+
+Error_t PeekAtLastError();
+
+const char *GetErrorName(Error_t Error);
+
+const char *GetErrorString(Error_t Error);
+
+Error_t GetDevice(int *DeviceNo);
+
+Error_t GetDeviceCount(int *Count);
+
+Error_t SetDevice(int DeviceNo);
+
+Error_t FreeHost(void *Ptr);
+
+Error_t DriverGetVersion(int *Version);
+
+Error_t GetDeviceProperties(DeviceProp_t *DeviceProp, int DeviceNo);
+
+Error_t StreamCreate(Stream_t *stream);
+
+Error_t StreamCreateWithFlags(Stream_t *stream, unsigned int flags);
+
+Error_t StreamDestroy(Stream_t stream);
+
+Error_t StreamSynchronize(Stream_t stream);
+
+template <typename UnaryFunction, class T>
+static inline Error_t OccupancyMaxPotentialBlockSizeVariableSMem(
+ int *minGridSize, int *blockSize, T func,
+ UnaryFunction blockSizeToDynamicSMemSize, int blockSizeLimit = 0) {
+#if defined(__AMDGPU__)
+ // TODO: values taken from AMD Instinct MI250X gfx90a
+ *minGridSize = 220;
+ *blockSize = 1024;
+#elif defined(__NVPTX__)
+ // TODO: values taken from NVIDIA H100 80GB HBM3
+ *minGridSize = 264;
+ *blockSize = 1024;
+#endif
+ return Success;
+}
+
+///
+
+#if defined(__AMDGPU__) || defined(__NVPTX__)
+#include <gpuintrin.h>
+
+/// Define \p FIELD as a property backed by component \p OFFSET of Vec.
+#define __LLVM_OFFLOAD_DEVICE_BUILTIN(FIELD, OFFSET) \
+ __declspec(property(get = __get_##FIELD, \
+ put = __put_##FIELD)) unsigned int FIELD; \
+ __device__ inline __attribute__((always_inline)) T __get_##FIELD(void) \
+ const { \
+ return Vec[OFFSET]; \
+ } \
+ __device__ inline __attribute__((always_inline)) T __put_##FIELD(T V) { \
+ return Vec[OFFSET] = V; \
+ }
+
+/// Common storage for CUDA/HIP vector aliases such as int4 and float3.
+///
+/// Provides array-style indexing and x/y/z/w component properties over Clang
+/// ext_vector_type storage.
+template <class T, int Size> struct BaseVector {
+ using VT = float __attribute__((ext_vector_type(Size)));
+ VT Vec;
+
+ __device__ __host__ BaseVector() = default;
+
+ /// Construct a vector from component values.
+ template <typename... Args>
+ __device__ __host__ BaseVector(Args... args) : BaseVector({args...}) {}
+
+ /// Return component \p Idx.
+ __device__ __host__ T &operator[](int Idx) { return Vec[Idx]; }
+ __device__ __host__ const T &operator[](int Idx) const { return Vec[Idx]; }
+
+ __LLVM_OFFLOAD_DEVICE_BUILTIN(x, 0);
+ __LLVM_OFFLOAD_DEVICE_BUILTIN(y, 1);
+ __LLVM_OFFLOAD_DEVICE_BUILTIN(z, 2);
+ __LLVM_OFFLOAD_DEVICE_BUILTIN(w, 3);
+};
+
+/// Define the vector alias TY##SIZE and its make_TY##SIZE constructor helper.
+#define __VECTOR_DEF_IMPL(TY, SIZE) \
+ using TY##SIZE = BaseVector<TY, SIZE>; \
+ \
+ template <typename... Args> \
+ __device__ __host__ TY##SIZE make_##TY##SIZE(Args... args) { \
+ return TY##SIZE(args...); \
+ }
+
+/// Define the standard 1/2/3/4/8/16 element vector aliases for \p TY.
+#define __VECTOR_DEF(TY) \
+ __VECTOR_DEF_IMPL(TY, 1) \
+ __VECTOR_DEF_IMPL(TY, 2) \
+ __VECTOR_DEF_IMPL(TY, 3) \
+ __VECTOR_DEF_IMPL(TY, 4) \
+ __VECTOR_DEF_IMPL(TY, 8) \
+ __VECTOR_DEF_IMPL(TY, 16)
+
+/// Instantiate CUDA/HIP-style vector types and make_* helpers.
+__VECTOR_DEF(float)
+__VECTOR_DEF(double)
+__VECTOR_DEF(int8_t)
+__VECTOR_DEF(int16_t)
+__VECTOR_DEF(int32_t)
+__VECTOR_DEF(int64_t)
+__VECTOR_DEF(uint8_t)
+__VECTOR_DEF(uint16_t)
+__VECTOR_DEF(uint32_t)
+__VECTOR_DEF(uint64_t)
+__VECTOR_DEF(char)
+__VECTOR_DEF(short)
+__VECTOR_DEF(int)
+__VECTOR_DEF(unsigned)
+__VECTOR_DEF(long)
+
+#undef __VECTOR_DEF_IMPL
+#undef __VECTOR_DEF
+#undef __LLVM_OFFLOAD_DEVICE_BUILTIN
+
+#endif
+
+#endif // LLVM_OFFLOAD_LANGUAGES_INCLUDE_KERNEL_LANGUAGE_RUNTIME_H
diff --git a/offload/languages/include/kernel/UndefineLanguageNames.inc b/offload/languages/include/kernel/UndefineLanguageNames.inc
new file mode 100644
index 0000000000000..ab5f257cdfaea
--- /dev/null
+++ b/offload/languages/include/kernel/UndefineLanguageNames.inc
@@ -0,0 +1,48 @@
+//===-- UndefineLanguageNames.inc - Kernel language API name undefines ----===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#undef Error_t
+#undef DeviceProp_t
+#undef Malloc
+#undef Free
+#undef Memcpy
+#undef DeviceSynchronize
+#undef Success
+#undef ErrorInvalidValue
+#undef MemcpyKind
+#undef MemcpyHostToHost
+#undef MemcpyHostToDevice
+#undef MemcpyDeviceToHost
+#undef MemcpyDeviceToDevice
+#undef MemcpyDefault
+#undef GetLastError
+#undef PeekAtLastError
+#undef GetErrorName
+#undef GetErrorString
+#undef GetDevice
+#undef GetDeviceCount
+#undef SetDevice
+#undef HostAlloc
+#undef HostAllocFlags
+#undef HostAllocDefault
+#undef HostAllocPortable
+#undef HostAllocMapped
+#undef HostAllocWriteCombined
+#undef MallocHost
+#undef FreeHost
+#undef DriverGetVersion
+#undef GetDeviceProperties
+#undef OccupancyMaxPotentialBlockSizeVariableSMem
+#undef Stream_t
+#undef StreamCreate
+#undef StreamCreateWithFlags
+#undef StreamDestroy
+#undef StreamSynchronize
+#undef StreamCreateWithFlagsFlags
+#undef StreamDefault
+#undef StreamNonBlocking
diff --git a/offload/languages/kernel/CMakeLists.txt b/offload/languages/kernel/CMakeLists.txt
index 3b0823a44faf1..81442f9f2c507 100644
--- a/offload/languages/kernel/CMakeLists.txt
+++ b/offload/languages/kernel/CMakeLists.txt
@@ -1,24 +1,56 @@
+set(LLVM_OFFLOAD_KERNEL_INCLUDE_DIRS
+ ${CMAKE_CURRENT_BINARY_DIR}/../include
+ ${CMAKE_CURRENT_SOURCE_DIR}/../include/cuda
+ ${CMAKE_CURRENT_SOURCE_DIR}/../include/hip
+ ${CMAKE_CURRENT_SOURCE_DIR}/../include/kernel
+ ${CMAKE_CURRENT_SOURCE_DIR}/include
+ ${CMAKE_CURRENT_SOURCE_DIR}/../kernel/include
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../liboffload/include
+ ${CMAKE_CURRENT_BINARY_DIR}/../../liboffload/API
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../include
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../plugins-nextgen/common/include)
+
+function(add_llvm_offload_kernel_language_runtime_objects target language)
+ add_library(${target} OBJECT
+ src/LanguageRuntime.cpp
+ )
+ add_dependencies(${target} OffloadAPI)
+ target_include_directories(${target} PRIVATE ${LLVM_OFFLOAD_KERNEL_INCLUDE_DIRS})
+ target_compile_options(${target} PRIVATE ${offload_compile_flags})
+ target_compile_definitions(${target} PRIVATE
+ LANGUAGE=${language}
+ TARGET_NAME="libLLVMOffloadKernel"
+ DEBUG_PREFIX="LLVMOffloadKernel"
+ )
+ set_target_properties(${target} PROPERTIES POSITION_INDEPENDENT_CODE ON)
+endfunction()
+
+add_llvm_offload_kernel_language_runtime_objects(
+ LLVMOffloadKernelCudaRuntimeObjects cuda)
+add_llvm_offload_kernel_language_runtime_objects(
+ LLVMOffloadKernelHipRuntimeObjects hip)
+
add_llvm_library(
LLVMOffloadKernel SHARED
+ $<TARGET_OBJECTS:LLVMOffloadKernelCudaRuntimeObjects>
+ $<TARGET_OBJECTS:LLVMOffloadKernelHipRuntimeObjects>
+ src/LanguageCommon.cpp
+ src/LanguageLaunch.cpp
+ src/LanguageRegistration.cpp
src/State.cpp
- src/ExportedAPI.cpp
LINK_COMPONENTS
Support
Offload
)
-if(LIBOMP_HAVE_VERSION_SCRIPT_FLAG)
+if(LLVM_HAVE_LINK_VERSION_SCRIPT)
target_link_libraries(LLVMOffloadKernel PRIVATE "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/exports")
endif()
target_include_directories(LLVMOffloadKernel PUBLIC
- ${CMAKE_CURRENT_SOURCE_DIR}/include
- ${CMAKE_CURRENT_SOURCE_DIR}/../../liboffload/include
- ${CMAKE_CURRENT_SOURCE_DIR}/../../liboffload/include/generated
- ${CMAKE_CURRENT_SOURCE_DIR}/../../include
- ${CMAKE_CURRENT_SOURCE_DIR}/../../plugins-nextgen/common/include)
+ ${LLVM_OFFLOAD_KERNEL_INCLUDE_DIRS})
target_compile_options(LLVMOffloadKernel PRIVATE ${offload_compile_flags})
target_link_options(LLVMOffloadKernel PRIVATE ${offload_link_flags})
@@ -29,7 +61,18 @@ target_compile_definitions(LLVMOffloadKernel PRIVATE
)
set_target_properties(LLVMOffloadKernel PROPERTIES
+ RUNTIME_OUTPUT_DIRECTORY "${LLVM_LIBRARY_OUTPUT_INTDIR}/${OFFLOAD_TARGET_SUBDIR}"
POSITION_INDEPENDENT_CODE ON
INSTALL_RPATH "$ORIGIN"
BUILD_RPATH "$ORIGIN:${CMAKE_CURRENT_BINARY_DIR}/..")
-install(TARGETS LLVMOffloadKernel LIBRARY COMPONENT offload DESTINATION "${OFFLOAD_INSTALL_LIBDIR}")
+install(TARGETS LLVMOffloadKernel
+ COMPONENT offload
+ RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
+ LIBRARY DESTINATION "${OFFLOAD_INSTALL_LIBDIR}"
+ ARCHIVE DESTINATION "${OFFLOAD_INSTALL_LIBDIR}")
+
+install(FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/../include/kernel/DefineLanguageNames.inc
+ ${CMAKE_CURRENT_SOURCE_DIR}/../include/kernel/LanguageRuntime.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/../include/kernel/UndefineLanguageNames.inc
+ DESTINATION ${CMAKE_INSTALL_PREFIX}/include/offload/kernel/)
diff --git a/offload/languages/kernel/exports b/offload/languages/kernel/exports
index 4bc5a4ab9710c..3372890ff42c6 100644
--- a/offload/languages/kernel/exports
+++ b/offload/languages/kernel/exports
@@ -1,8 +1,11 @@
VERS1.0 {
global:
-
- olK*;
-
+ *cuda*;
+ *hip*;
+ llvmLaunchKernel*;
+ __llvm*;
+ __tgt_register_lib;
+ __tgt_unregister_lib;
local:
*;
};
diff --git a/offload/languages/kernel/include/ExportedAPI.h b/offload/languages/kernel/include/ExportedAPI.h
deleted file mode 100644
index a4ce168d78fda..0000000000000
--- a/offload/languages/kernel/include/ExportedAPI.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*===---- ExportedAPI.h - Kernel language runtime - exported api ----------===
- *
- * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
- * See https://llvm.org/LICENSE.txt for license information.
- * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
- *
- *===-----------------------------------------------------------------------===
- */
-
-#pragma once
-
-#include "OffloadAPI.h"
-#include "Types.h"
-
-extern "C" {
-ol_device_handle_t olKGetDefaultDevice();
-
-ol_device_handle_t olKGetHostDevice();
-
-int olKGetDeviceCount();
-
-ol_device_handle_t olKGetDevice(int *DeviceNo);
-
-ol_device_handle_t olKSetDefaultDevice(int DeviceNo);
-
-ol_queue_handle_t olKGetDefaultQueue();
-
-CallConfigurationTy *olKGetCallConfiguration();
-
-void olKRegisterKernel(const void *ID, ol_symbol_handle_t Kernel);
-
-void olKUnregisterKernel(const void *ID);
-
-ol_symbol_handle_t olKGetKernel(const void *ID);
-
-void olKRegisterProgram(const void *ID, ol_program_handle_t Program);
-
-ol_program_handle_t olKUnregisterProgram(const void *ID);
-
-ol_program_handle_t olKGetProgram(const void *ID);
-}
diff --git a/offload/languages/kernel/include/LanguageAliases.inc b/offload/languages/kernel/include/LanguageAliases.inc
new file mode 100644
index 0000000000000..67c188bc16269
--- /dev/null
+++ b/offload/languages/kernel/include/LanguageAliases.inc
@@ -0,0 +1,70 @@
+//===-- LanguageAliases.inc - Language runtime symbol aliases -------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// The LLVM offload kernel runtime implements the shared __llvm* entry points
+// once. These wrappers expose the CUDA/HIP ABI names, such as
+// __cudaRegisterFunction and __hipPopCallConfiguration, as forwarding entry
+// points to the shared implementations.
+//
+//===----------------------------------------------------------------------===//
+
+// This file intentionally has no include guard. It is included once for each
+// LANGUAGE value to emit each language's alias definitions.
+
+#ifndef LANGUAGE
+#error This file should be included, or used, with a LANGUAGE macro set.
+#endif
+
+#define LA_IMPL2(PREFIX, L, NAME) PREFIX##L##NAME
+#define LA_IMPL1(PREFIX, L, NAME) LA_IMPL2(PREFIX, L, NAME)
+#define LANGUAGE_NAME(PREFIX, NAME) LA_IMPL1(PREFIX, LANGUAGE, NAME)
+
+extern "C" void LANGUAGE_NAME(__, RegisterFunction)(
+ const char *Binary, const char *KernelID, char *KernelName,
+ const char *KernelName1, int ThreadLimit, uint3 *Tid, uint3 *Bid,
+ dim3 *BlockDim, dim3 *GridDim, int *WSize) {
+ __llvmRegisterFunction(Binary, KernelID, KernelName, KernelName1, ThreadLimit,
+ Tid, Bid, BlockDim, GridDim, WSize);
+}
+
+extern "C" void LANGUAGE_NAME(__, RegisterVar)(void **Data, char *HostVar,
+ char *DeviceAddress,
+ const char *DeviceName, int Ext,
+ int Size, int Constant,
+ int Global) {
+ __llvmRegisterVar(Data, HostVar, DeviceAddress, DeviceName, Ext, Size,
+ Constant, Global);
+}
+
+extern "C" void LANGUAGE_NAME(__, RegisterManagedVar)(
+ void **Data, char *HostVar, char *DeviceAddress, const char *DeviceName,
+ size_t Size, unsigned Align) {
+ __llvmRegisterManagedVar(Data, HostVar, DeviceAddress, DeviceName, Size,
+ Align);
+}
+
+extern "C" void LANGUAGE_NAME(__, RegisterSurface)(
+ void **Data, const struct surfaceReference *SurfRef, const void **DevPtr,
+ const char *Name, int Dim, int Ext) {
+ __llvmRegisterSurface(Data, SurfRef, DevPtr, Name, Dim, Ext);
+}
+
+extern "C" void LANGUAGE_NAME(__, RegisterTexture)(
+ void **Data, const struct textureReference *TexRef, const void **DevPtr,
+ const char *Name, int Dim, int Norm, int Ext) {
+ __llvmRegisterTexture(Data, TexRef, DevPtr, Name, Dim, Norm, Ext);
+}
+
+extern "C" unsigned LANGUAGE_NAME(__, PopCallConfiguration)(
+ dim3 *GridSize, dim3 *BlockSize, size_t *SharedMemory, void **Stream) {
+ return __llvmPopCallConfiguration(GridSize, BlockSize, SharedMemory, Stream);
+}
+
+#undef LANGUAGE_NAME
+#undef LA_IMPL1
+#undef LA_IMPL2
diff --git a/offload/languages/kernel/include/LanguageLaunch.h b/offload/languages/kernel/include/LanguageLaunch.h
new file mode 100644
index 0000000000000..161aead85bbef
--- /dev/null
+++ b/offload/languages/kernel/include/LanguageLaunch.h
@@ -0,0 +1,40 @@
+//===-- LanguageLaunch.h - Language launch API declarations ---------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OFFLOAD_LANGUAGES_KERNEL_INCLUDE_LANGUAGE_LAUNCH_H
+#define LLVM_OFFLOAD_LANGUAGES_KERNEL_INCLUDE_LANGUAGE_LAUNCH_H
+
+#include "OffloadAPI.h"
+#include "Types.h"
+
+#include <algorithm> // for std::max
+#include <cstddef>
+#include <cstdint>
+
+extern "C" {
+
+/// Push call configuration for kernel launch
+unsigned __llvmPushCallConfiguration(dim3 __grid_size, dim3 __block_size,
+ size_t __shared_memory, void *__stream);
+
+/// Pop call configuration for kernel launch
+unsigned __llvmPopCallConfiguration(dim3 *__grid_size, dim3 *__block_size,
+ size_t *__shared_memory, void **__stream);
+
+/// Internal kernel launch implementation
+ol_result_t __llvmLaunchKernelImpl(const char *KernelID, dim3 GridDim,
+ dim3 BlockDim, void *KernelArgsPtr,
+ size_t DynamicSharedMem, void *Stream);
+
+/// LLVM-style kernel launch entry point
+unsigned __llvmLaunchKernel(const char *KernelID, dim3 GridDim, dim3 BlockDim,
+ void *KernelArgsPtr, size_t DynamicSharedMem,
+ void *Stream);
+}
+
+#endif // LLVM_OFFLOAD_LANGUAGES_KERNEL_INCLUDE_LANGUAGE_LAUNCH_H
diff --git a/offload/languages/kernel/include/LanguageRegistration.h b/offload/languages/kernel/include/LanguageRegistration.h
new file mode 100644
index 0000000000000..248aa74f600bd
--- /dev/null
+++ b/offload/languages/kernel/include/LanguageRegistration.h
@@ -0,0 +1,64 @@
+//===-- LanguageRegistration.h - Language registration API declarations ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OFFLOAD_LANGUAGES_KERNEL_INCLUDE_LANGUAGE_REGISTRATION_H
+#define LLVM_OFFLOAD_LANGUAGES_KERNEL_INCLUDE_LANGUAGE_REGISTRATION_H
+
+#include "OffloadAPI.h"
+#include "Types.h"
+
+#include <cstdint>
+#include <iterator>
+
+#define HIP_FATBIN_MAGIC_STR "__CLANG_OFFLOAD_BUNDLE__"
+constexpr auto HIP_FATBIN_MAGIC_STR_LEN = sizeof(HIP_FATBIN_MAGIC_STR) - 1;
+
+namespace {
+struct FatbinWrapperTy {
+ int Magic;
+ int Version;
+ const char *Data;
+ const char *DataEnd;
+};
+} // namespace
+
+static void readTUFatbin(const char *Binary, const FatbinWrapperTy *FW);
+
+static void readHIPFatbinEntries(const char *Binary, const char *HIPFatbinPtr);
+
+/// Hidden, but exported, Registration API
+///{
+extern "C" {
+
+void __llvmRegisterFunction(const char *Binary, const char *KernelID,
+ char *KernelName, const char *KernelName1, int,
+ uint3 *, uint3 *, dim3 *, dim3 *, int *);
+
+const char *__llvmRegisterFatBinary(const char *Binary);
+
+void __llvmUnregisterFatBinary(void *Handle);
+
+void __llvmRegisterVar(void **, char *, char *, const char *, int, int, int,
+ int);
+
+void __llvmRegisterManagedVar(void **, char *, char *, const char *, size_t,
+ unsigned);
+
+void __llvmRegisterSurface(void **, const struct surfaceReference *,
+ const void **, const char *, int, int);
+
+void __llvmRegisterTexture(void **, const struct textureReference *,
+ const void **, const char *, int, int, int);
+
+struct __tgt_bin_desc;
+void __tgt_register_lib(__tgt_bin_desc *Desc);
+void __tgt_unregister_lib(__tgt_bin_desc *Desc);
+}
+///}
+
+#endif // LLVM_OFFLOAD_LANGUAGES_KERNEL_INCLUDE_LANGUAGE_REGISTRATION_H
diff --git a/offload/languages/kernel/include/State.h b/offload/languages/kernel/include/State.h
index 90f323d160a04..12d1abafbf917 100644
--- a/offload/languages/kernel/include/State.h
+++ b/offload/languages/kernel/include/State.h
@@ -1,14 +1,13 @@
-//===------- State.h - Kernel Language (CUDA/HIP) persistent state --------===//
+//===-- State.h - Kernel language persistent state ------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
-//
-//===----------------------------------------------------------------------===//
-#pragma once
+#ifndef LLVM_OFFLOAD_LANGUAGES_KERNEL_INCLUDE_STATE_H
+#define LLVM_OFFLOAD_LANGUAGES_KERNEL_INCLUDE_STATE_H
#include "OffloadAPI.h"
#include "Types.h"
@@ -16,23 +15,52 @@
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/raw_ostream.h"
+
+#define CHECK_FATAL(ResultExpr, ...) \
+ do { \
+ ol_result_t CheckFatalResult = (ResultExpr); \
+ if (CheckFatalResult && CheckFatalResult->Code) { \
+ llvm::errs() << __VA_ARGS__; \
+ if (CheckFatalResult->Details) \
+ llvm::errs() << ": " << CheckFatalResult->Details; \
+ llvm::errs() << '\n'; \
+ abort(); \
+ } \
+ } while (false)
namespace llvm {
namespace offload {
+/// Opaque host-side key used to identify a registered kernel.
+///
+/// This is the address emitted in the offload entry table for the kernel,
+/// not a device number or liboffload handle. The runtime maps it to the
+/// loaded device symbol during registration and uses it again during launch.
using KernelIDTy = const void *;
+/// Per-thread state used by the language runtime entry points.
+///
+/// Tracks the current thread's default device, optional per-thread queue,
+/// and pending kernel launch configuration.
struct ThreadStateTy {
~ThreadStateTy();
- static ThreadStateTy &get();
-
+ /// Return the default queue for the current stream mode.
static ol_queue_handle_t getDefaultQueue();
+
+ /// Return the thread-local default device, or the first discovered device.
static ol_device_handle_t getDefaultDevice();
+
+ /// Return the pending kernel launch configuration for this thread.
static CallConfigurationTy &getCallConfiguration();
- void setDefaultDevice(ol_device_handle_t Device);
+
+ /// Set the thread-local default device to \p Device and recreate its queue.
+ static void setDefaultDevice(ol_device_handle_t Device);
private:
+ static ThreadStateTy &get();
+
void createDefaultQueue(ol_device_handle_t Device);
ol_device_handle_t DefaultDevice = nullptr;
@@ -43,58 +71,78 @@ struct ThreadStateTy {
ThreadStateTy();
};
+/// Process-wide state shared by CUDA and HIP language entry points.
+///
+/// Owns the discovered devices, host device, process default queue, and maps
+/// from registered binaries and kernels to liboffload handles.
struct StateTy {
~StateTy();
friend struct ThreadStateTy;
- static StateTy &get();
- static StateTy *tryGet();
+ /// Return the host device discovered during runtime initialization.
+ static ol_device_handle_t getHostDevice();
- static ol_device_handle_t getHostDevice() { return get().HostDevice; }
+ /// Return the number of non-host devices available to kernel languages.
+ static int getDeviceCount();
- ArrayRef<ol_device_handle_t> getDevices() const { return Devices; }
+ /// Return the thread-local default device and write its number to \p DeviceNo.
+ static ol_device_handle_t getDevice(int *DeviceNo);
- void addDevice(ol_device_handle_t Device) { Devices.push_back(Device); }
- void setHostDevice(ol_device_handle_t Device) {
- if (!HostDevice)
- HostDevice = Device;
- }
+ /// Set the thread-local default device by device number.
+ ///
+ /// \returns the selected device, or nullptr if \p DeviceNo is invalid.
+ static ol_device_handle_t setDefaultDevice(int DeviceNo);
- void addKernel(KernelIDTy KernelID, ol_symbol_handle_t Kernel) {
- KernelMap[KernelID] = Kernel;
- }
+ /// Register \p Kernel for the host-side kernel identifier \p ID.
+ ///
+ /// \p ID is the opaque kernel key emitted by Clang in the offload entry
+ /// table. It is later passed to the launch entry point to recover the
+ /// corresponding liboffload symbol handle.
+ static void registerKernel(const void *ID, ol_symbol_handle_t Kernel);
- void removeKernel(KernelIDTy KernelID) { KernelMap.erase(KernelID); }
+ /// Remove any registered kernel handle for the host-side kernel key \p ID.
+ static void unregisterKernel(const void *ID);
- ol_symbol_handle_t getKernel(KernelIDTy KernelID) {
- return KernelMap[KernelID];
- }
+ /// Return the registered kernel handle for the host-side kernel key \p ID.
+ static ol_symbol_handle_t getKernel(const void *ID);
- void addProgram(const void *Binary, ol_program_handle_t Program) {
- BinaryRegisterMap[Binary] = Program;
- }
+ /// Register \p Program for the binary image identifier \p ID.
+ ///
+ /// \p ID is the device image start address from the offload binary
+ /// descriptor. It keys the loaded program so later function registration
+ /// can look up the program that owns each kernel symbol.
+ static void registerProgram(const void *ID, ol_program_handle_t Program);
- ol_program_handle_t removeProgram(const void *Binary) {
- auto It = BinaryRegisterMap.find(Binary);
- if (It == BinaryRegisterMap.end())
- return nullptr;
- ol_program_handle_t Program = It->second;
- BinaryRegisterMap.erase(It);
- return Program;
- }
+ /// Remove and return the loaded program handle for binary image key \p ID.
+ static ol_program_handle_t unregisterProgram(const void *ID);
- ol_program_handle_t getProgram(const void *Binary) {
- assert(BinaryRegisterMap.count(Binary));
- return BinaryRegisterMap[Binary];
- }
+ /// Return the loaded program handle for binary image key \p ID.
+ static ol_program_handle_t getProgram(const void *ID);
+
+private:
+ static StateTy &get();
+ static StateTy *tryGet();
+ static bool addDevices(ol_device_handle_t Device, void *Payload);
+
+ llvm::ArrayRef<ol_device_handle_t> getDevices() const;
+
+ void addDevice(ol_device_handle_t Device);
+ void setHostDevice(ol_device_handle_t Device);
+
+ void addKernel(KernelIDTy KernelID, ol_symbol_handle_t Kernel);
+ void removeKernel(KernelIDTy KernelID);
+ ol_symbol_handle_t lookupKernel(KernelIDTy KernelID);
+
+ void addProgram(const void *Binary, ol_program_handle_t Program);
+ ol_program_handle_t removeProgram(const void *Binary);
+ ol_program_handle_t lookupProgram(const void *Binary);
void destroyRegisteredPrograms();
-private:
- DenseMap<const void *, ol_program_handle_t> BinaryRegisterMap;
- DenseMap<KernelIDTy, ol_symbol_handle_t> KernelMap;
- SmallVector<ol_device_handle_t, 8> Devices;
+ llvm::DenseMap<const void *, ol_program_handle_t> BinaryRegisterMap;
+ llvm::DenseMap<KernelIDTy, ol_symbol_handle_t> KernelMap;
+ llvm::SmallVector<ol_device_handle_t, 8> Devices;
ol_queue_handle_t DefaultQueue = nullptr;
ol_device_handle_t HostDevice = nullptr;
@@ -104,3 +152,5 @@ struct StateTy {
} // namespace offload
} // namespace llvm
+
+#endif // LLVM_OFFLOAD_LANGUAGES_KERNEL_INCLUDE_STATE_H
diff --git a/offload/languages/kernel/include/Types.h b/offload/languages/kernel/include/Types.h
index 6c5a0ec19a8f7..56435daf602fc 100644
--- a/offload/languages/kernel/include/Types.h
+++ b/offload/languages/kernel/include/Types.h
@@ -1,16 +1,14 @@
-//===------- Types.h - Kernel Language (CUDA/HIP) api types ---------------===//
+//===-- Types.h - Kernel language API types -------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
-//
-//===----------------------------------------------------------------------===//
-#pragma once
+#ifndef LLVM_OFFLOAD_LANGUAGES_KERNEL_INCLUDE_TYPES_H
+#define LLVM_OFFLOAD_LANGUAGES_KERNEL_INCLUDE_TYPES_H
-#include "Types.h"
#include <cstddef>
#include <cstdint>
@@ -26,3 +24,5 @@ struct CallConfigurationTy {
size_t SharedMemory;
void *Stream;
};
+
+#endif // LLVM_OFFLOAD_LANGUAGES_KERNEL_INCLUDE_TYPES_H
diff --git a/offload/languages/kernel/src/ExportedAPI.cpp b/offload/languages/kernel/src/ExportedAPI.cpp
deleted file mode 100644
index 5c65d3d66b89b..0000000000000
--- a/offload/languages/kernel/src/ExportedAPI.cpp
+++ /dev/null
@@ -1,99 +0,0 @@
-//===------ ExportedAPI.cpp - Kernel Language runtime - exported api ------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-//===----------------------------------------------------------------------===//
-
-#include "ExportedAPI.h"
-
-#include "State.h"
-#include "Types.h"
-
-#include "OffloadAPI.h"
-#include "llvm/ADT/ArrayRef.h"
-
-#include <cstdio>
-#include <stdint.h>
-
-using namespace llvm;
-using namespace offload;
-
-/// Runtime API
-///{
-ol_device_handle_t olKGetDefaultDevice() {
- ol_device_handle_t DefaultDevice = ThreadStateTy::getDefaultDevice();
- return DefaultDevice;
-}
-
-ol_device_handle_t olKGetHostDevice() {
- ol_device_handle_t HostDevice = StateTy::getHostDevice();
- return HostDevice;
-}
-
-int olKGetDeviceCount() {
- int DeviceCount = StateTy::get().getDevices().size();
- return DeviceCount;
-}
-
-ol_device_handle_t olKGetDevice(int *DeviceNo) {
- ol_device_handle_t DefaultDevice = ThreadStateTy::getDefaultDevice();
- int DeviceCount = StateTy::get().getDevices().size();
- ArrayRef<ol_device_handle_t> Devices = StateTy::get().getDevices();
- for (int i = 0; i < DeviceCount; i++) {
- if (Devices[i] == DefaultDevice) {
- *DeviceNo = i;
- return Devices[i];
- }
- }
- return nullptr;
-}
-
-ol_device_handle_t olKSetDefaultDevice(int DeviceNo) {
- ArrayRef<ol_device_handle_t> Devices = StateTy::get().getDevices();
- if (DeviceNo < 0 || DeviceNo >= static_cast<int>(Devices.size()))
- return nullptr;
- ol_device_handle_t Device = Devices[DeviceNo];
- ThreadStateTy::get().setDefaultDevice(Device);
- return Device;
-}
-
-ol_queue_handle_t olKGetDefaultQueue() {
- ol_queue_handle_t DefaultQueue = ThreadStateTy::getDefaultQueue();
- return DefaultQueue;
-}
-
-CallConfigurationTy *olKGetCallConfiguration() {
- return &ThreadStateTy::getCallConfiguration();
-}
-
-void olKRegisterKernel(const void *ID, ol_symbol_handle_t Kernel) {
- StateTy::get().addKernel(ID, Kernel);
-}
-
-void olKUnregisterKernel(const void *ID) {
- if (StateTy *State = StateTy::tryGet())
- State->removeKernel(ID);
-}
-
-ol_symbol_handle_t olKGetKernel(const void *ID) {
- return StateTy::get().getKernel(ID);
-}
-
-void olKRegisterProgram(const void *ID, ol_program_handle_t Program) {
- StateTy::get().addProgram(ID, Program);
-}
-
-ol_program_handle_t olKUnregisterProgram(const void *ID) {
- if (StateTy *State = StateTy::tryGet())
- return State->removeProgram(ID);
- return nullptr;
-}
-
-ol_program_handle_t olKGetProgram(const void *ID) {
- return StateTy::get().getProgram(ID);
-}
-///}
diff --git a/offload/languages/kernel/src/LanguageCommon.cpp b/offload/languages/kernel/src/LanguageCommon.cpp
new file mode 100644
index 0000000000000..f0e00ed9db050
--- /dev/null
+++ b/offload/languages/kernel/src/LanguageCommon.cpp
@@ -0,0 +1,18 @@
+//===-- LanguageCommon.cpp - Shared CUDA/HIP runtime entry points ---------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "LanguageLaunch.h"
+#include "LanguageRegistration.h"
+
+#define LANGUAGE cuda
+#include "LanguageAliases.inc"
+#undef LANGUAGE
+
+#define LANGUAGE hip
+#include "LanguageAliases.inc"
+#undef LANGUAGE
diff --git a/offload/languages/kernel/src/LanguageLaunch.cpp b/offload/languages/kernel/src/LanguageLaunch.cpp
new file mode 100644
index 0000000000000..20779f89f969a
--- /dev/null
+++ b/offload/languages/kernel/src/LanguageLaunch.cpp
@@ -0,0 +1,83 @@
+//===-- LanguageLaunch.cpp - Language launch API --------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "LanguageLaunch.h"
+#include "State.h"
+
+#include <cstdio>
+
+using RuntimeState = llvm::offload::StateTy;
+using ThreadState = llvm::offload::ThreadStateTy;
+
+extern "C" {
+
+/// Push call configuration for kernel launch
+unsigned __llvmPushCallConfiguration(dim3 __grid_size, dim3 __block_size,
+ size_t __shared_memory, void *__stream) {
+ CallConfigurationTy &CC = ThreadState::getCallConfiguration();
+
+ CC.GridSize = __grid_size;
+ CC.BlockSize = __block_size;
+ CC.SharedMemory = __shared_memory;
+ CC.Stream = __stream;
+ return 0;
+}
+
+/// Pop call configuration for kernel launch
+unsigned __llvmPopCallConfiguration(dim3 *__grid_size, dim3 *__block_size,
+ size_t *__shared_memory, void **__stream) {
+ CallConfigurationTy &CC = ThreadState::getCallConfiguration();
+ *__grid_size = CC.GridSize;
+ *__block_size = CC.BlockSize;
+ *__shared_memory = CC.SharedMemory;
+ *__stream = CC.Stream;
+ return 0;
+}
+
+/// Internal kernel launch implementation
+ol_result_t __llvmLaunchKernelImpl(const char *KernelID, dim3 GridDim,
+ dim3 BlockDim, void *KernelArgsPtr,
+ size_t DynamicSharedMem, void *Stream) {
+ ol_device_handle_t Device = ThreadState::getDefaultDevice();
+ ol_symbol_handle_t Kernel = RuntimeState::getKernel(KernelID);
+
+ ol_kernel_launch_size_args_t LaunchSizeArgs;
+ LaunchSizeArgs.Dimensions =
+ 1 + (GridDim.y > 1 || BlockDim.y > 1) + (GridDim.z > 1 || BlockDim.z > 1);
+ LaunchSizeArgs.NumGroups.x = GridDim.x;
+ LaunchSizeArgs.NumGroups.y = std::max(GridDim.y, 1u);
+ LaunchSizeArgs.NumGroups.z = std::max(GridDim.z, 1u);
+ LaunchSizeArgs.GroupSize.x = BlockDim.x;
+ LaunchSizeArgs.GroupSize.y = std::max(BlockDim.y, 1u);
+ LaunchSizeArgs.GroupSize.z = std::max(BlockDim.z, 1u);
+ LaunchSizeArgs.DynSharedMemory = DynamicSharedMem;
+
+ ol_queue_handle_t Queue = Stream ? reinterpret_cast<ol_queue_handle_t>(Stream)
+ : ThreadState::getDefaultQueue();
+
+ struct OffloadKernelArgs {
+ void **Args;
+ size_t NumArgs;
+ size_t *ArgSizes;
+ };
+ OffloadKernelArgs *OKA = static_cast<OffloadKernelArgs *>(KernelArgsPtr);
+
+ return olLaunchKernel(Queue, Device, Kernel, &LaunchSizeArgs,
+ /*Properties=*/nullptr, OKA->NumArgs, OKA->Args,
+ OKA->ArgSizes);
+}
+
+unsigned __llvmLaunchKernel(const char *KernelID, dim3 GridDim, dim3 BlockDim,
+ void *KernelArgsPtr, size_t DynamicSharedMem,
+ void *Stream) {
+ ol_result_t Result = __llvmLaunchKernelImpl(
+ KernelID, GridDim, BlockDim, KernelArgsPtr, DynamicSharedMem, Stream);
+ return Result ? Result->Code : 0;
+}
+
+} // extern "C"
diff --git a/offload/languages/kernel/src/LanguageRegistration.cpp b/offload/languages/kernel/src/LanguageRegistration.cpp
new file mode 100644
index 0000000000000..231eaa691ff0b
--- /dev/null
+++ b/offload/languages/kernel/src/LanguageRegistration.cpp
@@ -0,0 +1,318 @@
+//===-- LanguageRegistration.cpp - Language registration API --------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "LanguageRegistration.h"
+#include "OffloadAPI.h"
+#include "State.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Frontend/Offloading/Utility.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Support/raw_ostream.h"
+#include <cstdio>
+#include <cstring>
+#include <inttypes.h>
+
+using RuntimeState = llvm::offload::StateTy;
+using ThreadState = llvm::offload::ThreadStateTy;
+
+typedef struct __attribute__((__packed__)) {
+ uint32_t Magic;
+ uint16_t Version;
+ uint16_t HeaderSize;
+ uint64_t FatSize;
+} CudaFatbinHeader;
+
+// Inspired by
+// https://github.com/n-eiling/cuda-fatbin-decompression/blob/master/fatbin-decompress.h
+typedef struct __attribute__((__packed__)) {
+ uint16_t Kind;
+ uint16_t Unknown1;
+ uint32_t HeaderSize;
+ uint64_t Size;
+ uint32_t CompressedSize;
+ uint32_t Unknown2;
+ uint16_t Minor;
+ uint16_t Major;
+ uint32_t Arch;
+ uint32_t ObjNameOffset;
+ uint32_t ObjNameLen;
+ uint64_t Flags;
+ uint64_t Zero;
+ uint64_t DecompressedSize;
+} CudaFatbinTextHeader;
+
+// HIP uses this format:
+// https://clang.llvm.org/docs/ClangOffloadBundler.html#bundled-binary-file-layout
+typedef struct __attribute__((__packed__)) {
+ char Magic[24];
+ uint64_t NumBundles;
+} HipFatbinHeader;
+
+typedef struct __attribute__((__packed__)) {
+ uint64_t BundleOffset;
+ uint64_t BundleSize;
+ uint64_t IdLength;
+ char IdString[];
+} HipFatbinBundleEntry;
+
+static void readTUFatbin(const char *Binary, const FatbinWrapperTy *FW) {
+ ol_device_handle_t Device = language_registration::getDefaultDevice();
+
+ const CudaFatbinHeader *Header =
+ reinterpret_cast<const CudaFatbinHeader *>(FW->Data);
+ size_t HeaderSize = static_cast<size_t>(Header->HeaderSize); // Usually 16
+ size_t FatbinSize = static_cast<size_t>(Header->FatSize);
+
+ const void *ProgramData = nullptr;
+ size_t ProgramSize = 0;
+ uint32_t ProgramArch = 0;
+
+ const char *ReadPosition = FW->Data + HeaderSize;
+ while (ReadPosition < (FW->Data + FatbinSize)) {
+ const CudaFatbinTextHeader *TextHeader =
+ reinterpret_cast<const CudaFatbinTextHeader *>(ReadPosition);
+ size_t TextHeaderSize =
+ static_cast<size_t>(TextHeader->HeaderSize); // Usually 64
+ size_t CubinSize = static_cast<size_t>(TextHeader->Size);
+ const void *CubinData =
+ static_cast<const char *>(ReadPosition + TextHeaderSize);
+
+ uint32_t Arch = TextHeader->Arch;
+ bool IsCompatible = false;
+ olIsValidBinary(Device, CubinData, CubinSize, &IsCompatible);
+ if (!IsCompatible) {
+ fprintf(stderr, "Device is not compatible with image.");
+ abort();
+ }
+
+ if (Arch > ProgramArch) {
+ ProgramData = CubinData;
+ ProgramSize = CubinSize;
+ ProgramArch = Arch;
+ }
+
+ ReadPosition += TextHeaderSize + CubinSize;
+ }
+
+ if (ProgramData == nullptr) {
+ fprintf(stderr, "Failed to find compatible binary\n");
+ abort();
+ }
+
+ ol_program_handle_t Program = nullptr;
+
+ ol_result_t Result =
+ olCreateProgram(Device, ProgramData, ProgramSize, &Program);
+
+ if (Result && Result->Code) {
+ fprintf(stderr, "Failed to register device code (%i): %s\n", Result->Code,
+ Result->Details);
+ abort();
+ }
+
+ language_registration::registerProgram(Binary, Program);
+}
+
+static void readHIPFatbinEntries(const char *Binary, const char *HIPFatbinPtr) {
+ ol_device_handle_t Device = language_registration::getDefaultDevice();
+
+ const char *CurrentReadPosition = HIPFatbinPtr;
+
+ const HipFatbinHeader *Header =
+ reinterpret_cast<const HipFatbinHeader *>(CurrentReadPosition);
+ CurrentReadPosition += sizeof(HipFatbinHeader);
+
+ uint64_t NumBundles = Header->NumBundles;
+
+ const void *ProgramData = nullptr;
+ size_t ProgramSize = 0;
+ uint64_t ProgramIdLength = 0;
+ const char *ProgramIdString = nullptr;
+
+ for (uint64_t BundleId = 0; BundleId < NumBundles; ++BundleId) {
+ const HipFatbinBundleEntry *BundleEntry =
+ reinterpret_cast<const HipFatbinBundleEntry *>(CurrentReadPosition);
+
+ uint64_t BundleOffset = BundleEntry->BundleOffset;
+ uint64_t BundleSize = BundleEntry->BundleSize;
+ const char *BundleIdString = BundleEntry->IdString;
+ uint64_t BundleIdLength = BundleEntry->IdLength;
+
+ // Advance by the size of the entry including the ID string
+ CurrentReadPosition += sizeof(HipFatbinBundleEntry) + BundleIdLength;
+
+ if (!BundleSize) {
+ continue;
+ }
+
+ bool IsCompatible = false;
+ olIsValidBinary(Device, HIPFatbinPtr + BundleOffset, BundleSize,
+ &IsCompatible);
+
+ if (!IsCompatible) {
+ fprintf(stderr, "Device is not compatible with image.");
+ abort();
+ }
+
+ llvm::StringRef CurrentBundleId(ProgramIdString, ProgramIdLength);
+ llvm::StringRef NewBundleId(BundleIdString, BundleIdLength);
+ if (NewBundleId.compare(CurrentBundleId) > 0) {
+ ProgramData = HIPFatbinPtr + BundleOffset;
+ ProgramSize = BundleSize;
+ ProgramIdLength = BundleIdLength;
+ ProgramIdString = BundleIdString;
+ }
+ }
+
+ if (ProgramData == nullptr) {
+ fprintf(stderr, "Failed to find compatible binary\n");
+ abort();
+ }
+
+ ol_program_handle_t Program = nullptr;
+ ol_result_t Result =
+ olCreateProgram(Device, ProgramData, ProgramSize, &Program);
+ if (Result && Result->Code) {
+ fprintf(stderr, "Failed to register device code (%i): %s\n", Result->Code,
+ Result->Details);
+ abort();
+ }
+
+ language_registration::registerProgram(Binary, Program);
+}
+
+/// Hidden, but exported, Registration API
+///{
+extern "C" {
+
+void __llvmRegisterFunction(const char *Binary, const char *KernelID,
+ char *KernelName, const char *KernelName1, int,
+ uint3 *, uint3 *, dim3 *, dim3 *, int *) {
+ ol_symbol_handle_t Kernel;
+ ol_program_handle_t Program = RuntimeState::getProgram(Binary);
+ ol_result_t Result = olGetSymbol(
+ Program, KernelName, ol_symbol_kind_t::OL_SYMBOL_KIND_KERNEL, &Kernel);
+ if (Result && Result->Code) {
+ fprintf(stderr, "Failed to register kernel (%i): %s\n", Result->Code,
+ Result->Details);
+ abort();
+ }
+
+ RuntimeState::registerKernel(KernelID, Kernel);
+}
+
+const char *__llvmRegisterFatBinary(const char *Binary) {
+ const auto *FW = reinterpret_cast<const FatbinWrapperTy *>(Binary);
+ if (FW->Magic == 0x466243b1) {
+ readTUFatbin(Binary, FW);
+ } else if (FW->Magic == 0x48495046) {
+ if (!memcmp(FW->Data, HIP_FATBIN_MAGIC_STR, HIP_FATBIN_MAGIC_STR_LEN))
+ readHIPFatbinEntries(Binary, FW->Data);
+ else
+ readTUFatbin(Binary, FW);
+ } else {
+ fprintf(stderr, "Unknown fatbin format");
+ }
+
+ return Binary;
+}
+
+void __llvmUnregisterFatBinary(void *Handle) {
+ if (ol_program_handle_t Program =
+ language_registration::unregisterProgram(Handle))
+ olDestroyProgram(Program);
+}
+
+void __llvmRegisterVar(void **, char *, char *, const char *, int, int, int,
+ int) {
+ llvm::errs() << "RegisterVar is not implemented!" << "\n";
+}
+
+void __llvmRegisterManagedVar(void **, char *, char *, const char *, size_t,
+ unsigned) {
+ llvm::errs() << "RegisterManagedVar is not implemented!" << "\n";
+}
+
+void __llvmRegisterSurface(void **, const struct surfaceReference *,
+ const void **, const char *, int, int) {
+ llvm::errs() << "RegisterSurface is not implemented!" << "\n";
+}
+
+void __llvmRegisterTexture(void **, const struct textureReference *,
+ const void **, const char *, int, int, int) {
+ llvm::errs() << "RegisterTexture is not implemented!" << "\n";
+}
+
+/// This struct is a record of the device image information
+struct __tgt_device_image {
+ void *ImageStart; // Pointer to the target code start
+ void *ImageEnd; // Pointer to the target code end
+ llvm::offloading::EntryTy
+ *EntriesBegin; // Begin of table with all target entries
+ llvm::offloading::EntryTy *EntriesEnd; // End of table (non inclusive)
+};
+
+/// This struct is a record of all the host code that may be offloaded to a
+/// target.
+struct __tgt_bin_desc {
+ int32_t NumDeviceImages; // Number of device types supported
+ __tgt_device_image *DeviceImages; // Array of device images (1 per dev. type)
+ llvm::offloading::EntryTy
+ *HostEntriesBegin; // Begin of table with all host entries
+ llvm::offloading::EntryTy *HostEntriesEnd; // End of table (non inclusive)
+};
+
+void __tgt_register_lib(__tgt_bin_desc *Desc) {
+ // TODO: For each device, lazily.
+ ol_device_handle_t Device = ThreadState::getDefaultDevice();
+
+ for (int32_t I = 0, E = Desc->NumDeviceImages; I < E; ++I) {
+ ol_program_handle_t Program = nullptr;
+
+ __tgt_device_image &DeviceImage = Desc->DeviceImages[I];
+ void *ProgramData = DeviceImage.ImageStart;
+ size_t ProgramSize =
+ (char *)DeviceImage.ImageEnd - (char *)DeviceImage.ImageStart;
+ ol_result_t Result =
+ olCreateProgram(Device, ProgramData, ProgramSize, &Program);
+
+ if (Result && Result->Code) {
+ fprintf(stderr, "Failed to register device code (%i): %s\n", Result->Code,
+ Result->Details);
+ abort();
+ }
+
+ RuntimeState::registerProgram(DeviceImage.ImageStart, Program);
+
+ for (auto *Entry = DeviceImage.EntriesBegin;
+ Entry != DeviceImage.EntriesEnd; ++Entry) {
+ if (!Entry->Size && !Entry->Flags)
+ __llvmRegisterFunction((const char *)DeviceImage.ImageStart,
+ (const char *)Entry->Address, Entry->SymbolName,
+ Entry->SymbolName, 0, nullptr, nullptr, nullptr,
+ nullptr, nullptr);
+ }
+ }
+}
+
+void __tgt_unregister_lib(__tgt_bin_desc *Desc) {
+ for (int32_t I = 0, E = Desc->NumDeviceImages; I < E; ++I) {
+ __tgt_device_image &DeviceImage = Desc->DeviceImages[I];
+ for (auto *Entry = DeviceImage.EntriesBegin;
+ Entry != DeviceImage.EntriesEnd; ++Entry) {
+ if (!Entry->Size && !Entry->Flags)
+ RuntimeState::unregisterKernel((const char *)Entry->Address);
+ }
+
+ if (ol_program_handle_t Program =
+ RuntimeState::unregisterProgram(DeviceImage.ImageStart))
+ olDestroyProgram(Program);
+ }
+}
+}
+///}
diff --git a/offload/languages/kernel/src/LanguageRuntime.cpp b/offload/languages/kernel/src/LanguageRuntime.cpp
new file mode 100644
index 0000000000000..b1b21f57e35f1
--- /dev/null
+++ b/offload/languages/kernel/src/LanguageRuntime.cpp
@@ -0,0 +1,223 @@
+//===-- LanguageRuntime.cpp - Kernel language runtime API implementation --===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LANGUAGE
+#error This file should be included, or used, with a LANGUAGE macro set.
+#endif
+
+// Rename the generic runtime API before declaring or defining language symbols.
+#include "DefineLanguageNames.inc"
+#include "LanguageRuntime.h"
+
+#include "State.h"
+#include "Types.h"
+
+#include "OffloadAPI.h"
+
+#include <cassert>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+
+#define STR(X) #X
+#define LANGUAGE_STR STR(LANGUAGE)
+
+using RuntimeState = llvm::offload::StateTy;
+using ThreadState = llvm::offload::ThreadStateTy;
+
+static Error_t convertResult(ol_result_t Result) {
+ if (Result == OL_SUCCESS)
+ return Success;
+ switch (Result->Code) {
+ case OL_ERRC_INVALID_VALUE:
+ return ErrorInvalidValue;
+ default:
+ return ErrorInvalidValue;
+ }
+}
+
+Error_t Malloc(void **DevPtr, size_t Size) {
+ ol_device_handle_t Device = ThreadState::getDefaultDevice();
+ ol_result_t Result = olMemAlloc(Device, OL_ALLOC_TYPE_DEVICE, Size, DevPtr);
+ return convertResult(Result);
+}
+
+Error_t Free(void *DevPtr) {
+ ol_result_t Result = olMemFree(DevPtr);
+ return convertResult(Result);
+}
+
+Error_t Memcpy(void *Dst, const void *Src, size_t Size, MemcpyKind Kind) {
+ ol_queue_handle_t Queue = ThreadState::getDefaultQueue();
+
+ ol_result_t Result;
+ switch (Kind) {
+ case MemcpyHostToHost: {
+ ol_device_handle_t Host = RuntimeState::getHostDevice();
+ Result = olMemcpy(nullptr, Dst, Host, const_cast<void *>(Src), Host, Size);
+ break;
+ }
+ case MemcpyHostToDevice: {
+ ol_device_handle_t Device = ThreadState::getDefaultDevice();
+ ol_device_handle_t Host = RuntimeState::getHostDevice();
+ Result = olMemcpy(Queue, Dst, Device, const_cast<void *>(Src), Host, Size);
+ break;
+ }
+ case MemcpyDeviceToHost: {
+ ol_device_handle_t Device = ThreadState::getDefaultDevice();
+ ol_device_handle_t Host = RuntimeState::getHostDevice();
+
+ Result = olMemcpy(Queue, Dst, Host, const_cast<void *>(Src), Device, Size);
+ break;
+ }
+ case MemcpyDeviceToDevice: {
+ ol_device_handle_t Device = ThreadState::getDefaultDevice();
+
+ Result =
+ olMemcpy(Queue, Dst, Device, const_cast<void *>(Src), Device, Size);
+ break;
+ }
+ case MemcpyDefault:
+ fprintf(stderr, LANGUAGE_STR "MemcpyDefault is not implemented yet");
+ abort();
+ };
+
+ Result = olSyncQueue(Queue);
+
+ return convertResult(Result);
+}
+
+Error_t DeviceSynchronize() {
+ // TODO: This is not correct. We likely want to pipe this through to the
+ // plugins.
+ ol_queue_handle_t Queue = ThreadState::getDefaultQueue();
+ ol_result_t Result = olSyncQueue(Queue);
+ return convertResult(Result);
+}
+
+Error_t GetLastError() {
+ // TODO:
+ return Success;
+}
+
+Error_t PeekAtLastError() {
+ // TODO:
+ return Success;
+}
+
+const char *GetErrorName(Error_t Error) {
+ // TODO:
+ return "";
+}
+
+const char *GetErrorString(Error_t Error) {
+ // TODO:
+ return "";
+}
+
+Error_t GetDevice(int *DeviceNo) {
+ ol_device_handle_t Device = RuntimeState::getDevice(DeviceNo);
+ if (!Device)
+ return ErrorInvalidValue;
+ return Success;
+}
+
+Error_t GetDeviceCount(int *Count) {
+ *Count = RuntimeState::getDeviceCount();
+ return Success;
+}
+
+Error_t SetDevice(int DeviceNo) {
+ ol_device_handle_t Device = RuntimeState::setDefaultDevice(DeviceNo);
+ if (!Device)
+ return ErrorInvalidValue;
+ assert(Device == ThreadState::getDefaultDevice() &&
+ "Set Device is not Default Device");
+ return Device ? Success : ErrorInvalidValue;
+}
+
+Error_t HostAlloc(void **Ptr, size_t Size, unsigned int Flags) {
+ ol_device_handle_t Device = ThreadState::getDefaultDevice();
+ ol_result_t Result = olMemAllocHost(Device, Size, Ptr);
+ return convertResult(Result);
+}
+
+Error_t MallocHost(void **Ptr, size_t Size) {
+ return HostAlloc(Ptr, Size, /* HostAllocDefault */ 0);
+}
+
+Error_t FreeHost(void *Ptr) {
+ ol_result_t Result = olMemFree(Ptr);
+ return convertResult(Result);
+}
+
+Error_t DriverGetVersion(int *Version) {
+ // TODO:
+ *Version = 42;
+ return Success;
+}
+
+Error_t GetDeviceProperties(DeviceProp_t *DeviceProp, int DeviceNo) {
+ ol_device_handle_t Device = ThreadState::getDefaultDevice();
+ size_t NameSize = 0;
+ olGetDeviceInfoSize(Device, OL_DEVICE_INFO_NAME, &NameSize);
+ assert(NameSize <= sizeof(DeviceProp->name) &&
+ "Device name is too long for DeviceProp_t");
+ olGetDeviceInfo(Device, OL_DEVICE_INFO_NAME, NameSize, &DeviceProp->name[0]);
+ olGetDeviceInfo(Device, OL_DEVICE_INFO_GLOBAL_MEM_SIZE, sizeof(size_t),
+ &DeviceProp->totalGlobalMem);
+ olGetDeviceInfo(Device, OL_DEVICE_INFO_NUM_COMPUTE_UNITS, sizeof(uint32_t),
+ &DeviceProp->multiProcessorCount);
+ olGetDeviceInfo(Device, OL_DEVICE_INFO_NUM_LANES, sizeof(uint32_t),
+ &DeviceProp->warpSize);
+ return Success;
+}
+
+static Error_t getQueueFromStream(Stream_t Stream, ol_queue_handle_t *Queue) {
+ if (!Stream)
+ return ErrorInvalidValue;
+ *Queue = reinterpret_cast<ol_queue_handle_t>(Stream);
+ return Success;
+}
+
+Error_t StreamCreate(Stream_t *Stream) {
+ ol_queue_handle_t Queue;
+ olCreateQueue(ThreadState::getDefaultDevice(), &Queue);
+ *Stream = reinterpret_cast<Stream_t>(Queue);
+ return Success;
+}
+
+Error_t StreamCreateWithFlags(Stream_t *Stream, unsigned int Flags) {
+ if (Flags == StreamCreateWithFlagsFlags::StreamDefault)
+ // FIXME: [h15] offload streams are non-blocking by default
+ return StreamCreate(Stream);
+ if (Flags == StreamCreateWithFlagsFlags::StreamNonBlocking) {
+ return StreamCreate(Stream);
+ }
+ return ErrorInvalidValue;
+}
+
+Error_t StreamDestroy(Stream_t Stream) {
+ ol_queue_handle_t Queue;
+ Error_t Err = getQueueFromStream(Stream, &Queue);
+ if (Err != Success)
+ return Err;
+ ol_result_t Result = olDestroyQueue(Queue);
+ return convertResult(Result);
+}
+
+Error_t StreamSynchronize(Stream_t Stream) {
+ ol_queue_handle_t Queue;
+ Error_t Err = getQueueFromStream(Stream, &Queue);
+ if (Err != Success)
+ return Err;
+ ol_result_t Result = olSyncQueue(Queue);
+ return convertResult(Result);
+}
+
+#include "UndefineLanguageNames.inc"
diff --git a/offload/languages/kernel/src/State.cpp b/offload/languages/kernel/src/State.cpp
index eff3c31257e93..3dbd1f436ff24 100644
--- a/offload/languages/kernel/src/State.cpp
+++ b/offload/languages/kernel/src/State.cpp
@@ -1,38 +1,41 @@
-//===------ State.cpp - Kernel Language (CUDA/HIP) persistent state -------===//
+//===-- State.cpp - Kernel language persistent state ----------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
-//
-//===----------------------------------------------------------------------===//
#include "State.h"
#include "Types.h"
#include "OffloadAPI.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/raw_ostream.h"
#include <atomic>
+#include <cassert>
#include <cstdio>
#include <mutex>
#define CHECK_FATAL(Result, ...) \
if (Result && Result->Code) { \
- fprintf(stderr, __VA_ARGS__); \
+ llvm::errs() << __VA_ARGS__ << '\n'; \
abort(); \
}
using namespace llvm;
using namespace offload;
-std::atomic<uint32_t> AnyNonDefaultDevice = 0;
+// Weak so another runtime object can override the default stream mode.
__attribute__((weak)) uint32_t PerThreadQueue = 0;
thread_local CallConfigurationTy CC = {};
+// Process-wide singleton and thread-state registry.
static std::mutex StateLock;
static std::atomic<StateTy *> StatePtr = nullptr;
@@ -50,7 +53,7 @@ static void deleteThreadState() {
return;
for (auto *TS : *ThreadStates)
- delete (TS);
+ delete TS;
delete ThreadStates;
ThreadState = nullptr;
}
@@ -58,7 +61,7 @@ static void deleteThreadState() {
static void deleteState() {
StateTy *ST = StatePtr.load();
StatePtr.store(nullptr);
- delete (ST);
+ delete ST;
}
static void destroyQueue(ol_queue_handle_t &Queue) {
@@ -70,6 +73,11 @@ static void destroyQueue(ol_queue_handle_t &Queue) {
Queue = nullptr;
}
+namespace llvm {
+namespace offload {
+
+// ThreadStateTy implementation.
+
ThreadStateTy::ThreadStateTy() {
if (PerThreadQueue) [[unlikely]]
createDefaultQueue(getDefaultDevice());
@@ -98,11 +106,6 @@ ol_device_handle_t ThreadStateTy::getDefaultDevice() {
DD = Device;
break;
}
- if (AnyNonDefaultDevice.load(std::memory_order_relaxed)) [[unlikely]] {
- ol_device_handle_t TDD = ThreadStateTy::get().DefaultDevice;
- if (TDD)
- DD = TDD;
- }
return DD;
}
@@ -117,8 +120,9 @@ CallConfigurationTy &ThreadStateTy::getCallConfiguration() {
}
void ThreadStateTy::setDefaultDevice(ol_device_handle_t Device) {
- DefaultDevice = Device;
- createDefaultQueue(Device);
+ ThreadStateTy &State = get();
+ State.DefaultDevice = Device;
+ State.createDefaultQueue(Device);
}
void ThreadStateTy::createDefaultQueue(ol_device_handle_t Device) {
@@ -128,6 +132,8 @@ void ThreadStateTy::createDefaultQueue(ol_device_handle_t Device) {
"Failed to create per-thread default queue");
}
+// StateTy implementation.
+
StateTy &StateTy::get() {
StateTy *ST = StatePtr.load();
if (!ST) [[unlikely]] {
@@ -143,7 +149,103 @@ StateTy &StateTy::get() {
StateTy *StateTy::tryGet() { return StatePtr.load(); }
-static bool addDevices(ol_device_handle_t Device, void *Payload) {
+ol_device_handle_t StateTy::getHostDevice() { return get().HostDevice; }
+
+int StateTy::getDeviceCount() {
+ int DeviceCount = get().getDevices().size();
+ return DeviceCount;
+}
+
+ol_device_handle_t StateTy::getDevice(int *DeviceNo) {
+ ol_device_handle_t DefaultDevice = ThreadStateTy::getDefaultDevice();
+ int DeviceCount = get().getDevices().size();
+ ArrayRef<ol_device_handle_t> Devices = get().getDevices();
+ for (int i = 0; i < DeviceCount; i++) {
+ if (Devices[i] == DefaultDevice) {
+ *DeviceNo = i;
+ return Devices[i];
+ }
+ }
+ return nullptr;
+}
+
+ol_device_handle_t StateTy::setDefaultDevice(int DeviceNo) {
+ ArrayRef<ol_device_handle_t> Devices = get().getDevices();
+ if (DeviceNo < 0 || DeviceNo >= static_cast<int>(Devices.size()))
+ return nullptr;
+ ol_device_handle_t Device = Devices[DeviceNo];
+ ThreadStateTy::setDefaultDevice(Device);
+ return Device;
+}
+
+ArrayRef<ol_device_handle_t> StateTy::getDevices() const { return Devices; }
+
+void StateTy::addDevice(ol_device_handle_t Device) {
+ Devices.push_back(Device);
+}
+
+void StateTy::setHostDevice(ol_device_handle_t Device) {
+ if (!HostDevice)
+ HostDevice = Device;
+}
+
+void StateTy::addKernel(KernelIDTy KernelID, ol_symbol_handle_t Kernel) {
+ KernelMap[KernelID] = Kernel;
+}
+
+void StateTy::removeKernel(KernelIDTy KernelID) { KernelMap.erase(KernelID); }
+
+ol_symbol_handle_t StateTy::lookupKernel(KernelIDTy KernelID) {
+ return KernelMap[KernelID];
+}
+
+void StateTy::registerKernel(const void *ID, ol_symbol_handle_t Kernel) {
+ get().addKernel(ID, Kernel);
+}
+
+void StateTy::unregisterKernel(const void *ID) {
+ if (StateTy *State = tryGet())
+ State->removeKernel(ID);
+}
+
+ol_symbol_handle_t StateTy::getKernel(const void *ID) {
+ return get().lookupKernel(ID);
+}
+
+void StateTy::addProgram(const void *Binary, ol_program_handle_t Program) {
+ BinaryRegisterMap[Binary] = Program;
+}
+
+ol_program_handle_t StateTy::removeProgram(const void *Binary) {
+ auto It = BinaryRegisterMap.find(Binary);
+ if (It == BinaryRegisterMap.end())
+ return nullptr;
+ ol_program_handle_t Program = It->second;
+ BinaryRegisterMap.erase(It);
+ return Program;
+}
+
+ol_program_handle_t StateTy::lookupProgram(const void *Binary) {
+ assert(BinaryRegisterMap.count(Binary) &&
+ "Program not registered for binary");
+ return BinaryRegisterMap[Binary];
+}
+
+void StateTy::registerProgram(const void *ID, ol_program_handle_t Program) {
+ get().addProgram(ID, Program);
+}
+
+ol_program_handle_t StateTy::unregisterProgram(const void *ID) {
+ if (StateTy *State = tryGet())
+ return State->removeProgram(ID);
+ return nullptr;
+}
+
+ol_program_handle_t StateTy::getProgram(const void *ID) {
+ return get().lookupProgram(ID);
+}
+
+bool StateTy::addDevices(ol_device_handle_t Device, void *Payload) {
StateTy &State = *reinterpret_cast<StateTy *>(Payload);
ol_platform_handle_t Platform;
ol_result_t Result;
@@ -168,7 +270,8 @@ static bool addDevices(ol_device_handle_t Device, void *Payload) {
StateTy::StateTy() {
CHECK_FATAL(olInit(nullptr), "Failed to initialize the LLVMOffload");
- CHECK_FATAL(olIterateDevices(addDevices, this), "Failed to identify devices");
+ CHECK_FATAL(olIterateDevices(StateTy::addDevices, this),
+ "Failed to identify devices");
if (!PerThreadQueue) [[likely]]
if (!Devices.empty()) [[likely]]
@@ -196,3 +299,6 @@ void StateTy::destroyRegisteredPrograms() {
for (ol_program_handle_t Program : Programs)
olDestroyProgram(Program);
}
+
+} // namespace offload
+} // namespace llvm
>From 67498fac91e7fe41beed1364d141f4a194ec973e Mon Sep 17 00:00:00 2001
From: Sophia Herrmann <herrmann15 at llnl.gov>
Date: Fri, 24 Jul 2026 10:56:46 -0700
Subject: [PATCH 3/4] remove unimplemented stuff + minor fixes
formatting
remove empty stubs
fix HostToHost bug + SetDevice assertion
add C++ style includes
fix olMemAlloc after rebase
---
.../include/kernel/DefineLanguageNames.inc | 11 ------
.../include/kernel/LanguageRuntime.h | 39 +------------------
.../include/kernel/UndefineLanguageNames.inc | 10 -----
.../languages/kernel/src/LanguageRuntime.cpp | 38 +-----------------
4 files changed, 3 insertions(+), 95 deletions(-)
diff --git a/offload/languages/include/kernel/DefineLanguageNames.inc b/offload/languages/include/kernel/DefineLanguageNames.inc
index 7f2b0776a03ff..cfab6998c28e6 100644
--- a/offload/languages/include/kernel/DefineLanguageNames.inc
+++ b/offload/languages/include/kernel/DefineLanguageNames.inc
@@ -23,10 +23,6 @@
#define MemcpyDeviceToHost COMBINE(LANGUAGE, MemcpyDeviceToHost)
#define MemcpyDeviceToDevice COMBINE(LANGUAGE, MemcpyDeviceToDevice)
#define MemcpyDefault COMBINE(LANGUAGE, MemcpyDefault)
-#define GetLastError COMBINE(LANGUAGE, GetLastError)
-#define PeekAtLastError COMBINE(LANGUAGE, PeekAtLastError)
-#define GetErrorName COMBINE(LANGUAGE, GetErrorName)
-#define GetErrorString COMBINE(LANGUAGE, GetErrorString)
#define GetDevice COMBINE(LANGUAGE, GetDevice)
#define GetDeviceCount COMBINE(LANGUAGE, GetDeviceCount)
#define SetDevice COMBINE(LANGUAGE, SetDevice)
@@ -37,15 +33,8 @@
#define HostAllocWriteCombined COMBINE(LANGUAGE, HostAllocWriteCombined)
#define MallocHost COMBINE(LANGUAGE, MallocHost)
#define FreeHost COMBINE(LANGUAGE, FreeHost)
-#define DriverGetVersion COMBINE(LANGUAGE, DriverGetVersion)
#define GetDeviceProperties COMBINE(LANGUAGE, GetDeviceProperties)
-#define OccupancyMaxPotentialBlockSizeVariableSMem \
- COMBINE(LANGUAGE, OccupancyMaxPotentialBlockSizeVariableSMem)
#define Stream_t COMBINE(LANGUAGE, Stream_t)
#define StreamCreate COMBINE(LANGUAGE, StreamCreate)
-#define StreamCreateWithFlags COMBINE(LANGUAGE, StreamCreateWithFlags)
#define StreamDestroy COMBINE(LANGUAGE, StreamDestroy)
#define StreamSynchronize COMBINE(LANGUAGE, StreamSynchronize)
-#define StreamCreateWithFlagsFlags COMBINE(LANGUAGE, StreamCreateWithFlagsFlags)
-#define StreamDefault COMBINE(LANGUAGE, StreamDefault)
-#define StreamNonBlocking COMBINE(LANGUAGE, StreamNonBlocking)
diff --git a/offload/languages/include/kernel/LanguageRuntime.h b/offload/languages/include/kernel/LanguageRuntime.h
index dc00ae4ad5a1c..b072087ba0e7d 100644
--- a/offload/languages/include/kernel/LanguageRuntime.h
+++ b/offload/languages/include/kernel/LanguageRuntime.h
@@ -9,10 +9,10 @@
#ifndef LLVM_OFFLOAD_LANGUAGES_INCLUDE_KERNEL_LANGUAGE_RUNTIME_H
#define LLVM_OFFLOAD_LANGUAGES_INCLUDE_KERNEL_LANGUAGE_RUNTIME_H
+#include <cstddef>
+#include <cstdint>
#include <cstdio>
#include <cstdlib>
-#include <stddef.h>
-#include <stdint.h>
enum Error_t : uint32_t {
Success = 0,
@@ -48,11 +48,6 @@ enum HostAllocFlags : unsigned int {
HostAllocWriteCombined = 0x04,
};
-enum StreamCreateWithFlagsFlags : unsigned int {
- StreamDefault = 0x00,
- StreamNonBlocking = 0x01,
-};
-
typedef struct Stream_st *Stream_t;
/// Malloc, with type template overlay.
@@ -93,14 +88,6 @@ static inline Error_t Memcpy(T *Dst, const T *Src, size_t Size,
Error_t DeviceSynchronize();
-Error_t GetLastError();
-
-Error_t PeekAtLastError();
-
-const char *GetErrorName(Error_t Error);
-
-const char *GetErrorString(Error_t Error);
-
Error_t GetDevice(int *DeviceNo);
Error_t GetDeviceCount(int *Count);
@@ -109,36 +96,14 @@ Error_t SetDevice(int DeviceNo);
Error_t FreeHost(void *Ptr);
-Error_t DriverGetVersion(int *Version);
-
Error_t GetDeviceProperties(DeviceProp_t *DeviceProp, int DeviceNo);
Error_t StreamCreate(Stream_t *stream);
-Error_t StreamCreateWithFlags(Stream_t *stream, unsigned int flags);
-
Error_t StreamDestroy(Stream_t stream);
Error_t StreamSynchronize(Stream_t stream);
-template <typename UnaryFunction, class T>
-static inline Error_t OccupancyMaxPotentialBlockSizeVariableSMem(
- int *minGridSize, int *blockSize, T func,
- UnaryFunction blockSizeToDynamicSMemSize, int blockSizeLimit = 0) {
-#if defined(__AMDGPU__)
- // TODO: values taken from AMD Instinct MI250X gfx90a
- *minGridSize = 220;
- *blockSize = 1024;
-#elif defined(__NVPTX__)
- // TODO: values taken from NVIDIA H100 80GB HBM3
- *minGridSize = 264;
- *blockSize = 1024;
-#endif
- return Success;
-}
-
-///
-
#if defined(__AMDGPU__) || defined(__NVPTX__)
#include <gpuintrin.h>
diff --git a/offload/languages/include/kernel/UndefineLanguageNames.inc b/offload/languages/include/kernel/UndefineLanguageNames.inc
index ab5f257cdfaea..c1cc75719a18c 100644
--- a/offload/languages/include/kernel/UndefineLanguageNames.inc
+++ b/offload/languages/include/kernel/UndefineLanguageNames.inc
@@ -20,10 +20,6 @@
#undef MemcpyDeviceToHost
#undef MemcpyDeviceToDevice
#undef MemcpyDefault
-#undef GetLastError
-#undef PeekAtLastError
-#undef GetErrorName
-#undef GetErrorString
#undef GetDevice
#undef GetDeviceCount
#undef SetDevice
@@ -35,14 +31,8 @@
#undef HostAllocWriteCombined
#undef MallocHost
#undef FreeHost
-#undef DriverGetVersion
#undef GetDeviceProperties
-#undef OccupancyMaxPotentialBlockSizeVariableSMem
#undef Stream_t
#undef StreamCreate
-#undef StreamCreateWithFlags
#undef StreamDestroy
#undef StreamSynchronize
-#undef StreamCreateWithFlagsFlags
-#undef StreamDefault
-#undef StreamNonBlocking
diff --git a/offload/languages/kernel/src/LanguageRuntime.cpp b/offload/languages/kernel/src/LanguageRuntime.cpp
index b1b21f57e35f1..0859a7955dbe7 100644
--- a/offload/languages/kernel/src/LanguageRuntime.cpp
+++ b/offload/languages/kernel/src/LanguageRuntime.cpp
@@ -100,26 +100,6 @@ Error_t DeviceSynchronize() {
return convertResult(Result);
}
-Error_t GetLastError() {
- // TODO:
- return Success;
-}
-
-Error_t PeekAtLastError() {
- // TODO:
- return Success;
-}
-
-const char *GetErrorName(Error_t Error) {
- // TODO:
- return "";
-}
-
-const char *GetErrorString(Error_t Error) {
- // TODO:
- return "";
-}
-
Error_t GetDevice(int *DeviceNo) {
ol_device_handle_t Device = RuntimeState::getDevice(DeviceNo);
if (!Device)
@@ -138,7 +118,7 @@ Error_t SetDevice(int DeviceNo) {
return ErrorInvalidValue;
assert(Device == ThreadState::getDefaultDevice() &&
"Set Device is not Default Device");
- return Device ? Success : ErrorInvalidValue;
+ return Success;
}
Error_t HostAlloc(void **Ptr, size_t Size, unsigned int Flags) {
@@ -156,12 +136,6 @@ Error_t FreeHost(void *Ptr) {
return convertResult(Result);
}
-Error_t DriverGetVersion(int *Version) {
- // TODO:
- *Version = 42;
- return Success;
-}
-
Error_t GetDeviceProperties(DeviceProp_t *DeviceProp, int DeviceNo) {
ol_device_handle_t Device = ThreadState::getDefaultDevice();
size_t NameSize = 0;
@@ -192,16 +166,6 @@ Error_t StreamCreate(Stream_t *Stream) {
return Success;
}
-Error_t StreamCreateWithFlags(Stream_t *Stream, unsigned int Flags) {
- if (Flags == StreamCreateWithFlagsFlags::StreamDefault)
- // FIXME: [h15] offload streams are non-blocking by default
- return StreamCreate(Stream);
- if (Flags == StreamCreateWithFlagsFlags::StreamNonBlocking) {
- return StreamCreate(Stream);
- }
- return ErrorInvalidValue;
-}
-
Error_t StreamDestroy(Stream_t Stream) {
ol_queue_handle_t Queue;
Error_t Err = getQueueFromStream(Stream, &Queue);
>From 6a5a98219b15dadf4c94b04c86607505024b33b5 Mon Sep 17 00:00:00 2001
From: Sophia Herrmann <herrmann15 at llnl.gov>
Date: Thu, 30 Jul 2026 14:43:27 -0700
Subject: [PATCH 4/4] remove legacy fatbin registration wrapping
---
offload/languages/README.md | 3 +-
.../kernel/include/LanguageAliases.inc | 22 +-
.../languages/kernel/include/LanguageLaunch.h | 1 -
.../kernel/include/LanguageRegistration.h | 20 --
offload/languages/kernel/include/State.h | 25 ++-
.../languages/kernel/src/LanguageLaunch.cpp | 25 +--
.../kernel/src/LanguageRegistration.cpp | 195 +-----------------
.../languages/kernel/src/LanguageRuntime.cpp | 6 +-
offload/languages/kernel/src/State.cpp | 71 +++----
9 files changed, 68 insertions(+), 300 deletions(-)
diff --git a/offload/languages/README.md b/offload/languages/README.md
index 8361648df1779..2ef13f49321f0 100644
--- a/offload/languages/README.md
+++ b/offload/languages/README.md
@@ -24,4 +24,5 @@ Source files that do not depend on CUDA or HIP spelling are compiled once and
shared by both languages.
The `cuda/` and `hip/` directories are kept in case there is ever a need for
-language-specific behavior.
+language-specific behavior. For now, the minimal differences between cuda and
+hip are taken care of in cuda/hip_runtime.h after the generic parts are included.
diff --git a/offload/languages/kernel/include/LanguageAliases.inc b/offload/languages/kernel/include/LanguageAliases.inc
index 67c188bc16269..551f64a5b8fc8 100644
--- a/offload/languages/kernel/include/LanguageAliases.inc
+++ b/offload/languages/kernel/include/LanguageAliases.inc
@@ -24,10 +24,11 @@
#define LA_IMPL1(PREFIX, L, NAME) LA_IMPL2(PREFIX, L, NAME)
#define LANGUAGE_NAME(PREFIX, NAME) LA_IMPL1(PREFIX, LANGUAGE, NAME)
-extern "C" void LANGUAGE_NAME(__, RegisterFunction)(
- const char *Binary, const char *KernelID, char *KernelName,
- const char *KernelName1, int ThreadLimit, uint3 *Tid, uint3 *Bid,
- dim3 *BlockDim, dim3 *GridDim, int *WSize) {
+extern "C" void
+LANGUAGE_NAME(__, RegisterFunction)(const char *Binary, const char *KernelID,
+ char *KernelName, const char *KernelName1,
+ int ThreadLimit, uint3 *Tid, uint3 *Bid,
+ dim3 *BlockDim, dim3 *GridDim, int *WSize) {
__llvmRegisterFunction(Binary, KernelID, KernelName, KernelName1, ThreadLimit,
Tid, Bid, BlockDim, GridDim, WSize);
}
@@ -41,9 +42,11 @@ extern "C" void LANGUAGE_NAME(__, RegisterVar)(void **Data, char *HostVar,
Constant, Global);
}
-extern "C" void LANGUAGE_NAME(__, RegisterManagedVar)(
- void **Data, char *HostVar, char *DeviceAddress, const char *DeviceName,
- size_t Size, unsigned Align) {
+extern "C" void LANGUAGE_NAME(__,
+ RegisterManagedVar)(void **Data, char *HostVar,
+ char *DeviceAddress,
+ const char *DeviceName,
+ size_t Size, unsigned Align) {
__llvmRegisterManagedVar(Data, HostVar, DeviceAddress, DeviceName, Size,
Align);
}
@@ -60,8 +63,9 @@ extern "C" void LANGUAGE_NAME(__, RegisterTexture)(
__llvmRegisterTexture(Data, TexRef, DevPtr, Name, Dim, Norm, Ext);
}
-extern "C" unsigned LANGUAGE_NAME(__, PopCallConfiguration)(
- dim3 *GridSize, dim3 *BlockSize, size_t *SharedMemory, void **Stream) {
+extern "C" unsigned
+LANGUAGE_NAME(__, PopCallConfiguration)(dim3 *GridSize, dim3 *BlockSize,
+ size_t *SharedMemory, void **Stream) {
return __llvmPopCallConfiguration(GridSize, BlockSize, SharedMemory, Stream);
}
diff --git a/offload/languages/kernel/include/LanguageLaunch.h b/offload/languages/kernel/include/LanguageLaunch.h
index 161aead85bbef..c72f3ec215ac1 100644
--- a/offload/languages/kernel/include/LanguageLaunch.h
+++ b/offload/languages/kernel/include/LanguageLaunch.h
@@ -12,7 +12,6 @@
#include "OffloadAPI.h"
#include "Types.h"
-#include <algorithm> // for std::max
#include <cstddef>
#include <cstdint>
diff --git a/offload/languages/kernel/include/LanguageRegistration.h b/offload/languages/kernel/include/LanguageRegistration.h
index 248aa74f600bd..7570ce76de546 100644
--- a/offload/languages/kernel/include/LanguageRegistration.h
+++ b/offload/languages/kernel/include/LanguageRegistration.h
@@ -15,22 +15,6 @@
#include <cstdint>
#include <iterator>
-#define HIP_FATBIN_MAGIC_STR "__CLANG_OFFLOAD_BUNDLE__"
-constexpr auto HIP_FATBIN_MAGIC_STR_LEN = sizeof(HIP_FATBIN_MAGIC_STR) - 1;
-
-namespace {
-struct FatbinWrapperTy {
- int Magic;
- int Version;
- const char *Data;
- const char *DataEnd;
-};
-} // namespace
-
-static void readTUFatbin(const char *Binary, const FatbinWrapperTy *FW);
-
-static void readHIPFatbinEntries(const char *Binary, const char *HIPFatbinPtr);
-
/// Hidden, but exported, Registration API
///{
extern "C" {
@@ -39,10 +23,6 @@ void __llvmRegisterFunction(const char *Binary, const char *KernelID,
char *KernelName, const char *KernelName1, int,
uint3 *, uint3 *, dim3 *, dim3 *, int *);
-const char *__llvmRegisterFatBinary(const char *Binary);
-
-void __llvmUnregisterFatBinary(void *Handle);
-
void __llvmRegisterVar(void **, char *, char *, const char *, int, int, int,
int);
diff --git a/offload/languages/kernel/include/State.h b/offload/languages/kernel/include/State.h
index 12d1abafbf917..ffbf1e3ae3ced 100644
--- a/offload/languages/kernel/include/State.h
+++ b/offload/languages/kernel/include/State.h
@@ -34,9 +34,7 @@ namespace offload {
/// Opaque host-side key used to identify a registered kernel.
///
-/// This is the address emitted in the offload entry table for the kernel,
-/// not a device number or liboffload handle. The runtime maps it to the
-/// loaded device symbol during registration and uses it again during launch.
+/// This is the address emitted in the offload entry table for the kernel
using KernelIDTy = const void *;
/// Per-thread state used by the language runtime entry points.
@@ -46,12 +44,21 @@ using KernelIDTy = const void *;
struct ThreadStateTy {
~ThreadStateTy();
- /// Return the default queue for the current stream mode.
+ /// Return the default queue for the current host thread
static ol_queue_handle_t getDefaultQueue();
/// Return the thread-local default device, or the first discovered device.
static ol_device_handle_t getDefaultDevice();
+ /// Return the thread-local default device and write its number to \p
+ /// DeviceNo.
+ static ol_device_handle_t getDevice(int *DeviceNo);
+
+ /// Set the thread-local default device by device number.
+ ///
+ /// \returns the selected device, or nullptr if \p DeviceNo is invalid.
+ static ol_device_handle_t setDefaultDevice(int DeviceNo);
+
/// Return the pending kernel launch configuration for this thread.
static CallConfigurationTy &getCallConfiguration();
@@ -63,7 +70,7 @@ struct ThreadStateTy {
void createDefaultQueue(ol_device_handle_t Device);
- ol_device_handle_t DefaultDevice = nullptr;
+ int DefaultDevice = 0;
ol_queue_handle_t DefaultQueue = nullptr;
CallConfigurationTy CC = {};
@@ -86,14 +93,6 @@ struct StateTy {
/// Return the number of non-host devices available to kernel languages.
static int getDeviceCount();
- /// Return the thread-local default device and write its number to \p DeviceNo.
- static ol_device_handle_t getDevice(int *DeviceNo);
-
- /// Set the thread-local default device by device number.
- ///
- /// \returns the selected device, or nullptr if \p DeviceNo is invalid.
- static ol_device_handle_t setDefaultDevice(int DeviceNo);
-
/// Register \p Kernel for the host-side kernel identifier \p ID.
///
/// \p ID is the opaque kernel key emitted by Clang in the offload entry
diff --git a/offload/languages/kernel/src/LanguageLaunch.cpp b/offload/languages/kernel/src/LanguageLaunch.cpp
index 20779f89f969a..eff3d11668c17 100644
--- a/offload/languages/kernel/src/LanguageLaunch.cpp
+++ b/offload/languages/kernel/src/LanguageLaunch.cpp
@@ -9,6 +9,7 @@
#include "LanguageLaunch.h"
#include "State.h"
+#include <algorithm>
#include <cstdio>
using RuntimeState = llvm::offload::StateTy;
@@ -17,25 +18,25 @@ using ThreadState = llvm::offload::ThreadStateTy;
extern "C" {
/// Push call configuration for kernel launch
-unsigned __llvmPushCallConfiguration(dim3 __grid_size, dim3 __block_size,
- size_t __shared_memory, void *__stream) {
+unsigned __llvmPushCallConfiguration(dim3 GridSize, dim3 BlockSize,
+ size_t SharedMemory, void *Stream) {
CallConfigurationTy &CC = ThreadState::getCallConfiguration();
- CC.GridSize = __grid_size;
- CC.BlockSize = __block_size;
- CC.SharedMemory = __shared_memory;
- CC.Stream = __stream;
+ CC.GridSize = GridSize;
+ CC.BlockSize = BlockSize;
+ CC.SharedMemory = SharedMemory;
+ CC.Stream = Stream;
return 0;
}
/// Pop call configuration for kernel launch
-unsigned __llvmPopCallConfiguration(dim3 *__grid_size, dim3 *__block_size,
- size_t *__shared_memory, void **__stream) {
+unsigned __llvmPopCallConfiguration(dim3 *GridSize, dim3 *BlockSize,
+ size_t *SharedMemory, void **Stream) {
CallConfigurationTy &CC = ThreadState::getCallConfiguration();
- *__grid_size = CC.GridSize;
- *__block_size = CC.BlockSize;
- *__shared_memory = CC.SharedMemory;
- *__stream = CC.Stream;
+ *GridSize = CC.GridSize;
+ *BlockSize = CC.BlockSize;
+ *SharedMemory = CC.SharedMemory;
+ *Stream = CC.Stream;
return 0;
}
diff --git a/offload/languages/kernel/src/LanguageRegistration.cpp b/offload/languages/kernel/src/LanguageRegistration.cpp
index 231eaa691ff0b..2219e16ea0365 100644
--- a/offload/languages/kernel/src/LanguageRegistration.cpp
+++ b/offload/languages/kernel/src/LanguageRegistration.cpp
@@ -20,172 +20,6 @@
using RuntimeState = llvm::offload::StateTy;
using ThreadState = llvm::offload::ThreadStateTy;
-typedef struct __attribute__((__packed__)) {
- uint32_t Magic;
- uint16_t Version;
- uint16_t HeaderSize;
- uint64_t FatSize;
-} CudaFatbinHeader;
-
-// Inspired by
-// https://github.com/n-eiling/cuda-fatbin-decompression/blob/master/fatbin-decompress.h
-typedef struct __attribute__((__packed__)) {
- uint16_t Kind;
- uint16_t Unknown1;
- uint32_t HeaderSize;
- uint64_t Size;
- uint32_t CompressedSize;
- uint32_t Unknown2;
- uint16_t Minor;
- uint16_t Major;
- uint32_t Arch;
- uint32_t ObjNameOffset;
- uint32_t ObjNameLen;
- uint64_t Flags;
- uint64_t Zero;
- uint64_t DecompressedSize;
-} CudaFatbinTextHeader;
-
-// HIP uses this format:
-// https://clang.llvm.org/docs/ClangOffloadBundler.html#bundled-binary-file-layout
-typedef struct __attribute__((__packed__)) {
- char Magic[24];
- uint64_t NumBundles;
-} HipFatbinHeader;
-
-typedef struct __attribute__((__packed__)) {
- uint64_t BundleOffset;
- uint64_t BundleSize;
- uint64_t IdLength;
- char IdString[];
-} HipFatbinBundleEntry;
-
-static void readTUFatbin(const char *Binary, const FatbinWrapperTy *FW) {
- ol_device_handle_t Device = language_registration::getDefaultDevice();
-
- const CudaFatbinHeader *Header =
- reinterpret_cast<const CudaFatbinHeader *>(FW->Data);
- size_t HeaderSize = static_cast<size_t>(Header->HeaderSize); // Usually 16
- size_t FatbinSize = static_cast<size_t>(Header->FatSize);
-
- const void *ProgramData = nullptr;
- size_t ProgramSize = 0;
- uint32_t ProgramArch = 0;
-
- const char *ReadPosition = FW->Data + HeaderSize;
- while (ReadPosition < (FW->Data + FatbinSize)) {
- const CudaFatbinTextHeader *TextHeader =
- reinterpret_cast<const CudaFatbinTextHeader *>(ReadPosition);
- size_t TextHeaderSize =
- static_cast<size_t>(TextHeader->HeaderSize); // Usually 64
- size_t CubinSize = static_cast<size_t>(TextHeader->Size);
- const void *CubinData =
- static_cast<const char *>(ReadPosition + TextHeaderSize);
-
- uint32_t Arch = TextHeader->Arch;
- bool IsCompatible = false;
- olIsValidBinary(Device, CubinData, CubinSize, &IsCompatible);
- if (!IsCompatible) {
- fprintf(stderr, "Device is not compatible with image.");
- abort();
- }
-
- if (Arch > ProgramArch) {
- ProgramData = CubinData;
- ProgramSize = CubinSize;
- ProgramArch = Arch;
- }
-
- ReadPosition += TextHeaderSize + CubinSize;
- }
-
- if (ProgramData == nullptr) {
- fprintf(stderr, "Failed to find compatible binary\n");
- abort();
- }
-
- ol_program_handle_t Program = nullptr;
-
- ol_result_t Result =
- olCreateProgram(Device, ProgramData, ProgramSize, &Program);
-
- if (Result && Result->Code) {
- fprintf(stderr, "Failed to register device code (%i): %s\n", Result->Code,
- Result->Details);
- abort();
- }
-
- language_registration::registerProgram(Binary, Program);
-}
-
-static void readHIPFatbinEntries(const char *Binary, const char *HIPFatbinPtr) {
- ol_device_handle_t Device = language_registration::getDefaultDevice();
-
- const char *CurrentReadPosition = HIPFatbinPtr;
-
- const HipFatbinHeader *Header =
- reinterpret_cast<const HipFatbinHeader *>(CurrentReadPosition);
- CurrentReadPosition += sizeof(HipFatbinHeader);
-
- uint64_t NumBundles = Header->NumBundles;
-
- const void *ProgramData = nullptr;
- size_t ProgramSize = 0;
- uint64_t ProgramIdLength = 0;
- const char *ProgramIdString = nullptr;
-
- for (uint64_t BundleId = 0; BundleId < NumBundles; ++BundleId) {
- const HipFatbinBundleEntry *BundleEntry =
- reinterpret_cast<const HipFatbinBundleEntry *>(CurrentReadPosition);
-
- uint64_t BundleOffset = BundleEntry->BundleOffset;
- uint64_t BundleSize = BundleEntry->BundleSize;
- const char *BundleIdString = BundleEntry->IdString;
- uint64_t BundleIdLength = BundleEntry->IdLength;
-
- // Advance by the size of the entry including the ID string
- CurrentReadPosition += sizeof(HipFatbinBundleEntry) + BundleIdLength;
-
- if (!BundleSize) {
- continue;
- }
-
- bool IsCompatible = false;
- olIsValidBinary(Device, HIPFatbinPtr + BundleOffset, BundleSize,
- &IsCompatible);
-
- if (!IsCompatible) {
- fprintf(stderr, "Device is not compatible with image.");
- abort();
- }
-
- llvm::StringRef CurrentBundleId(ProgramIdString, ProgramIdLength);
- llvm::StringRef NewBundleId(BundleIdString, BundleIdLength);
- if (NewBundleId.compare(CurrentBundleId) > 0) {
- ProgramData = HIPFatbinPtr + BundleOffset;
- ProgramSize = BundleSize;
- ProgramIdLength = BundleIdLength;
- ProgramIdString = BundleIdString;
- }
- }
-
- if (ProgramData == nullptr) {
- fprintf(stderr, "Failed to find compatible binary\n");
- abort();
- }
-
- ol_program_handle_t Program = nullptr;
- ol_result_t Result =
- olCreateProgram(Device, ProgramData, ProgramSize, &Program);
- if (Result && Result->Code) {
- fprintf(stderr, "Failed to register device code (%i): %s\n", Result->Code,
- Result->Details);
- abort();
- }
-
- language_registration::registerProgram(Binary, Program);
-}
-
/// Hidden, but exported, Registration API
///{
extern "C" {
@@ -197,37 +31,10 @@ void __llvmRegisterFunction(const char *Binary, const char *KernelID,
ol_program_handle_t Program = RuntimeState::getProgram(Binary);
ol_result_t Result = olGetSymbol(
Program, KernelName, ol_symbol_kind_t::OL_SYMBOL_KIND_KERNEL, &Kernel);
- if (Result && Result->Code) {
- fprintf(stderr, "Failed to register kernel (%i): %s\n", Result->Code,
- Result->Details);
- abort();
- }
-
+ CHECK_FATAL(Result, "Failed to get kernel symbol for " << KernelName);
RuntimeState::registerKernel(KernelID, Kernel);
}
-const char *__llvmRegisterFatBinary(const char *Binary) {
- const auto *FW = reinterpret_cast<const FatbinWrapperTy *>(Binary);
- if (FW->Magic == 0x466243b1) {
- readTUFatbin(Binary, FW);
- } else if (FW->Magic == 0x48495046) {
- if (!memcmp(FW->Data, HIP_FATBIN_MAGIC_STR, HIP_FATBIN_MAGIC_STR_LEN))
- readHIPFatbinEntries(Binary, FW->Data);
- else
- readTUFatbin(Binary, FW);
- } else {
- fprintf(stderr, "Unknown fatbin format");
- }
-
- return Binary;
-}
-
-void __llvmUnregisterFatBinary(void *Handle) {
- if (ol_program_handle_t Program =
- language_registration::unregisterProgram(Handle))
- olDestroyProgram(Program);
-}
-
void __llvmRegisterVar(void **, char *, char *, const char *, int, int, int,
int) {
llvm::errs() << "RegisterVar is not implemented!" << "\n";
diff --git a/offload/languages/kernel/src/LanguageRuntime.cpp b/offload/languages/kernel/src/LanguageRuntime.cpp
index 0859a7955dbe7..f570fb9626b49 100644
--- a/offload/languages/kernel/src/LanguageRuntime.cpp
+++ b/offload/languages/kernel/src/LanguageRuntime.cpp
@@ -11,8 +11,10 @@
#endif
// Rename the generic runtime API before declaring or defining language symbols.
+// clang-format off
#include "DefineLanguageNames.inc"
#include "LanguageRuntime.h"
+// clang-format on
#include "State.h"
#include "Types.h"
@@ -101,7 +103,7 @@ Error_t DeviceSynchronize() {
}
Error_t GetDevice(int *DeviceNo) {
- ol_device_handle_t Device = RuntimeState::getDevice(DeviceNo);
+ ol_device_handle_t Device = ThreadState::getDevice(DeviceNo);
if (!Device)
return ErrorInvalidValue;
return Success;
@@ -113,7 +115,7 @@ Error_t GetDeviceCount(int *Count) {
}
Error_t SetDevice(int DeviceNo) {
- ol_device_handle_t Device = RuntimeState::setDefaultDevice(DeviceNo);
+ ol_device_handle_t Device = ThreadState::setDefaultDevice(DeviceNo);
if (!Device)
return ErrorInvalidValue;
assert(Device == ThreadState::getDefaultDevice() &&
diff --git a/offload/languages/kernel/src/State.cpp b/offload/languages/kernel/src/State.cpp
index 3dbd1f436ff24..f135360eb1442 100644
--- a/offload/languages/kernel/src/State.cpp
+++ b/offload/languages/kernel/src/State.cpp
@@ -14,27 +14,18 @@
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
-#include "llvm/Support/raw_ostream.h"
#include <atomic>
#include <cassert>
#include <cstdio>
#include <mutex>
-#define CHECK_FATAL(Result, ...) \
- if (Result && Result->Code) { \
- llvm::errs() << __VA_ARGS__ << '\n'; \
- abort(); \
- }
-
using namespace llvm;
using namespace offload;
// Weak so another runtime object can override the default stream mode.
__attribute__((weak)) uint32_t PerThreadQueue = 0;
-thread_local CallConfigurationTy CC = {};
-
// Process-wide singleton and thread-state registry.
static std::mutex StateLock;
static std::atomic<StateTy *> StatePtr = nullptr;
@@ -45,7 +36,9 @@ static std::mutex ThreadStatesLock;
using ThreadStatesTy = SmallVector<ThreadStateTy *, 64>;
static ThreadStatesTy *ThreadStatesPtr = nullptr;
-static void deleteThreadState() {
+static void deleteThreadStates() {
+ // Detach the registry before deletion because deleteThreadState may be called
+ // more than once via atexit and StateTy teardown.
std::lock_guard<std::mutex> LG(ThreadStatesLock);
ThreadStatesTy *ThreadStates = ThreadStatesPtr;
ThreadStatesPtr = nullptr;
@@ -56,12 +49,14 @@ static void deleteThreadState() {
delete TS;
delete ThreadStates;
ThreadState = nullptr;
+ ThreadStates = nullptr;
}
static void deleteState() {
StateTy *ST = StatePtr.load();
StatePtr.store(nullptr);
delete ST;
+ StatePtr = nullptr;
}
static void destroyQueue(ol_queue_handle_t &Queue) {
@@ -81,15 +76,14 @@ namespace offload {
ThreadStateTy::ThreadStateTy() {
if (PerThreadQueue) [[unlikely]]
createDefaultQueue(getDefaultDevice());
- atexit(deleteThreadState);
+ atexit(deleteThreadStates);
}
ThreadStateTy::~ThreadStateTy() { destroyQueue(DefaultQueue); }
ThreadStateTy &ThreadStateTy::get() {
- auto *TS = ThreadState;
+ auto *&TS = ThreadState;
if (!TS) {
TS = new ThreadStateTy();
- ThreadState = TS;
std::lock_guard<std::mutex> LG(ThreadStatesLock);
if (!ThreadStatesPtr)
ThreadStatesPtr = new ThreadStatesTy;
@@ -99,14 +93,8 @@ ThreadStateTy &ThreadStateTy::get() {
}
ol_device_handle_t ThreadStateTy::getDefaultDevice() {
- ol_device_handle_t DD = ThreadStateTy::get().DefaultDevice;
- if (DD)
- return DD;
- for (ol_device_handle_t Device : StateTy::get().getDevices()) {
- DD = Device;
- break;
- }
- return DD;
+ int DD = ThreadStateTy::get().DefaultDevice;
+ return StateTy::get().getDevices()[DD];
}
ol_queue_handle_t ThreadStateTy::getDefaultQueue() {
@@ -119,10 +107,19 @@ CallConfigurationTy &ThreadStateTy::getCallConfiguration() {
return ThreadStateTy::get().CC;
}
-void ThreadStateTy::setDefaultDevice(ol_device_handle_t Device) {
- ThreadStateTy &State = get();
- State.DefaultDevice = Device;
- State.createDefaultQueue(Device);
+ol_device_handle_t ThreadStateTy::setDefaultDevice(int DeviceNo) {
+ ArrayRef<ol_device_handle_t> Devices = StateTy::get().getDevices();
+ if (DeviceNo < 0 || DeviceNo >= static_cast<int>(Devices.size()))
+ return nullptr;
+ ThreadStateTy::get().DefaultDevice = DeviceNo;
+ ol_device_handle_t DD = Devices[DeviceNo];
+ ThreadStateTy::get().createDefaultQueue(DD);
+ return DD;
+}
+
+ol_device_handle_t ThreadStateTy::getDevice(int *DeviceNo) {
+ *DeviceNo = ThreadStateTy::get().DefaultDevice;
+ return ThreadStateTy::getDefaultDevice();
}
void ThreadStateTy::createDefaultQueue(ol_device_handle_t Device) {
@@ -156,28 +153,6 @@ int StateTy::getDeviceCount() {
return DeviceCount;
}
-ol_device_handle_t StateTy::getDevice(int *DeviceNo) {
- ol_device_handle_t DefaultDevice = ThreadStateTy::getDefaultDevice();
- int DeviceCount = get().getDevices().size();
- ArrayRef<ol_device_handle_t> Devices = get().getDevices();
- for (int i = 0; i < DeviceCount; i++) {
- if (Devices[i] == DefaultDevice) {
- *DeviceNo = i;
- return Devices[i];
- }
- }
- return nullptr;
-}
-
-ol_device_handle_t StateTy::setDefaultDevice(int DeviceNo) {
- ArrayRef<ol_device_handle_t> Devices = get().getDevices();
- if (DeviceNo < 0 || DeviceNo >= static_cast<int>(Devices.size()))
- return nullptr;
- ol_device_handle_t Device = Devices[DeviceNo];
- ThreadStateTy::setDefaultDevice(Device);
- return Device;
-}
-
ArrayRef<ol_device_handle_t> StateTy::getDevices() const { return Devices; }
void StateTy::addDevice(ol_device_handle_t Device) {
@@ -282,7 +257,7 @@ StateTy::StateTy() {
}
StateTy::~StateTy() {
- deleteThreadState();
+ deleteThreadStates();
destroyQueue(DefaultQueue);
destroyRegisteredPrograms();
olShutDown();
More information about the llvm-commits
mailing list