[llvm] [Offload][omp] Add own Error class to libomptarget (PR #229711)

Alex Duran via llvm-commits llvm-commits at lists.llvm.org
Wed Oct 7 02:42:35 PDT 2026


https://github.com/adurang created https://github.com/llvm/llvm-project/pull/229711

Add a new class for Errors generated within libomptarget to break the dependence with the Error class defined inside the plugins.

Assisted by Claude.

>From 5c327b6b998a3d506a38df0a158c944e4d6d95b3 Mon Sep 17 00:00:00 2001
From: "Duran, Alex" <alejandro.duran at intel.com>
Date: Wed, 7 Oct 2026 02:09:51 -0700
Subject: [PATCH] [Offload][omp] Add own Error class to libomptarget

Add a new class for Errors generated within libomptarget to break the dependence with the Error class defined inside the plugins.

Assisted by Claude.
---
 offload/include/OmpAccError.h              | 65 ++++++++++++++++++++++
 offload/include/PluginManager.h            |  7 ++-
 offload/liboffload/src/OffloadImpl.cpp     |  2 +-
 offload/libompaccsupport/OmpAccError.cpp   | 43 ++++++++++++++
 offload/libompaccsupport/PluginManager.cpp | 11 ++--
 offload/libompaccsupport/device.cpp        | 54 +++++++++---------
 offload/libomptarget/CMakeLists.txt        |  1 +
 7 files changed, 146 insertions(+), 37 deletions(-)
 create mode 100644 offload/include/OmpAccError.h
 create mode 100644 offload/libompaccsupport/OmpAccError.cpp

diff --git a/offload/include/OmpAccError.h b/offload/include/OmpAccError.h
new file mode 100644
index 00000000000000..f6b0c713f626db
--- /dev/null
+++ b/offload/include/OmpAccError.h
@@ -0,0 +1,65 @@
+//===- OmpAccError.h - Error class for the OpenMP offload RTL -------===//
+//
+// 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 OMPTARGET_OMPACCERROR_H
+#define OMPTARGET_OMPACCERROR_H
+
+#include "llvm/Support/Error.h"
+#include "llvm/Support/raw_ostream.h"
+
+namespace llvm::omp::target::error {
+
+enum class ErrorCode {
+  Unknown,
+  InvalidBinary,
+  InvalidValue,
+  BackendFailure,
+};
+
+} // namespace llvm::omp::target::error
+
+namespace std {
+template <>
+struct is_error_code_enum<llvm::omp::target::error::ErrorCode>
+    : std::true_type {};
+} // namespace std
+
+namespace llvm::omp::target::error {
+
+const std::error_category &OmpAccErrCategory();
+
+inline std::error_code make_error_code(ErrorCode E) {
+  return std::error_code(static_cast<int>(E), OmpAccErrCategory());
+}
+
+/// Error class used by the OpenMP offload runtime (libomptarget).
+class OmpAccError : public llvm::ErrorInfo<OmpAccError, llvm::StringError> {
+public:
+  using ErrorInfo<OmpAccError, StringError>::ErrorInfo;
+
+  OmpAccError(const llvm::Twine &S) : ErrorInfo(S, ErrorCode::Unknown) {}
+
+  static char ID;
+};
+
+/// Create an offload runtime error.
+template <typename... ArgsTy>
+[[maybe_unused]] static llvm::Error
+createError(ErrorCode Code, const char *ErrFmt, ArgsTy... Args) {
+  std::string Buffer;
+  llvm::raw_string_ostream(Buffer) << llvm::format(ErrFmt, Args...);
+  return llvm::make_error<OmpAccError>(Code, Buffer);
+}
+
+inline llvm::Error createError(ErrorCode Code, const char *S) {
+  return llvm::make_error<OmpAccError>(Code, S);
+}
+
+} // namespace llvm::omp::target::error
+
+#endif
diff --git a/offload/include/PluginManager.h b/offload/include/PluginManager.h
index e2e0638cc39cc5..1d2a9580eed4ab 100644
--- a/offload/include/PluginManager.h
+++ b/offload/include/PluginManager.h
@@ -18,6 +18,7 @@
 
 #include "DeviceImage.h"
 #include "ExclusiveAccess.h"
+#include "OmpAccError.h"
 #include "Shared/APITypes.h"
 #include "Shared/Requirements.h"
 
@@ -208,9 +209,9 @@ template <typename CallbackTy> llvm::Error iterateDevices(CallbackTy Callback) {
     return true;
   };
   if (auto Res = olIterateDevices(Wrapper, &Callback))
-    return error::createOffloadError(error::ErrorCode::BACKEND_FAILURE,
-                                     "Failed to iterate devices: %d",
-                                     Res->Details);
+    return llvm::omp::target::error::createError(
+        llvm::omp::target::error::ErrorCode::BackendFailure,
+        "Failed to iterate devices: %s", Res->Details);
   return llvm::Error::success();
 }
 #endif // OMPTARGET_PLUGIN_MANAGER_H
