https://github.com/adurang updated 
https://github.com/llvm/llvm-project/pull/238764

>From df8e0c88ce1601c3548954dcb775e835ac1bdbd3 Mon Sep 17 00:00:00 2001
From: "Duran, Alex" <[email protected]>
Date: Mon, 19 Oct 2026 22:14:52 -0700
Subject: [PATCH] [Offload][Omp] Split plugin diagnostics into detection &
 messaging

The plugin interface tracks a allocations and kernels (when 
TrackAllocationTraces
and TrackNumKernelLaunches are enabled) to emit diagnostic messages.

These messages currently contain OpenMP specific data that needs to be carried
through the Plugin Interface.

This PR splits this support in two pieces: tracking and detection that is
kept inside the plugins, and reporting of the error which is done through
a handler set from libomptarget.

A new diagnostic handler type is added, and the API to associate it to a device
are added to liboffload.

This will allow to handle the OpenMP specific data fromb the libomptarget 
handler
and remove it from the Plugin Interface (not done in this PR).
---
 offload/include/DiagnosticPrinter.h           |  23 +
 offload/liboffload/API/Device.td              |  15 +
 offload/liboffload/API/Diagnostic.td          | 127 +++++
 offload/liboffload/API/OffloadAPI.td          |   1 +
 offload/liboffload/src/OffloadImpl.cpp        |   6 +
 offload/libompaccsupport/CMakeLists.txt       |   1 +
 .../libompaccsupport/DiagnosticPrinter.cpp    | 341 ++++++++++++
 offload/libompaccsupport/device.cpp           |   6 +
 offload/plugins-nextgen/amdgpu/src/rtl.cpp    |   4 +-
 offload/plugins-nextgen/common/CMakeLists.txt |   1 +
 .../common/include/ErrorReporting.h           | 493 ++++++++----------
 .../common/include/PluginInterface.h          |  17 +-
 .../common/src/ErrorReporting.cpp             |  64 +++
 .../common/src/PluginInterface.cpp            |  39 +-
 offload/tools/offload-tblgen/PrintGen.cpp     |   3 +
 offload/tools/offload-tblgen/RecordTypes.hpp  |   1 +
 16 files changed, 858 insertions(+), 284 deletions(-)
 create mode 100644 offload/include/DiagnosticPrinter.h
 create mode 100644 offload/liboffload/API/Diagnostic.td
 create mode 100644 offload/libompaccsupport/DiagnosticPrinter.cpp
 create mode 100644 offload/plugins-nextgen/common/src/ErrorReporting.cpp

diff --git a/offload/include/DiagnosticPrinter.h 
b/offload/include/DiagnosticPrinter.h
new file mode 100644
index 00000000000000..967bc56bfcda88
--- /dev/null
+++ b/offload/include/DiagnosticPrinter.h
@@ -0,0 +1,23 @@
+//===-------- DiagnosticPrinter.h --------------------------------- C++ 
-*-===//
+//
+// 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_DIAGNOSTIC_PRINTER_H
+#define OMPTARGET_DIAGNOSTIC_PRINTER_H
+
+#include "OffloadAPI.h"
+
+namespace llvm::omp::target {
+
+/// Return the handler that prints the diagnostic error messages.
+const ol_diagnostic_handler_t *getDiagnosticPrinter();
+
+} // namespace llvm::omp::target
+
+#endif // OMPTARGET_DIAGNOSTIC_PRINTER_H
diff --git a/offload/liboffload/API/Device.td b/offload/liboffload/API/Device.td
index c82151a6068863..a1a171973d90e6 100644
--- a/offload/liboffload/API/Device.td
+++ b/offload/liboffload/API/Device.td
@@ -165,6 +165,21 @@ def olGetDeviceInfo : Function {
   ];
 }
 