diff --git a/offload/liboffload/src/OffloadImpl.cpp b/offload/liboffload/src/OffloadImpl.cpp
index cff0b533075793..057c300dcccf52 100644
--- a/offload/liboffload/src/OffloadImpl.cpp
+++ b/offload/liboffload/src/OffloadImpl.cpp
@@ -14,7 +14,7 @@
 #include "OffloadImpl.hpp"
 #include "Helpers.hpp"
 #include "OffloadPrint.hpp"
-#include "PluginManager.h"
+#include "llvm/ADT/SmallSet.h"
 #include "llvm/Support/FormatVariadic.h"
 #include <OffloadAPI.h>
 
diff --git a/offload/libompaccsupport/OmpAccError.cpp b/offload/libompaccsupport/OmpAccError.cpp
new file mode 100644
index 00000000000000..63e4993b2171db
--- /dev/null
+++ b/offload/libompaccsupport/OmpAccError.cpp
@@ -0,0 +1,43 @@
+//===- OmpAccError.cpp - Error class for the OpenMP offload RTL -----===//
+//
+// 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 "OmpAccError.h"
+#include "llvm/Support/ErrorHandling.h"
+
+using namespace llvm;
+using namespace llvm::omp::target::error;
+
+namespace {
+// OmpAccError inherits from llvm::StringError which requires a
+// std::error_code. Once/if that requirement is removed, then this
+// std::error_code machinery can be removed.
+class OmpAccErrorCategory : public std::error_category {
+public:
+  const char *name() const noexcept override { return "llvm.omptarget"; }
+  std::string message(int Condition) const override {
+    switch (static_cast<ErrorCode>(Condition)) {
+    case ErrorCode::Unknown:
+      return "unknown error";
+    case ErrorCode::InvalidBinary:
+      return "invalid binary";
+    case ErrorCode::InvalidValue:
+      return "invalid value";
+    case ErrorCode::BackendFailure:
+      return "backend failure";
+    }
+    llvm_unreachable("Unrecognized offload RTL ErrorCode");
+  }
+};
+} // namespace
+
+const std::error_category &llvm::omp::target::error::OmpAccErrCategory() {
+  static OmpAccErrorCategory Category;
+  return Category;
+}
+
+char OmpAccError::ID;
diff --git a/offload/libompaccsupport/PluginManager.cpp b/offload/libompaccsupport/PluginManager.cpp
index 9a3c9070ae6f04..a0147e1557027a 100644
--- a/offload/libompaccsupport/PluginManager.cpp
+++ b/offload/libompaccsupport/PluginManager.cpp
@@ -12,6 +12,7 @@
 
 #include "PluginManager.h"
 #include "OffloadPolicy.h"
+#include "OmpAccError.h"
 #include "OpenMP/OMPT/Interface.h"
 #include "Shared/Debug.h"
 #include "Shared/Environment.h"
@@ -31,6 +32,7 @@ using namespace llvm::omp::target::ompt;
 
 using namespace llvm;
 using namespace llvm::sys;
+using namespace llvm::omp::target::error;
 using namespace llvm::omp::target::debug;
 
 PluginManager *PM = nullptr;