+def olSetDeviceDiagnosticHandler : Function {
+  let desc = "Sets the handler used to report problems detected on the 
device.";
+  let details = [
+    "Problems detected on a device without a handler get minimal built-in 
reporting.",
+    "The handler is not copied: it must stay valid for as long as it is set on 
the device. Passing `NULL` removes the handler."
+  ];
+  let params = [
+    Param<"ol_device_handle_t", "Device", "handle of the device instance", 
PARAM_IN>,
+    Param<"const ol_diagnostic_handler_t*", "Handler", "the handler to use, or 
NULL to remove it", PARAM_IN_OPTIONAL>
+  ];
+  let returns = [
+    Return<"OL_ERRC_INVALID_DEVICE">
+  ];
+}
+
 def olGetDeviceInfoSize : Function {
   let desc = "Returns the storage size of the given device query.";
   let details = [];
diff --git a/offload/liboffload/API/Diagnostic.td 
b/offload/liboffload/API/Diagnostic.td
new file mode 100644
index 00000000000000..1e14be759e15e1
--- /dev/null
+++ b/offload/liboffload/API/Diagnostic.td
@@ -0,0 +1,127 @@
+//===-- Diagnostic.td - Diagnostic definitions for Offload -*- tablegen 
-*-===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+//
+// Diagnostics reporting is split into two halves:
+//
+//  - Detection lives in the plugins. It notices the problem, triages it, and
+//    gathers everything worth reporting into a self-contained diagnostic. It
+//    also judges whether the problem is fatal, which the handler can override.
+//
+//  - Messaging turns a diagnostic into user-visible text. It is configurable 
by
+//    the users of the library, which set a handler on each device.
+//
+//===----------------------------------------------------------------------===//
+
+def ol_diagnostic_kind_t : Enum {
+  let desc = "The kind of problem that was detected";
+  let etors = [
+    Etor<"DEALLOCATION_OF_NON_ALLOCATED_PTR", "Deallocation of a pointer that 
was never allocated">,
+    Etor<"DOUBLE_FREE", "Deallocation of a pointer that was already 
deallocated">,
+    Etor<"DEALLOCATION_OF_WRONG_PTR_KIND", "Deallocation with a different 
allocation kind than the allocation used">,
+    Etor<"MEMORY_ACCESS_FAULT", "The device faulted accessing memory">,
+    Etor<"TRAP_IN_KERNEL", "A kernel executed a trap instruction">,
+  ];
+}
+
+def ol_pointer_relation_t : Enum {
+  let desc = "Where a device pointer sits with respect to the known 
allocations";
+  let etors = [
+    Etor<"NO_ALLOCATIONS", "No host-issued allocation is known at all">,
+    Etor<"INSIDE", "The pointer points into a live allocation">,
+    Etor<"INSIDE_PRIOR", "The pointer points into an allocation that was 
freed">,
+    Etor<"NEAR", "The pointer is outside of, but close to, a known 
allocation">,
+    Etor<"FAR", "The pointer is far away from any known allocation">,
+  ];
+}
+
+def ol_allocation_info_t : Struct {
+  let desc = "Information about a tracked allocation, and about the allocation 
history at the same base pointer";
+  let members = [
+    StructMember<"const char*", "AllocationTrace", "The stack trace of the 
allocation itself. Never null, possibly empty">,
+    StructMember<"const char*", "DeallocationTrace", "The stack trace of the 
deallocation. Never null, empty if still live">,
+    StructMember<"void*", "DevicePtr", "The allocated device pointer">,
+    StructMember<"void*", "HostPtr", "The corresponding host pointer, or 
null">,
+    StructMember<"uint64_t", "Size", "The size of the allocation">,
+    StructMember<"const struct ol_allocation_info_t*", "Prior", "Prior 
allocations at the same base pointer, most recent first. Null when NumPrior is 
zero">,
+    StructMember<"size_t", "NumPrior", "The number of entries in Prior">,
+  ];
+}
+
+def ol_kernel_launch_info_t : Struct {
+  let desc = "Information about a tracked kernel launch";
+  let members = [
+    StructMember<"const char*", "Name", "The symbol name of the kernel, not 
prettified. Never null">,
+    StructMember<"const char*", "LaunchTrace", "The stack trace of the launch. 
Never null, empty if it was not tracked">,
+    StructMember<"int", "IsCulprit", "Non-zero if this launch was identified 
as the one that caused the problem">,
+  ];
+}
+
+def ol_pointer_info_t : Struct {
+  let desc = "Information about the device pointer a diagnostic is about";
+  let members = [
+    StructMember<"void*", "DevicePtr", "The device pointer in question">,
+    StructMember<"ol_pointer_relation_t", "Relation", "How DevicePtr relates 
to the known allocations">,
+    StructMember<"uintptr_t", "Distance", "The distance to Allocation in 
bytes, meaningful for OL_POINTER_RELATION_NEAR">,
+    StructMember<"const struct ol_allocation_info_t*", "Allocation", "The 
allocation Relation refers to, or null if there is none">,
+  ];
+}
+
+def ol_diagnostic_hints_t : Struct {
+  let desc = "What is being tracked, so that a handler can suggest how to get 
more information without knowing about environment variables";
+  let members = [
+    StructMember<"int", "AllocationTracesEnabled", "Non-zero if allocation 
stack traces are being tracked">,
+    StructMember<"const char*", "AllocationTracesEnvar", "The name of the 
environment variable controlling the above">,
+    StructMember<"const char*", "KernelLaunchesEnvar", "The name of the 
environment variable controlling how many kernel launch traces are tracked">,
+    StructMember<"int", "KernelLaunchesKnown", "Non-zero if information about 
kernel launches was available at all. If zero, no kernel launches should be 
reported, not even their absence">,
+    StructMember<"uint32_t", "KernelLaunchesRequested", "The number of kernel 
launch traces that were requested">,
+    StructMember<"uint32_t", "KernelLaunchesAvailable", "The number of kernel 
launches known">,
+    StructMember<"uint64_t", "KernelLaunchesCapacity", "The maximal number of 
kernel launches that can be known">,
+  ];
+}
+
+def ol_diagnostic_t : Struct {
+  let desc = "A self-contained description of a detected problem";
+  let members = [
+    StructMember<"ol_diagnostic_kind_t", "Kind", "The kind of problem">,
+    StructMember<"int", "HasDeviceId", "Non-zero if DeviceId is known">,
+    StructMember<"int32_t", "DeviceId", "The device the problem was detected 
on, if HasDeviceId is non-zero">,
+    StructMember<"int", "IsFatal", "Non-zero if the detection side judged that 
the execution cannot continue. This is what ol_diagnostic_response_t::Abort 
defaults to; the handler has the last word">,
+    StructMember<"const char*", "Summary", "A one-line description of the 
problem. Never null">,
+    StructMember<"const char*", "OffendingStackTrace", "The host stack trace 
at the point of detection. Never null, possibly empty">,
+    StructMember<"const struct ol_pointer_info_t*", "Pointer", "The device 
pointer involved, or null if none is">,
+    StructMember<"const struct ol_kernel_launch_info_t*", "KernelTraces", "The 
kernel launches worth reporting, most recent first. Null when NumKernelTraces 
is zero">,
+    StructMember<"size_t", "NumKernelTraces", "The number of entries in 
KernelTraces">,
+    StructMember<"ol_diagnostic_hints_t", "Tracking", "What is being tracked, 
for \"use X to get more information\" hints">,
+  ];
+}
+
+def ol_diagnostic_response_t : Struct {
+  let desc = "What a handler wants done with a diagnostic, beyond whatever 
messages it printed itself. The detection side pre-fills it with the defaults, 
the handler only has to touch what it wants to change";
+  let members = [
+    StructMember<"int", "Reported", "Non-zero if the handler reported the 
diagnostic. Defaults to zero, so a handler that leaves it alone gets the 
minimal built-in reporting on top of whatever it did itself">,
+    StructMember<"int", "Abort", "Non-zero if the execution must end once the 
diagnostic is reported. Defaults to ol_diagnostic_t::IsFatal. Clearing it 
resumes execution; note that the operation the problem was detected in still 
fails">,
+  ];
+}
+
+def ol_diagnostic_cb_t : FptrTypedef {
+  let desc = "Turns a diagnostic into a user-visible message and says in 
`Response` what should happen next. Must be thread safe, it can be called from 
plugin-owned threads.";
+  let params = [
+    Param<"const struct ol_diagnostic_t*", "Diag", "the detected problem", 
PARAM_IN>,
+    Param<"void*", "UserData", "the user data of the handler", 
PARAM_IN_OPTIONAL>,
+    Param<"struct ol_diagnostic_response_t*", "Response", "what should happen 
next, pre-filled with the defaults", !or(PARAM_IN, PARAM_OUT)>
+  ];
+  let return = "void";
+}
+
+def ol_diagnostic_handler_t : Struct {
+  let desc = "A diagnostic handler: what to call, and what to pass it";
+  let members = [
+    StructMember<"ol_diagnostic_cb_t", "Callback", "The function called for 
each diagnostic">,
+    StructMember<"void*", "UserData", "Passed to Callback">,
+  ];
+}
diff --git a/offload/liboffload/API/OffloadAPI.td 
b/offload/liboffload/API/OffloadAPI.td
index e28f79f2e34af9..3ccff170665886 100644
--- a/offload/liboffload/API/OffloadAPI.td
+++ b/offload/liboffload/API/OffloadAPI.td
@@ -12,6 +12,7 @@ include "APIDefs.td"
 // Add API definition files here
 include "Common.td"
 include "Platform.td"
+include "Diagnostic.td"
 include "Device.td"
 include "Context.td"
 include "Memory.td"
diff --git a/offload/liboffload/src/OffloadImpl.cpp 
b/offload/liboffload/src/OffloadImpl.cpp
index 71508901025772..e6741b9e7a534a 100644
--- a/offload/liboffload/src/OffloadImpl.cpp
+++ b/offload/liboffload/src/OffloadImpl.cpp
@@ -720,6 +720,12 @@ Error olGetDeviceInfoSize_impl(ol_device_handle_t Device,
   return olGetDeviceInfoImplDetail(Device, PropName, 0, nullptr, PropSizeRet);
 }
 
+Error olSetDeviceDiagnosticHandler_impl(
+    ol_device_handle_t Device, const ol_diagnostic_handler_t *Handler) {
+  Device->Device->setDiagnosticHandler(Handler);
+  return Error::success();
+}
+
 Error olIterateDevices_impl(ol_device_iterate_cb_t Callback, void *UserData) {
   for (auto &Platform : OffloadContext::get().Platforms) {
     auto DevicesOrErr = Platform->getDevices();
diff --git a/offload/libompaccsupport/CMakeLists.txt 
b/offload/libompaccsupport/CMakeLists.txt
index 73382eed07a801..5a672bfdbe9640 100644
--- a/offload/libompaccsupport/CMakeLists.txt
+++ b/offload/libompaccsupport/CMakeLists.txt
@@ -1,6 +1,7 @@
 set(LIBOMPACCSUPPORT_SOURCES
   ${CMAKE_CURRENT_SOURCE_DIR}/AsyncInfo.cpp
   ${CMAKE_CURRENT_SOURCE_DIR}/device.cpp
+  ${CMAKE_CURRENT_SOURCE_DIR}/DiagnosticPrinter.cpp
   ${CMAKE_CURRENT_SOURCE_DIR}/PluginManager.cpp
   ${CMAKE_CURRENT_SOURCE_DIR}/DeviceImage.cpp
   ${CMAKE_CURRENT_SOURCE_DIR}/Mapping.cpp
diff --git a/offload/libompaccsupport/DiagnosticPrinter.cpp 
b/offload/libompaccsupport/DiagnosticPrinter.cpp
new file mode 100644
index 00000000000000..f0ec36fab2465a
--- /dev/null
+++ b/offload/libompaccsupport/DiagnosticPrinter.cpp
@@ -0,0 +1,341 @@
+//===- DiagnosticPrinter.cpp - OpenMP messages for offload diagnostics 
----===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+//
+// Handle diagnostic messages from liboffload.
+//
+//===----------------------------------------------------------------------===//
+
+#include "DiagnosticPrinter.h"
+
+#include "OffloadAPI.h"
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Frontend/OpenMP/OMP.h"
+#include "llvm/Support/Format.h"
+#include "llvm/Support/WithColor.h"
+#include "llvm/Support/raw_ostream.h"
+
+#include <algorithm>
+#include <cassert>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+
+using namespace llvm;
+using namespace llvm::omp::target;
+
+namespace {
+
+class DiagnosticPrinterTy {
+
+  enum ColorTy {
+    Yellow = int(HighlightColor::Address),
+    Green = int(HighlightColor::String),
+    DarkBlue = int(HighlightColor::Tag),
+    Cyan = int(HighlightColor::Attribute),
+    DarkPurple = int(HighlightColor::Enumerator),
+    DarkRed = int(HighlightColor::Macro),
+    BoldRed = int(HighlightColor::Error),
+    BoldLightPurple = int(HighlightColor::Warning),
+    BoldDarkGrey = int(HighlightColor::Note),
+    BoldLightBlue = int(HighlightColor::Remark),
+  };
+
+  /// The banner printed at the beginning of an error report.
+  static constexpr auto ErrorBanner = "OFFLOAD ERROR: ";
+
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgcc-compat"
+#pragma clang diagnostic ignored "-Wformat-security"
+#endif
+  /// Print \p Format, instantiated with \p Args to stderr.
+  /// TODO: Allow redirection into a file stream.
+  template <typename... ArgsTy>
+#ifdef __clang__ // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77958
+  [[gnu::format(__printf__, 1, 2)]]
+#endif
+  static void print(const char *Format, ArgsTy &&...Args) {
+    auto &OS = llvm::errs();
+    OS << llvm::format(Format, Args...);
+  }
+
+  /// Print \p Format, instantiated with \p Args to stderr, but colored.
+  /// TODO: Allow redirection into a file stream.
+  template <typename... ArgsTy>
+#ifdef __clang__ // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77958
+  [[gnu::format(__printf__, 2, 3)]]
+#endif
+  static void print(ColorTy Color, const char *Format, ArgsTy &&...Args) {
+    auto &OS = llvm::errs();
+    WithColor(OS, HighlightColor(Color)) << llvm::format(Format, Args...);
+  }
+
+  /// Print \p Format, instantiated with \p Args to stderr, but colored and 
with
+  /// a banner.
+  /// TODO: Allow redirection into a file stream.
+  template <typename... ArgsTy>
+#ifdef __clang__ // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77958
+  [[gnu::format(__printf__, 1, 2)]]
+#endif
+  static void reportError(const char *Format, ArgsTy &&...Args) {
+    print(BoldRed, "%s", ErrorBanner);
+    print(BoldRed, Format, Args...);
+    print("\n");
+  }
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
+
+  static void reportError(const char *Str) { reportError("%s", Str); }
+  static void print(const char *Str) { print("%s", Str); }
+  static void print(StringRef Str) { print("%s", Str.str().c_str()); }
+  static void print(ColorTy Color, const char *Str) { print(Color, "%s", Str); 
}
+  static void print(ColorTy Color, StringRef Str) {
+    print(Color, "%s", Str.str().c_str());
+  }
+
+  /// Pretty print a stack trace.
+  static void reportStackTrace(StringRef StackTrace) {
+    if (StackTrace.empty())
+      return;
+
+    SmallVector<StringRef> Lines, Parts;
+    StackTrace.split(Lines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
+    int Start = Lines.empty() || !Lines[0].contains("PrintStackTrace") ? 0 : 1;
+    unsigned NumDigits =
+        (int)(floor(log10(Lines.size() - Start - /*0*/ 1)) + 1);
+    for (int I = Start, E = Lines.size(); I < E; ++I) {
+      auto Line = Lines[I];
+      Parts.clear();
+      Line = Line.drop_while([](char C) { return std::isspace(C); });
+      Line.split(Parts, " ", /*MaxSplit=*/2);
+      if (Parts.size() != 3 || Parts[0].size() < 2 || Parts[0][0] != '#') {
+        print("%s\n", Line.str().c_str());
+        continue;
+      }
+      unsigned FrameIdx = std::stoi(Parts[0].drop_front(1).str());
+      if (Start)
+        FrameIdx -= 1;
+      print(DarkPurple, "    %s", Parts[0].take_front().str().c_str());
+      print(Green, "%*u", NumDigits, FrameIdx);
+      print(BoldLightBlue, " %s", Parts[1].str().c_str());
+      print(" %s\n", Parts[2].str().c_str());
+    }
+    print("\n");
+  }
+
+  /// Report information about an allocation, and the prior allocations at the
+  /// same base pointer.
+  static void reportAllocationInfo(const ol_allocation_info_t &Alloc) {
+    if (*Alloc.DeallocationTrace) {
+      print(BoldLightPurple, "Last deallocation:\n");
+      reportStackTrace(Alloc.DeallocationTrace);
+    }
+
+    if (Alloc.HostPtr)
+      print(BoldLightPurple,
+            "Last allocation of size %lu for host pointer %p -> device pointer 
"
+            "%p:\n",
+            Alloc.Size, Alloc.HostPtr, Alloc.DevicePtr);
+    else
+      print(BoldLightPurple,
+            "Last allocation of size %lu -> device pointer %p:\n", Alloc.Size,
+            Alloc.DevicePtr);
+    reportStackTrace(Alloc.AllocationTrace);
+    if (!Alloc.NumPrior)
+      return;
+
+    print(BoldLightPurple, "Prior allocations with the same base pointer:");
+    for (unsigned I = 0, E = Alloc.NumPrior; I < E; ++I) {
+      const auto &Prior = Alloc.Prior[I];
+      print("\n");
+      print(BoldLightPurple, " #%u Prior deallocation of size %lu:\n", I,
+            Prior.Size);
+      reportStackTrace(Prior.DeallocationTrace);
+      if (Prior.HostPtr)
+        print(
+            BoldLightPurple,
+            " #%u Prior allocation for host pointer %p -> device pointer 
%p:\n",
+            I, Prior.HostPtr, Prior.DevicePtr);
+      else
+        print(BoldLightPurple, " #%u Prior allocation -> device pointer %p:\n",
+              I, Prior.DevicePtr);
+      reportStackTrace(Prior.AllocationTrace);
+    }
+  }
+
+  /// Report a deallocation error and the history of the pointer involved.
+  static void reportDeallocationError(const ol_diagnostic_t &Diag) {
+    reportError(Diag.Summary);
+    reportStackTrace(Diag.OffendingStackTrace);
+    if (Diag.Pointer && Diag.Pointer->Allocation)
+      reportAllocationInfo(*Diag.Pointer->Allocation);
+  }
+
+  /// Report the kernel traces in \p Diag, up to
+  /// OFFLOAD_TRACK_NUM_KERNEL_LAUNCH_TRACES many.
+  static void reportKernelTraces(const ol_diagnostic_t &Diag) {
+    uint32_t NumKTIs = Diag.NumKernelTraces;
+    if (NumKTIs == 0) {
+      print(BoldRed, "No kernel launches known\n");
+      return;
+    }
+
+    uint32_t TracesToShow =
+        std::min(Diag.Tracking.KernelLaunchesRequested, NumKTIs);
+    if (TracesToShow == 0) {
+      if (NumKTIs == 1)
+        print(BoldLightPurple, "Display only launched kernel:\n");
+      else
+        print(BoldLightPurple, "Display last %u kernels launched:\n", NumKTIs);
+    } else {
+      if (NumKTIs == 1)
+        print(BoldLightPurple, "Display kernel launch trace:\n");
+      else
+        print(BoldLightPurple,
+              "Display %u of the %u last kernel launch traces:\n", 
TracesToShow,
+              NumKTIs);
+    }
+
+    for (uint32_t I = 0; I < NumKTIs; ++I) {
+      const auto &KTI = Diag.KernelTraces[I];
+      auto PrettyKernelName = llvm::omp::prettifyFunctionName(KTI.Name);
+      if (NumKTIs == 1)
+        print(BoldLightPurple, "Kernel '%s'\n", PrettyKernelName.c_str());
+      else
+        print(BoldLightPurple, "Kernel %d: '%s'\n", I,
+              PrettyKernelName.c_str());
+      reportStackTrace(KTI.LaunchTrace);
+    }
+
+    if (NumKTIs != 1) {
+      print(Yellow,
+            "Use '%s=<num>' to adjust the number of shown stack traces (%u "
+            "now, up to %zu)\n",
+            Diag.Tracking.KernelLaunchesEnvar,
+            Diag.Tracking.KernelLaunchesRequested,
+            size_t(Diag.Tracking.KernelLaunchesCapacity));
+    }
+    // TODO: Let users know how to serialize kernels
+  }
+
+  /// Report a device memory access fault and what is known about the faulting
+  /// pointer.
+  static void reportMemoryAccessError(const ol_diagnostic_t &Diag) {
+    if (Diag.Tracking.KernelLaunchesKnown)
+      reportKernelTraces(Diag);
+
+    reportError(Diag.Summary);
+
+    if (!Diag.Tracking.AllocationTracesEnabled) {
+      print(Yellow, "Use '%s=true' to track device allocations\n",
+            Diag.Tracking.AllocationTracesEnvar);
+      return;
+    }
+
+    if (!Diag.Pointer)
+      return;
+
+    const ol_pointer_info_t &Pointer = *Diag.Pointer;
+    switch (Pointer.Relation) {
+    case OL_POINTER_RELATION_NO_ALLOCATIONS:
+      print(Cyan,
+            "No host-issued allocations; device pointer %p might be "
+            "a global, stack, or shared location\n",
+            Pointer.DevicePtr);
+      return;
+    case OL_POINTER_RELATION_INSIDE:
+    case OL_POINTER_RELATION_INSIDE_PRIOR:
+      print(Cyan, "Device pointer %p points into%s host-issued allocation:\n",
+            Pointer.DevicePtr,
+            Pointer.Relation == OL_POINTER_RELATION_INSIDE ? "" : " prior");
+      if (Pointer.Allocation)
+        reportAllocationInfo(*Pointer.Allocation);
+      return;
+    case OL_POINTER_RELATION_NEAR:
+    case OL_POINTER_RELATION_FAR: {
+      bool IsClose = Pointer.Relation == OL_POINTER_RELATION_NEAR;
+      print(Cyan,
+            "Device pointer %p does not point into any (current or prior) "
+            "host-issued allocation%s.\n",
+            Pointer.DevicePtr,
+            IsClose ? "" : " (might be a global, stack, or shared location)");
+      if (!IsClose)
+        return;
+      print(Cyan,
+            "Closest host-issued allocation (distance %" PRIuPTR
+            " byte%s; might be by page):\n",
+            Pointer.Distance, Pointer.Distance > 1 ? "s" : "");
+      if (Pointer.Allocation)
+        reportAllocationInfo(*Pointer.Allocation);
+      return;
+    }
+    case OL_POINTER_RELATION_LAST:
+    case OL_POINTER_RELATION_FORCE_UINT32:
+      // Not real relations.
+      return;
+    }
+  }
+
+  /// Report that a kernel encountered a trap instruction.
+  static void reportTrapInKernel(const ol_diagnostic_t &Diag) {
+    const ol_kernel_launch_info_t *Culprit =
+        Diag.NumKernelTraces ? &Diag.KernelTraces[0] : nullptr;
+    assert((!Culprit || Culprit->IsCulprit) &&
+           "Expected the reported kernel to be the culprit");
+
+    if (Culprit) {
+      auto PrettyKernelName = llvm::omp::prettifyFunctionName(Culprit->Name);
+      reportError("Kernel '%s'", PrettyKernelName.c_str());
+    }
+    reportError(Diag.Summary);
+    if (!Culprit)
+      return;
+
+    if (*Culprit->LaunchTrace)
+      reportStackTrace(Culprit->LaunchTrace);
+    else
+      print(Yellow, "Use '%s=1' to show the stack trace of the kernel\n",
+            Diag.Tracking.KernelLaunchesEnvar);
+  }
+
+public:
+  /// ol_diagnostic_cb_t entry point.
+  static void report(const ol_diagnostic_t *Diag, void * /*UserData*/,
+                     ol_diagnostic_response_t *Response) {
+    Response->Reported = 1;
+    switch (Diag->Kind) {
+    case OL_DIAGNOSTIC_KIND_DEALLOCATION_OF_NON_ALLOCATED_PTR:
+    case OL_DIAGNOSTIC_KIND_DOUBLE_FREE:
+    case OL_DIAGNOSTIC_KIND_DEALLOCATION_OF_WRONG_PTR_KIND:
+      reportDeallocationError(*Diag);
+      return;
+    case OL_DIAGNOSTIC_KIND_MEMORY_ACCESS_FAULT:
+      reportMemoryAccessError(*Diag);
+      return;
+    case OL_DIAGNOSTIC_KIND_TRAP_IN_KERNEL:
+      reportTrapInKernel(*Diag);
+      return;
+    case OL_DIAGNOSTIC_KIND_LAST:
+    case OL_DIAGNOSTIC_KIND_FORCE_UINT32:
+      // Not real kinds.
+      return;
+    }
+  }
+};
+
+} // namespace
+
+const ol_diagnostic_handler_t *llvm::omp::target::getDiagnosticPrinter() {
+  static const ol_diagnostic_handler_t ThePrinter = {
+      &DiagnosticPrinterTy::report,
+      /*UserData=*/nullptr};
+  return &ThePrinter;
+}
diff --git a/offload/libompaccsupport/device.cpp 
b/offload/libompaccsupport/device.cpp
index 70536dcb47417c..7be17e9e67c84a 100644
--- a/offload/libompaccsupport/device.cpp
+++ b/offload/libompaccsupport/device.cpp
@@ -11,6 +11,7 @@
 
//===----------------------------------------------------------------------===//
 
 #include "device.h"
+#include "DiagnosticPrinter.h"
 #include "OffloadEntry.h"
 #include "OmpAccError.h"
 #include "OpenMP/Mapping.h"
@@ -159,6 +160,11 @@ llvm::Error DeviceTy::init() {
 
   RTL = llvm::offload::tmp::__ol_tgt_GetPluginFromPlatform(Platform);
   RTLDeviceID = llvm::offload::tmp::__ol_tgt_GetPluginDeviceId(DeviceHandle);
+  if (auto Err = olSetDeviceDiagnosticHandler(
+          DeviceHandle, llvm::omp::target::getDiagnosticPrinter()))
+    return createError(ErrorCode::BackendFailure,
+                       "failed to set diagnostic handler for device %d: %s",
+                       DeviceID, Err->Details);
 
   // Needs to be initialized before the GeometryProps.
   if (olGetPlatformInfo(Platform, OL_PLATFORM_INFO_BACKEND, sizeof(Backend),
diff --git a/offload/plugins-nextgen/amdgpu/src/rtl.cpp 
b/offload/plugins-nextgen/amdgpu/src/rtl.cpp
index 8c168873b90535..b932b3785fb9a8 100644
--- a/offload/plugins-nextgen/amdgpu/src/rtl.cpp
+++ b/offload/plugins-nextgen/amdgpu/src/rtl.cpp
@@ -4605,9 +4605,9 @@ struct AMDGPUPluginTy final : public GenericPluginTy {
                          Node, Event->memory_fault.agent.handle,
                          (void *)Event->memory_fault.virtual_address,
                          llvm::join(Reasons, ", ").c_str());
-      ErrorReporter::reportKernelTraces(AMDGPUDevice, *KernelTraceInfoRecord);
       ErrorReporter::reportMemoryAccessError(AMDGPUDevice, DevicePtr, S,
-                                             /*Abort*/ true);
+                                             /*Abort*/ true,
+                                             &*KernelTraceInfoRecord);
     }
 
     // Abort the execution since we do not recover from this error.
diff --git a/offload/plugins-nextgen/common/CMakeLists.txt 
b/offload/plugins-nextgen/common/CMakeLists.txt
index 4942f16afe5196..008b59714e644f 100644
--- a/offload/plugins-nextgen/common/CMakeLists.txt
+++ b/offload/plugins-nextgen/common/CMakeLists.txt
@@ -17,6 +17,7 @@ add_library(PluginCommon OBJECT
   src/RecordReplay.cpp
   src/RPC.cpp
   src/OffloadError.cpp
+  src/ErrorReporting.cpp
   src/Utils/ELF.cpp
 )
 add_dependencies(PluginCommon intrinsics_gen PluginErrcodes OffloadAPI)
diff --git a/offload/plugins-nextgen/common/include/ErrorReporting.h 
b/offload/plugins-nextgen/common/include/ErrorReporting.h
index e6f65549bc3545..6328aef4187e6a 100644
--- a/offload/plugins-nextgen/common/include/ErrorReporting.h
+++ b/offload/plugins-nextgen/common/include/ErrorReporting.h
@@ -1,4 +1,4 @@
-//===- ErrorReporting.h - Helper to provide nice error messages ----- c++ 
-===//
+//===- ErrorReporting.h - Detect and triage offload errors ------- c++ -===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
@@ -6,27 +6,30 @@
 //
 
//===----------------------------------------------------------------------===//
 //
+// Diagnostic entry points for offload error detection.
+// Nothing here formats user-visible messages beyond the one-line summary of
+// what went wrong.
+//
 
//===----------------------------------------------------------------------===//
 
 #ifndef OFFLOAD_PLUGINS_NEXTGEN_COMMON_ERROR_REPORTING_H
 #define OFFLOAD_PLUGINS_NEXTGEN_COMMON_ERROR_REPORTING_H
 
+#include "OffloadAPI.h"
 #include "PluginInterface.h"
 #include "Shared/EnvironmentVar.h"
 
-#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/Frontend/OpenMP/OMP.h"
+#include "llvm/Support/Allocator.h"
 #include "llvm/Support/ErrorHandling.h"
-#include "llvm/Support/WithColor.h"
+#include "llvm/Support/Format.h"
+#include "llvm/Support/StringSaver.h"
 #include "llvm/Support/raw_ostream.h"
 
 #include <cstdint>
-#include <cstdio>
-#include <cstdlib>
 #include <functional>
-#include <optional>
 #include <string>
 
 namespace llvm {
@@ -34,252 +37,260 @@ namespace omp {
 namespace target {
 namespace plugin {
 
-class ErrorReporter {
-
-  enum ColorTy {
-    Yellow = int(HighlightColor::Address),
-    Green = int(HighlightColor::String),
-    DarkBlue = int(HighlightColor::Tag),
-    Cyan = int(HighlightColor::Attribute),
-    DarkPurple = int(HighlightColor::Enumerator),
-    DarkRed = int(HighlightColor::Macro),
-    BoldRed = int(HighlightColor::Error),
-    BoldLightPurple = int(HighlightColor::Warning),
-    BoldDarkGrey = int(HighlightColor::Note),
-    BoldLightBlue = int(HighlightColor::Remark),
-  };
-
-  /// The banner printed at the beginning of an error report.
-  static constexpr auto ErrorBanner = "OFFLOAD ERROR: ";
-
-  /// Return the device id as string, or n/a if not available.
-  static std::string getDeviceIdStr(GenericDeviceTy *Device) {
-    return Device ? std::to_string(Device->getDeviceId()) : "n/a";
+/// Builds an ol_diagnostic_t and owns the storage its pointers refer to, so 
the
+/// diagnostic is only usable while the builder is alive.
+class DiagnosticBuilderTy {
+public:
+  explicit DiagnosticBuilderTy(ol_diagnostic_kind_t Kind) {
+    Diag.Kind = Kind;
+    Diag.IsFatal = 1;
+    // The strings in a diagnostic are never null, only possibly empty.
+    Diag.Summary = "";
+    Diag.OffendingStackTrace = "";
   }
 
-  /// Return a nice name for an TargetAllocTy.
-  static StringRef getAllocTyName(TargetAllocTy Kind) {
-    switch (Kind) {
-    case TARGET_ALLOC_DEFAULT:
-    case TARGET_ALLOC_DEVICE:
-      return "device memory";
-    case TARGET_ALLOC_HOST:
-      return "pinned host memory";
-    case TARGET_ALLOC_SHARED:
-      return "managed memory";
-      break;
-    }
-    llvm_unreachable("Unknown target alloc kind");
-  }
+  /// The diagnostic being built. Its pointer fields are owned by this object.
+  ol_diagnostic_t Diag{};
 
 #ifdef __clang__
 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wgcc-compat"
 #pragma clang diagnostic ignored "-Wformat-security"
 #endif
-  /// Print \p Format, instantiated with \p Args to stderr.
-  /// TODO: Allow redirection into a file stream.
+  /// Set the one-line description of the problem to \p Format, instantiated
+  /// with \p Args.
   template <typename... ArgsTy>
 #ifdef __clang__ // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77958
-  [[gnu::format(__printf__, 1, 2)]]
+  [[gnu::format(__printf__, 2, 3)]]
 #endif
-  static void print(const char *Format, ArgsTy &&...Args) {
-    auto &OS = llvm::errs();
+  void setSummary(const char *Format, ArgsTy &&...Args) {
+    SmallString<128> Summary;
+    raw_svector_ostream OS(Summary);
     OS << llvm::format(Format, Args...);
+    Diag.Summary = store(Summary);
   }
-
-  /// Print \p Format, instantiated with \p Args to stderr, but colored.
-  /// TODO: Allow redirection into a file stream.
-  template <typename... ArgsTy>
-#ifdef __clang__ // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77958
-  [[gnu::format(__printf__, 2, 3)]]
+#ifdef __clang__
+#pragma clang diagnostic pop
 #endif
-  static void print(ColorTy Color, const char *Format, ArgsTy &&...Args) {
-    auto &OS = llvm::errs();
-    WithColor(OS, HighlightColor(Color)) << llvm::format(Format, Args...);
+
+  /// Set the host stack trace at the point of detection.
+  void setOffendingStackTrace(StringRef StackTrace) {
+    Diag.OffendingStackTrace = store(StackTrace);
   }
 
-  /// Print \p Format, instantiated with \p Args to stderr, but colored and 
with
-  /// a banner.
-  /// TODO: Allow redirection into a file stream.
-  template <typename... ArgsTy>
-#ifdef __clang__ // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77958
-  [[gnu::format(__printf__, 1, 2)]]
-#endif
-  static void reportError(const char *Format, ArgsTy &&...Args) {
-    print(BoldRed, "%s", ErrorBanner);
-    print(BoldRed, Format, Args...);
-    print("\n");
+  void setTracking(GenericDeviceTy &Device) {
+    // The names are string literals, so they can be used as C strings.
+    Diag.Tracking.AllocationTracesEnabled = Device.OMPX_TrackAllocationTraces;
+    Diag.Tracking.AllocationTracesEnvar =
+        Device.OMPX_TrackAllocationTraces.getName().data();
+    Diag.Tracking.KernelLaunchesEnvar =
+        Device.OMPX_TrackNumKernelLaunches.getName().data();
+    Diag.Tracking.KernelLaunchesRequested =
+        Device.OMPX_TrackNumKernelLaunches.get();
   }
-#ifdef __clang__
-#pragma clang diagnostic pop
-#endif
 
-  static void reportError(const char *Str) { reportError("%s", Str); }
-  static void print(const char *Str) { print("%s", Str); }
-  static void print(StringRef Str) { print("%s", Str.str().c_str()); }
-  static void print(ColorTy Color, const char *Str) { print(Color, "%s", Str); 
}
-  static void print(ColorTy Color, StringRef Str) {
-    print(Color, "%s", Str.str().c_str());
+  ol_pointer_info_t &setPointer(void *DevicePtr) {
+    Pointer = ol_pointer_info_t{};
+    Pointer.DevicePtr = DevicePtr;
+    Pointer.Relation = OL_POINTER_RELATION_NO_ALLOCATIONS;
+    Diag.Pointer = &Pointer;
+    return Pointer;
   }
 
-  /// Pretty print a stack trace.
-  static void reportStackTrace(StringRef StackTrace) {
-    if (StackTrace.empty())
-      return;
+  void setAllocation(AllocationTraceInfoTy *ATI) {
+    assert(Diag.Pointer && "No pointer to attach the allocation to");
+    fill(Allocation, ATI);
 
-    SmallVector<StringRef> Lines, Parts;
-    StackTrace.split(Lines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
-    int Start = Lines.empty() || !Lines[0].contains("PrintStackTrace") ? 0 : 1;
-    unsigned NumDigits =
-        (int)(floor(log10(Lines.size() - Start - /*0*/ 1)) + 1);
-    for (int I = Start, E = Lines.size(); I < E; ++I) {
-      auto Line = Lines[I];
-      Parts.clear();
-      Line = Line.drop_while([](char C) { return std::isspace(C); });
-      Line.split(Parts, " ", /*MaxSplit=*/2);
-      if (Parts.size() != 3 || Parts[0].size() < 2 || Parts[0][0] != '#') {
-        print("%s\n", Line.str().c_str());
-        continue;
-      }
-      unsigned FrameIdx = std::stoi(Parts[0].drop_front(1).str());
-      if (Start)
-        FrameIdx -= 1;
-      print(DarkPurple, "    %s", Parts[0].take_front().str().c_str());
-      print(Green, "%*u", NumDigits, FrameIdx);
-      print(BoldLightBlue, " %s", Parts[1].str().c_str());
-      print(" %s\n", Parts[2].str().c_str());
+    for (auto *Prior = ATI->LastAllocationInfo; Prior;
+         Prior = Prior->LastAllocationInfo)
+      fill(PriorAllocations.emplace_back(), Prior);
+
+    Allocation.Prior =
+        PriorAllocations.empty() ? nullptr : PriorAllocations.data();
+    Allocation.NumPrior = PriorAllocations.size();
+    Pointer.Allocation = &Allocation;
+  }
+
+  void addKernelTrace(const KernelTraceInfoTy &KTI, bool IsCulprit) {
+    ol_kernel_launch_info_t &Info = KernelTraces.emplace_back();
+    // The name belongs to the kernel, which outlives the diagnostic.
+    Info.Name = KTI.Kernel->getName();
+    Info.LaunchTrace = store(KTI.LaunchTrace);
+    Info.IsCulprit = IsCulprit;
+
+    Diag.KernelTraces = KernelTraces.data();
+    Diag.NumKernelTraces = KernelTraces.size();
+  }
+
+private:
+  /// Keep a copy of \p Str and return it as a C string. The copies live until
+  /// the builder dies, and StringSaver null-terminates them.
+  const char *store(StringRef Str) { return Strings.save(Str).data(); }
+
+  /// Copy the parts of \p ATI the messaging side can report into \p Info.
+  void fill(ol_allocation_info_t &Info, AllocationTraceInfoTy *ATI) {
+    Info.AllocationTrace = store(ATI->AllocationTrace);
+    Info.DeallocationTrace = store(ATI->DeallocationTrace);
+    Info.DevicePtr = ATI->DevicePtr;
+    Info.HostPtr = ATI->HostPtr;
+    Info.Size = ATI->Size;
+    Info.Prior = nullptr;
+    Info.NumPrior = 0;
+  }
+
+  /// Storage for the strings the diagnostic points into.
+  BumpPtrAllocator StringAlloc;
+  StringSaver Strings{StringAlloc};
+
+  ol_pointer_info_t Pointer{};
+  ol_allocation_info_t Allocation{};
+  SmallVector<ol_allocation_info_t> PriorAllocations;
+  SmallVector<ol_kernel_launch_info_t> KernelTraces;
+};
+
+/// Hand \p Diag to \p Handler, falling back to the built-in minimal reporting
+/// if there is no handler or if the handler asks for it, then end the 
execution
+/// unless the handler decided otherwise.
+void emitDiagnostic(const ol_diagnostic_handler_t *Handler,
+                    const ol_diagnostic_t &Diag);
+
+class ErrorReporter {
+
+  /// Return a nice name for an TargetAllocTy.
+  static StringRef getAllocTyName(TargetAllocTy Kind) {
+    switch (Kind) {
+    case TARGET_ALLOC_DEFAULT:
+    case TARGET_ALLOC_DEVICE:
+      return "device memory";
+    case TARGET_ALLOC_HOST:
+      return "pinned host memory";
+    case TARGET_ALLOC_SHARED:
+      return "managed memory";
+      break;
     }
-    print("\n");
+    llvm_unreachable("Unknown target alloc kind");
   }
 
-  /// Report information about an allocation associated with \p ATI.
-  static void reportAllocationInfo(AllocationTraceInfoTy *ATI) {
-    if (!ATI)
-      return;
+  /// Classify how \p DevicePtr relates to the allocations known to \p Device.
+  static void classifyPointer(GenericDeviceTy &Device, void *DevicePtr,
+                              DiagnosticBuilderTy &Builder) {
+    ol_pointer_info_t &Pointer = Builder.setPointer(DevicePtr);
 
-    if (!ATI->DeallocationTrace.empty()) {
-      print(BoldLightPurple, "Last deallocation:\n");
-      reportStackTrace(ATI->DeallocationTrace);
+    uintptr_t Distance = 0;
+    auto *ATI =
+        Device.getClosestAllocationTraceInfoForAddr(DevicePtr, Distance);
+    if (!ATI) {
+      Pointer.Relation = OL_POINTER_RELATION_NO_ALLOCATIONS;
+      return;
     }
 
-    if (ATI->HostPtr)
-      print(BoldLightPurple,
-            "Last allocation of size %lu for host pointer %p -> device pointer 
"
-            "%p:\n",
-            ATI->Size, ATI->HostPtr, ATI->DevicePtr);
-    else
-      print(BoldLightPurple,
-            "Last allocation of size %lu -> device pointer %p:\n", ATI->Size,
-            ATI->DevicePtr);
-    reportStackTrace(ATI->AllocationTrace);
-    if (!ATI->LastAllocationInfo)
+    if (!Distance) {
+      Pointer.Relation = ATI->DeallocationTrace.empty()
+                             ? OL_POINTER_RELATION_INSIDE
+                             : OL_POINTER_RELATION_INSIDE_PRIOR;
+      Builder.setAllocation(ATI);
       return;
+    }
 
-    unsigned I = 0;
-    print(BoldLightPurple, "Prior allocations with the same base pointer:");
-    while (ATI->LastAllocationInfo) {
-      print("\n");
-      ATI = ATI->LastAllocationInfo;
-      print(BoldLightPurple, " #%u Prior deallocation of size %lu:\n", I,
-            ATI->Size);
-      reportStackTrace(ATI->DeallocationTrace);
-      if (ATI->HostPtr)
-        print(
-            BoldLightPurple,
-            " #%u Prior allocation for host pointer %p -> device pointer 
%p:\n",
-            I, ATI->HostPtr, ATI->DevicePtr);
-      else
-        print(BoldLightPurple, " #%u Prior allocation -> device pointer %p:\n",
-              I, ATI->DevicePtr);
-      reportStackTrace(ATI->AllocationTrace);
-      ++I;
+    bool IsClose = Distance < (1L << 29L /*512MB=*/);
+    Pointer.Distance = Distance;
+    if (!IsClose) {
+      Pointer.Relation = OL_POINTER_RELATION_FAR;
+      return;
     }
+
+    Pointer.Relation = OL_POINTER_RELATION_NEAR;
+    Builder.setAllocation(ATI);
   }
 
-  /// End the execution of the program.
-  static void abortExecution() { abort(); }
+  /// Report the kernel launches recorded in \p KTIR, most recent first.
+  static void collectKernelTraces(KernelTraceInfoRecordTy &KTIR,
+                                  DiagnosticBuilderTy &Builder) {
+    Builder.Diag.Tracking.KernelLaunchesKnown = 1;
+    Builder.Diag.Tracking.KernelLaunchesCapacity = KTIR.size();
 
-public:
-#define DEALLOCATION_ERROR(Format, ...)                                        
\
-  reportError(Format, __VA_ARGS__);                                            
\
-  reportStackTrace(StackTrace);                                                
\
-  reportAllocationInfo(ATI);                                                   
\
-  abortExecution();
+    for (uint32_t I = 0, E = KTIR.size(); I < E; ++I) {
+      auto KTI = KTIR.getKernelTraceInfo(I);
+      if (KTI.Kernel == nullptr)
+        break;
+      Builder.addKernelTrace(KTI, /*IsCulprit=*/false);
+    }
+    Builder.Diag.Tracking.KernelLaunchesAvailable =
+        Builder.Diag.NumKernelTraces;
+  }
 
-  static void reportDeallocationOfNonAllocatedPtr(void *DevicePtr,
+public:
+#define DEALLOCATION_DIAGNOSTIC(DiagKind, Format, ...)                         
\
+  DiagnosticBuilderTy Builder(DiagKind);                                       
\
+  Builder.Diag.HasDeviceId = 1;                                                
\
+  Builder.Diag.DeviceId = Device.getDeviceId();                                
\
+  Builder.setSummary(Format, __VA_ARGS__);                                     
\
+  Builder.setOffendingStackTrace(StackTrace);                                  
\
+  if (ATI) {                                                                   
\
+    Builder.setPointer(DevicePtr).Relation = OL_POINTER_RELATION_INSIDE;       
\
+    Builder.setAllocation(ATI);                                                
\
+  }                                                                            
\
+  emitDiagnostic(Device.getDiagnosticHandler(), Builder.Diag);
+
+  static void reportDeallocationOfNonAllocatedPtr(GenericDeviceTy &Device,
+                                                  void *DevicePtr,
                                                   TargetAllocTy Kind,
                                                   AllocationTraceInfoTy *ATI,
                                                   std::string &StackTrace) {
-    DEALLOCATION_ERROR("deallocation of non-allocated %s: %p",
-                       getAllocTyName(Kind).data(), DevicePtr);
+    DEALLOCATION_DIAGNOSTIC(
+        OL_DIAGNOSTIC_KIND_DEALLOCATION_OF_NON_ALLOCATED_PTR,
+        "deallocation of non-allocated %s: %p", getAllocTyName(Kind).data(),
+        DevicePtr);
   }
 
-  static void reportDeallocationOfDeallocatedPtr(void *DevicePtr,
+  static void reportDeallocationOfDeallocatedPtr(GenericDeviceTy &Device,
+                                                 void *DevicePtr,
                                                  TargetAllocTy Kind,
                                                  AllocationTraceInfoTy *ATI,
                                                  std::string &StackTrace) {
-    DEALLOCATION_ERROR("double-free of %s: %p", getAllocTyName(Kind).data(),
-                       DevicePtr);
+    DEALLOCATION_DIAGNOSTIC(OL_DIAGNOSTIC_KIND_DOUBLE_FREE,
+                            "double-free of %s: %p",
+                            getAllocTyName(Kind).data(), DevicePtr);
   }
 
-  static void reportDeallocationOfWrongPtrKind(void *DevicePtr,
+  static void reportDeallocationOfWrongPtrKind(GenericDeviceTy &Device,
+                                               void *DevicePtr,
                                                TargetAllocTy Kind,
                                                AllocationTraceInfoTy *ATI,
                                                std::string &StackTrace) {
-    DEALLOCATION_ERROR("deallocation requires %s but allocation was %s: %p",
-                       getAllocTyName(Kind).data(),
-                       getAllocTyName(ATI->Kind).data(), DevicePtr);
-#undef DEALLOCATION_ERROR
+    DEALLOCATION_DIAGNOSTIC(
+        OL_DIAGNOSTIC_KIND_DEALLOCATION_OF_WRONG_PTR_KIND,
+        "deallocation requires %s but allocation was %s: %p",
+        getAllocTyName(Kind).data(), getAllocTyName(ATI->Kind).data(),
+        DevicePtr);
+#undef DEALLOCATION_DIAGNOSTIC
   }
 
+  /// Report that the device faulted accessing \p DevicePtr. If \p KTIR is 
given
+  /// the known kernel launches are reported alongside the fault. The fault is
+  /// asynchronous: there is no call to attribute it to, it is reported with
+  /// the handler of the device it happened on like everything else.
   static void reportMemoryAccessError(GenericDeviceTy &Device, void *DevicePtr,
-                                      std::string &ErrorStr, bool Abort) {
-    reportError(ErrorStr.c_str());
-
-    if (!Device.OMPX_TrackAllocationTraces) {
-      print(Yellow, "Use '%s=true' to track device allocations\n",
-            Device.OMPX_TrackAllocationTraces.getName().data());
-      if (Abort)
-        abortExecution();
-      return;
-    }
-    uintptr_t Distance = false;
-    auto *ATI =
-        Device.getClosestAllocationTraceInfoForAddr(DevicePtr, Distance);
-    if (!ATI) {
-      print(Cyan,
-            "No host-issued allocations; device pointer %p might be "
-            "a global, stack, or shared location\n",
-            DevicePtr);
-      if (Abort)
-        abortExecution();
-      return;
-    }
-    if (!Distance) {
-      print(Cyan, "Device pointer %p points into%s host-issued allocation:\n",
-            DevicePtr, ATI->DeallocationTrace.empty() ? "" : " prior");
-      reportAllocationInfo(ATI);
-      if (Abort)
-        abortExecution();
-      return;
-    }
+                                      std::string &ErrorStr, bool Abort,
+                                      KernelTraceInfoRecordTy *KTIR = nullptr) 
{
+    DiagnosticBuilderTy Builder(OL_DIAGNOSTIC_KIND_MEMORY_ACCESS_FAULT);
+    Builder.Diag.HasDeviceId = 1;
+    Builder.Diag.DeviceId = Device.getDeviceId();
+    Builder.Diag.IsFatal = Abort;
+    Builder.setSummary("%s", ErrorStr.c_str());
+    Builder.setTracking(Device);
+
+    if (KTIR)
+      collectKernelTraces(*KTIR, Builder);
+
+    // Without allocation tracking there is nothing to say about the pointer
+    // beyond its value, the messaging side will suggest enabling tracking.
+    if (Device.OMPX_TrackAllocationTraces)
+      classifyPointer(Device, DevicePtr, Builder);
+    else
+      Builder.setPointer(DevicePtr);
 
-    bool IsClose = Distance < (1L << 29L /*512MB=*/);
-    print(Cyan,
-          "Device pointer %p does not point into any (current or prior) "
-          "host-issued allocation%s.\n",
-          DevicePtr,
-          IsClose ? "" : " (might be a global, stack, or shared location)");
-    if (IsClose) {
-      print(Cyan,
-            "Closest host-issued allocation (distance %" PRIuPTR
-            " byte%s; might be by page):\n",
-            Distance, Distance > 1 ? "s" : "");
-      reportAllocationInfo(ATI);
-    }
-    if (Abort)
-      abortExecution();
+    emitDiagnostic(Device.getDiagnosticHandler(), Builder.Diag);
   }
 
   /// Report that a kernel encountered a trap instruction.
@@ -288,6 +299,13 @@ class ErrorReporter {
       std::function<bool(__tgt_async_info &)> AsyncInfoWrapperMatcher) {
     assert(AsyncInfoWrapperMatcher && "A matcher is required");
 
+    DiagnosticBuilderTy Builder(OL_DIAGNOSTIC_KIND_TRAP_IN_KERNEL);
+    Builder.Diag.HasDeviceId = 1;
+    Builder.Diag.DeviceId = Device.getDeviceId();
+    Builder.setSummary("%s",
+                       "execution interrupted by hardware trap instruction");
+    Builder.setTracking(Device);
+
     uint32_t Idx = 0;
     for (uint32_t I = 0, E = KTIR.size(); I < E; ++I) {
       auto KTI = KTIR.getKernelTraceInfo(I);
@@ -301,75 +319,10 @@ class ErrorReporter {
     }
 
     auto KTI = KTIR.getKernelTraceInfo(Idx);
-    if (KTI.AsyncInfo && (AsyncInfoWrapperMatcher(*KTI.AsyncInfo))) {
-      auto PrettyKernelName =
-          llvm::omp::prettifyFunctionName(KTI.Kernel->getName());
-      reportError("Kernel '%s'", PrettyKernelName.c_str());
-    }
-    reportError("execution interrupted by hardware trap instruction");
-    if (KTI.AsyncInfo && (AsyncInfoWrapperMatcher(*KTI.AsyncInfo))) {
-      if (!KTI.LaunchTrace.empty())
-        reportStackTrace(KTI.LaunchTrace);
-      else
-        print(Yellow, "Use '%s=1' to show the stack trace of the kernel\n",
-              Device.OMPX_TrackNumKernelLaunches.getName().data());
-    }
-    abort();
-  }
+    if (KTI.AsyncInfo && (AsyncInfoWrapperMatcher(*KTI.AsyncInfo)))
+      Builder.addKernelTrace(KTI, /*IsCulprit=*/true);
 
-  /// Report the kernel traces taken from \p KTIR, up to
-  /// OFFLOAD_TRACK_NUM_KERNEL_LAUNCH_TRACES many.
-  static void reportKernelTraces(GenericDeviceTy &Device,
-                                 KernelTraceInfoRecordTy &KTIR) {
-    uint32_t NumKTIs = 0;
-    for (uint32_t I = 0, E = KTIR.size(); I < E; ++I) {
-      auto KTI = KTIR.getKernelTraceInfo(I);
-      if (KTI.Kernel == nullptr)
-        break;
-      ++NumKTIs;
-    }
-    if (NumKTIs == 0) {
-      print(BoldRed, "No kernel launches known\n");
-      return;
-    }
-
-    uint32_t TracesToShow =
-        std::min(Device.OMPX_TrackNumKernelLaunches.get(), NumKTIs);
-    if (TracesToShow == 0) {
-      if (NumKTIs == 1)
-        print(BoldLightPurple, "Display only launched kernel:\n");
-      else
-        print(BoldLightPurple, "Display last %u kernels launched:\n", NumKTIs);
-    } else {
-      if (NumKTIs == 1)
-        print(BoldLightPurple, "Display kernel launch trace:\n");
-      else
-        print(BoldLightPurple,
-              "Display %u of the %u last kernel launch traces:\n", 
TracesToShow,
-              NumKTIs);
-    }
-
-    for (uint32_t Idx = 0, I = 0; I < NumKTIs; ++Idx) {
-      auto KTI = KTIR.getKernelTraceInfo(Idx);
-      auto PrettyKernelName =
-          llvm::omp::prettifyFunctionName(KTI.Kernel->getName());
-      if (NumKTIs == 1)
-        print(BoldLightPurple, "Kernel '%s'\n", PrettyKernelName.c_str());
-      else
-        print(BoldLightPurple, "Kernel %d: '%s'\n", I,
-              PrettyKernelName.c_str());
-      reportStackTrace(KTI.LaunchTrace);
-      ++I;
-    }
-
-    if (NumKTIs != 1) {
-      print(Yellow,
-            "Use '%s=<num>' to adjust the number of shown stack traces (%u "
-            "now, up to %zu)\n",
-            Device.OMPX_TrackNumKernelLaunches.getName().data(),
-            Device.OMPX_TrackNumKernelLaunches.get(), KTIR.size());
-    }
-    // TODO: Let users know how to serialize kernels
+    emitDiagnostic(Device.getDiagnosticHandler(), Builder.Diag);
   }
 };
 
diff --git a/offload/plugins-nextgen/common/include/PluginInterface.h 
b/offload/plugins-nextgen/common/include/PluginInterface.h
index 699c4b7c350750..e5deffb5a407d0 100644
--- a/offload/plugins-nextgen/common/include/PluginInterface.h
+++ b/offload/plugins-nextgen/common/include/PluginInterface.h
@@ -11,6 +11,7 @@
 #ifndef OPENMP_LIBOMPTARGET_PLUGINS_NEXTGEN_COMMON_PLUGININTERFACE_H
 #define OPENMP_LIBOMPTARGET_PLUGINS_NEXTGEN_COMMON_PLUGININTERFACE_H
 
+#include <atomic>
 #include <cstddef>
 #include <cstdint>
 #include <deque>
@@ -22,6 +23,7 @@
 #include <vector>
 
 #include "ExclusiveAccess.h"
+#include "OffloadAPI.h"
 #include "OpenMP/InteropAPI.h"
 #include "Shared/APITypes.h"
 #include "Shared/Debug.h"
@@ -990,7 +992,7 @@ struct GenericDeviceTy : public DeviceAllocatorTy {
   /// Record the deallocation of \p Kind memory at \p DevicePtr, and report it
   /// if the allocation it refers to was never made, is already deallocated, or
   /// was of another kind. Does nothing if allocation traces are not tracked.
-  void recordDeallocation(void *DevicePtr, TargetAllocTy Kind);
+  Error recordDeallocation(void *DevicePtr, TargetAllocTy Kind);
 
   /// Pin or register host memory to optimize transfers and return the device
   /// accessible pointer that devices should use for memory transfers involving
@@ -1303,9 +1305,22 @@ struct GenericDeviceTy : public DeviceAllocatorTy {
 
   RecordReplayTy *getRecordReplay() { return RecordReplay; }
 
+  /// Set the handler used to report problems detected on this device.
+  void setDiagnosticHandler(const ol_diagnostic_handler_t *Handler) {
+    DiagnosticHandler.store(Handler, std::memory_order_release);
+  }
+
+  /// Return the handler for problems detected on this device.
+  const ol_diagnostic_handler_t *getDiagnosticHandler() const {
+    return DiagnosticHandler.load(std::memory_order_acquire);
+  }
+
   /// Map to record kernel have been launchedl, for error reporting purposes.
   ProtectedObj<KernelTraceInfoRecordTy> KernelLaunchTraces;
 
+  /// Handler for problems detected on this device.
+  std::atomic<const ol_diagnostic_handler_t *> DiagnosticHandler{nullptr};
+
   /// Environment variable to determine if stack traces for kernel launches are
   /// tracked.
   UInt32Envar OMPX_TrackNumKernelLaunches =
diff --git a/offload/plugins-nextgen/common/src/ErrorReporting.cpp 
b/offload/plugins-nextgen/common/src/ErrorReporting.cpp
new file mode 100644
index 00000000000000..d492159bc0557e
--- /dev/null
+++ b/offload/plugins-nextgen/common/src/ErrorReporting.cpp
@@ -0,0 +1,64 @@
+//===- ErrorReporting.cpp - Diagnostic dispatch for the plugin interface 
--===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+//
+// Diagnostic dispatch for the detection side of error reporting, plus the
+// minimal built-in reporting used for diagnostics that come with no handler.
+//
+//===----------------------------------------------------------------------===//
+
+#include "OffloadAPI.h"
+
+#include "ErrorReporting.h"
+
+#include "llvm/Support/raw_ostream.h"
+
+#include <cstdlib>
+
+using namespace llvm;
+using namespace omp;
+using namespace target;
+using namespace plugin;
+
+/// Simple default reporting of diagnostics.
+static void reportDefault(const ol_diagnostic_t &Diag) {
+  auto &OS = errs();
+  OS << "OFFLOAD ERROR: " << Diag.Summary << "\n";
+
+  if (*Diag.OffendingStackTrace)
+    OS << Diag.OffendingStackTrace;
+
+  if (Diag.Pointer && Diag.Pointer->Allocation) {
+    const ol_allocation_info_t &Alloc = *Diag.Pointer->Allocation;
+    if (*Alloc.DeallocationTrace)
+      OS << "Last deallocation:\n" << Alloc.DeallocationTrace;
+    OS << "Last allocation of size " << Alloc.Size << " -> device pointer "
+       << Alloc.DevicePtr << ":\n"
+       << Alloc.AllocationTrace;
+  }
+
+  for (size_t I = 0, E = Diag.NumKernelTraces; I < E; ++I) {
+    const ol_kernel_launch_info_t &KTI = Diag.KernelTraces[I];
+    OS << "Kernel '" << KTI.Name << "'\n";
+    if (*KTI.LaunchTrace)
+      OS << KTI.LaunchTrace;
+  }
+}
+
+void llvm::omp::target::plugin::emitDiagnostic(
+    const ol_diagnostic_handler_t *Handler, const ol_diagnostic_t &Diag) {
+  // The handler only has to override what it cares about.
+  ol_diagnostic_response_t Response = {/*Reported=*/0, /*Abort=*/Diag.IsFatal};
+  if (Handler && Handler->Callback)
+    Handler->Callback(&Diag, Handler->UserData, &Response);
+
+  if (!Response.Reported)
+    reportDefault(Diag);
+
+  if (Response.Abort)
+    abort();
+}
diff --git a/offload/plugins-nextgen/common/src/PluginInterface.cpp 
b/offload/plugins-nextgen/common/src/PluginInterface.cpp
index 7926a70e390603..bc5b501e6b1c1e 100644
--- a/offload/plugins-nextgen/common/src/PluginInterface.cpp
+++ b/offload/plugins-nextgen/common/src/PluginInterface.cpp
@@ -640,9 +640,9 @@ void GenericDeviceTy::recordAllocation(void *DevicePtr, 
void *HostPtr,
   MapATI = ATI;
 }
 
-void GenericDeviceTy::recordDeallocation(void *DevicePtr, TargetAllocTy Kind) {
+Error GenericDeviceTy::recordDeallocation(void *DevicePtr, TargetAllocTy Kind) 
{
   if (!OMPX_TrackAllocationTraces)
-    return;
+    return Plugin::success();
 
   AllocationTraceInfoTy *ATI = nullptr;
   {
@@ -654,21 +654,37 @@ void GenericDeviceTy::recordDeallocation(void *DevicePtr, 
TargetAllocTy Kind) {
   llvm::raw_string_ostream OS(StackTrace);
   llvm::sys::PrintStackTrace(OS);
 
-  if (!ATI)
-    ErrorReporter::reportDeallocationOfNonAllocatedPtr(DevicePtr, Kind, ATI,
-                                                       StackTrace);
+  // The reporting functions below only return if the diagnostic handler
+  // decided that the problem should not end the execution. There is no
+  // sensible way to carry out any of these deallocations, so the call fails
+  // instead.
+  if (!ATI) {
+    ErrorReporter::reportDeallocationOfNonAllocatedPtr(*this, DevicePtr, Kind,
+                                                       ATI, StackTrace);
+    return Plugin::error(ErrorCode::INVALID_ARGUMENT,
+                         "deallocation of non-allocated pointer %p", 
DevicePtr);
+  }
 
   // ATI is not null, thus we can lock it to inspect and modify it further.
   std::lock_guard<std::mutex> LG(ATI->Lock);
-  if (!ATI->DeallocationTrace.empty())
-    ErrorReporter::reportDeallocationOfDeallocatedPtr(DevicePtr, Kind, ATI,
-                                                      StackTrace);
+  if (!ATI->DeallocationTrace.empty()) {
+    ErrorReporter::reportDeallocationOfDeallocatedPtr(*this, DevicePtr, Kind,
+                                                      ATI, StackTrace);
+    return Plugin::error(ErrorCode::INVALID_ARGUMENT,
+                         "double-free of pointer %p", DevicePtr);
+  }
 
-  if (ATI->Kind != Kind)
-    ErrorReporter::reportDeallocationOfWrongPtrKind(DevicePtr, Kind, ATI,
+  if (ATI->Kind != Kind) {
+    ErrorReporter::reportDeallocationOfWrongPtrKind(*this, DevicePtr, Kind, 
ATI,
                                                     StackTrace);
+    return Plugin::error(
+        ErrorCode::INVALID_ARGUMENT,
+        "deallocation of pointer %p with a different allocation kind",
+        DevicePtr);
+  }
 
   ATI->DeallocationTrace = StackTrace;
+  return Plugin::success();
 }
 
 Error GenericDeviceTy::dataDelete(void *TgtPtr, TargetAllocTy Kind,
@@ -899,7 +915,8 @@ Error PluginContextTy::deallocate(void *Ptr, 
GenericProfilerTy *ProfilerPtr) {
 Error PluginContextTy::deallocate(GenericDeviceTy &Device, void *Ptr,
                                   TargetAllocTy Kind,
                                   GenericProfilerTy *ProfilerPtr) {
-  Device.recordDeallocation(Ptr, Kind);
+  if (auto Err = Device.recordDeallocation(Ptr, Kind))
+    return Err;
   untrackAllocation(Ptr);
 
   if (MemoryManagerTy *Manager = getMemoryManagerFor(Device, Kind))
diff --git a/offload/tools/offload-tblgen/PrintGen.cpp 
b/offload/tools/offload-tblgen/PrintGen.cpp
index d2475d0d43a01e..44a6d69a1dd2c3 100644
--- a/offload/tools/offload-tblgen/PrintGen.cpp
+++ b/offload/tools/offload-tblgen/PrintGen.cpp
@@ -172,6 +172,9 @@ inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os, 
const struct {0} par
     OS << formatv(TAB_1 "os << \".{0} = \";\n", Member.getName());
     if (Member.isPointerType() || Member.isHandleType()) {
       OS << formatv(TAB_1 "printPtr(os, params.{0});\n", Member.getName());
+    } else if (Member.isFptrType()) {
+      OS << formatv(TAB_1 "os << reinterpret_cast<void*>(params.{0});\n",
+                    Member.getName());
     } else {
       OS << formatv(TAB_1 "os << params.{0};\n", Member.getName());
     }
diff --git a/offload/tools/offload-tblgen/RecordTypes.hpp 
b/offload/tools/offload-tblgen/RecordTypes.hpp
index 584025dcce3321..335f672a49c33a 100644
--- a/offload/tools/offload-tblgen/RecordTypes.hpp
+++ b/offload/tools/offload-tblgen/RecordTypes.hpp
@@ -107,6 +107,7 @@ class StructMemberRec {
   StringRef getDesc() const { return rec->getValueAsString("desc"); }
   bool isPointerType() const { return getType().ends_with('*'); }
   bool isHandleType() const { return getType().ends_with("_handle_t"); }
+  bool isFptrType() const { return getType().ends_with("_cb_t"); }
 
 private:
   const Record *rec;

_______________________________________________
llvm-branch-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits

Reply via email to