@@ -631,8 +633,8 @@ Expected<DeviceTy &> PluginManager::getDevice(uint32_t DeviceNo) {
   {
     auto ExclusiveDevicesAccessor = getExclusiveDevicesAccessor();
     if (DeviceNo >= ExclusiveDevicesAccessor->size())
-      return error::createOffloadError(
-          error::ErrorCode::INVALID_VALUE,
+      return createError(
+          ErrorCode::InvalidValue,
           "device number '%i' out of range, only %i devices available",
           DeviceNo, ExclusiveDevicesAccessor->size());
 
@@ -642,8 +644,7 @@ Expected<DeviceTy &> PluginManager::getDevice(uint32_t DeviceNo) {
   // Check whether global data has been mapped for this device
   if (DevicePtr->hasPendingImages())
     if (loadImagesOntoDevice(*DevicePtr) != OFFLOAD_SUCCESS)
-      return error::createOffloadError(error::ErrorCode::BACKEND_FAILURE,
-                                       "failed to load images on device '%i'",
-                                       DeviceNo);
+      return createError(ErrorCode::BackendFailure,
+                         "failed to load images on device '%i'", DeviceNo);
   return *DevicePtr;
 }
diff --git a/offload/libompaccsupport/device.cpp b/offload/libompaccsupport/device.cpp
index af30aa757a15a2..b22f11531c0753 100644
--- a/offload/libompaccsupport/device.cpp
+++ b/offload/libompaccsupport/device.cpp
@@ -12,6 +12,7 @@
 
 #include "device.h"
 #include "OffloadEntry.h"
+#include "OmpAccError.h"
 #include "OpenMP/Mapping.h"
 #include "OpenMP/OMPT/Callback.h"
 #include "OpenMP/OMPT/Interface.h"
@@ -40,6 +41,7 @@
 using namespace llvm::omp::target::ompt;
 #endif
 
+using namespace llvm::omp::target::error;
 using namespace llvm::omp::target::plugin;
 using namespace llvm::omp::target::debug;
 
@@ -116,9 +118,8 @@ llvm::Error DeviceTy::init() {
         OMPX_RecordReportFilename.get().c_str(),
         OMPX_RecordOutputDir.get().c_str());
     if (Ret != OFFLOAD_SUCCESS)
-      return error::createOffloadError(error::ErrorCode::BACKEND_FAILURE,
-                                       "failed to initialize RR in device %d\n",
-                                       DeviceID);
+      return createError(ErrorCode::BackendFailure,
+                         "failed to initialize RR in device %d\n", DeviceID);
   }
 
   return llvm::Error::success();
@@ -151,17 +152,17 @@ setupIndirectCallTable(DeviceTy &Device, __tgt_device_image *Image,
       void *Vtable;
       void *res;
       if (Device.RTL->get_global(Binary, PtrSize, Entry.SymbolName, &Vtable))
-        return error::createOffloadError(error::ErrorCode::INVALID_BINARY,
-                                         "failed to load %s", Entry.SymbolName);
+        return createError(ErrorCode::InvalidBinary, "failed to load %s",
+                           Entry.SymbolName);
 
       // HstPtr = Entry.Address;
       if (Device.retrieveData(&res, Vtable, PtrSize, AsyncInfo))
-        return error::createOffloadError(error::ErrorCode::INVALID_BINARY,
-                                         "failed to load %s", Entry.SymbolName);
+        return createError(ErrorCode::InvalidBinary, "failed to load %s",
+                           Entry.SymbolName);
       if (Device.synchronize(AsyncInfo))
-        return error::createOffloadError(
-            error::ErrorCode::INVALID_BINARY,
-            "failed to synchronize after retrieving %s", Entry.SymbolName);
+        return createError(ErrorCode::InvalidBinary,
+                           "failed to synchronize after retrieving %s",
+                           Entry.SymbolName);
       // Calculate and emplace entire Vtable from first Vtable byte
       for (uint64_t i = 0; i < Entry.Size / PtrSize; ++i) {
         auto &[HstPtr, DevPtr] = IndirectCallTable.emplace_back();
@@ -177,18 +178,18 @@ setupIndirectCallTable(DeviceTy &Device, __tgt_device_image *Image,
       auto &[HstPtr, DevPtr] = IndirectCallTable.emplace_back();
       void *Ptr;
       if (Device.RTL->get_global(Binary, Entry.Size, Entry.SymbolName, &Ptr))
-        return error::createOffloadError(error::ErrorCode::INVALID_BINARY,
-                                         "failed to load %s", Entry.SymbolName);
+        return createError(ErrorCode::InvalidBinary, "failed to load %s",
+                           Entry.SymbolName);
 
       HstPtr = Entry.Address;
       if (Device.retrieveData(&DevPtr, Ptr, Entry.Size, AsyncInfo))
-        return error::createOffloadError(error::ErrorCode::INVALID_BINARY,
-                                         "failed to load %s", Entry.SymbolName);
+        return createError(ErrorCode::InvalidBinary, "failed to load %s",
+                           Entry.SymbolName);
     }
     if (Device.synchronize(AsyncInfo))
-      return error::createOffloadError(
-          error::ErrorCode::INVALID_BINARY,
-          "failed to synchronize after retrieving %s", Entry.SymbolName);
+      return createError(ErrorCode::InvalidBinary,
+                         "failed to synchronize after retrieving %s",
+                         Entry.SymbolName);
   }
 
   // If we do not have any indirect globals we exit early.
@@ -204,14 +205,12 @@ setupIndirectCallTable(DeviceTy &Device, __tgt_device_image *Image,
   void *DevicePtr = Device.allocData(TableSize, nullptr, TARGET_ALLOC_DEVICE);
   if (Device.submitData(DevicePtr, IndirectCallTable.data(), TableSize,
                         AsyncInfo))
-    return error::createOffloadError(error::ErrorCode::INVALID_BINARY,
-                                     "failed to copy data");
+    return createError(ErrorCode::InvalidBinary, "failed to copy data");
   // The IndirectCallTable is on the stack, so we must synchronize to ensure
   // the data is copied before we return.
   if (Device.synchronize(AsyncInfo))
-    return error::createOffloadError(
-        error::ErrorCode::INVALID_BINARY,
-        "failed to synchronize after copying data");
+    return createError(ErrorCode::InvalidBinary,
+                       "failed to synchronize after copying data");
 
   return std::pair<void *, uint64_t>(DevicePtr, IndirectCallTable.size());
 }
@@ -222,8 +221,8 @@ DeviceTy::loadBinary(__tgt_device_image *Img) {
   __tgt_device_binary Binary;
 
   if (RTL->load_binary(RTLDeviceID, Img, &Binary) != OFFLOAD_SUCCESS)
-    return error::createOffloadError(error::ErrorCode::INVALID_BINARY,
-                                     "failed to load binary %p", Img);
+    return createError(ErrorCode::InvalidBinary, "failed to load binary %p",
+                       Img);
 
   OMPT_IF_BUILT_AND_INITIALIZED(performOmptCallback(
       device_load, DeviceID, /*FileName=*/nullptr, /*FileOffset=*/0,
@@ -261,8 +260,7 @@ DeviceTy::loadBinary(__tgt_device_image *Img) {
   AsyncInfoTy AsyncInfo(*this);
   if (submitData(DeviceEnvironmentPtr, &DeviceEnvironment,
                  sizeof(DeviceEnvironment), AsyncInfo))
-    return error::createOffloadError(error::ErrorCode::INVALID_BINARY,
-                                     "failed to copy data");
+    return createError(ErrorCode::InvalidBinary, "failed to copy data");
 
   return Binary;
 }
@@ -487,8 +485,8 @@ static llvm::Expected<KernelLaunchEnvironmentTy *> getKernelLaunchEnvironment(
 
   const bool NeedsReductionBuffer = KernelEnv.ReductionDataSize != 0;
   if (NeedsReductionBuffer && LaunchArgs.OmpABIVersion < OMP_KERNEL_ARG_VERSION)
-    return error::createOffloadError(
-        error::ErrorCode::INVALID_BINARY,
+    return createError(
+        ErrorCode::InvalidBinary,
         "kernel was built against an older OpenMP kernel-launch-environment "
         "ABI (v%u); current runtime requires v%u for cross-team reductions",
         LaunchArgs.OmpABIVersion, OMP_KERNEL_ARG_VERSION);
diff --git a/offload/libomptarget/CMakeLists.txt b/offload/libomptarget/CMakeLists.txt
index 21cc5a41e0be6c..72401dbfba619d 100644
--- a/offload/libomptarget/CMakeLists.txt
+++ b/offload/libomptarget/CMakeLists.txt
@@ -19,6 +19,7 @@ add_library(omptarget SHARED
   ../libompaccsupport/PluginManager.cpp
   ../libompaccsupport/DeviceImage.cpp
   ../libompaccsupport/Mapping.cpp
+  ../libompaccsupport/OmpAccError.cpp
 
   KernelLanguage/API.cpp
 )



More information about the llvm-commits mailing list