[Hexagon] Experimental Qualcomm Hexagon DSP HAL driver (part 1: list and open devices) (#25188) This is the first part of upstreaming the Hexagon HAL driver that Roofline is developing in a separate plugin repository (https://github.com/RooflineAI/iree-hexagon-plugins). The driver runs on Android arm64 hosts and is compatible with Qualcomm Snapdragon SoCs, using FastRPC to drive the Hexagon DSP. It lives in `experimental/runtime/src/iree/hal/drivers/hexagon` and is neither included in the cmake build nor in the bazel build by default. This initial PR adds the part of the runtime for listing Hexagon devices and opening a Hexagon device. However, no functionality is provided by this device yet, so it immediately will fail with UNIMPLEMENTED. See `experimental/runtime/src/iree/hal/drivers/hexagon/README.md` for how to build the (partial) Hexagon runtime and how to test it. # Commits on this PR - **[Bazel] Add Android arm64 cross-compilation toolchain** Adds a C/C++ toolchain and platform for building the runtime for Android arm64 with the Android NDK r28 (API level 28): `bazel build --config=android_arm64 //tools:iree-run-module`. The NDK is located via the `ANDROID_NDK` (or `ANDROID_NDK_HOME`) environment variable. Without a configured NDK the repository is a stub and the toolchain targets are only analyzed for Android, so host builds are not affected. `iree_is_android` now also matches the Android platform in addition to `--define=iree_is_android=true`. - **[Hexagon] Add build support for the Hexagon SDK** Prepares building the experimental Hexagon HAL driver: - `@hexagon_sdk` repository (Bazel), downloading the free Hexagon SDK release or using an existing installation via `--repo_env=HEXAGON_SDK_ROOT`, and `iree_hexagon_sdk.cmake` (CMake, `HEXAGON_SDK_ROOT`). - `iree_hexagon_interface`: generates FastRPC stub/skel sources from IDL files with the SDK qaic compiler. - `iree_hexagon_dsp_library`: builds a FastRPC skeleton shared library for the DSP by invoking the SDK compiler directly. - `bazel_to_cmake` conversions for the above and for `experimental/runtime/src`, a package root mirroring `runtime/src`. - `experimental/runtime` is no longer ignored by Bazel. All Hexagon targets are restricted to Android aarch64, so host builds do not fetch the SDK. - **[Hexagon] Add FastRPC interface and DSP library** Adds the FastRPC interface between the Hexagon HAL driver on the Android host and the DSP (interface `hexagon_dsp : remote_handle64`, without any RPCs yet) and the DSP library `libhexagon_dsp_skel.so` for Hexagon v79, implementing opening and closing of the RPC session. - **[Hexagon] Add experimental Hexagon HAL driver** Adds the host side of the experimental Qualcomm Hexagon DSP HAL driver for Android aarch64. The driver lists the DSP domains supporting unsigned protection domains as devices. Creating a device opens a FastRPC session with the DSP, which loads `libhexagon_dsp_skel.so`. Allocation, executables, command buffers, and queue operations are not implemented yet and return `UNIMPLEMENTED`. Enable with: - `bazel build --config=hexagon //tools:iree-run-module` - `cmake ... -DIREE_EXTERNAL_HAL_DRIVERS=hexagon -DHEXAGON_SDK_ROOT=<path>` - **[Hexagon] Add README and code owners for the Hexagon HAL driver** Documents building, deploying, and manually verifying the experimental Hexagon HAL driver. # Local Testing Log of local testing with a OnePlus 13 phone: ``` ~/iree$ add push ../iree-build-android/tools/iree-run-module /data/local/tmp/schuermans-roofline/upstream/bin/ ../iree-build-android/tools/iree-run-module: 1 file pushed, 0 skipped. 333.6 MB/s (10283608 bytes in 0.029s) ~/iree$ adb push ../iree-build-android/experimental/runtime/src/iree/hal/drivers/hexagon/dsp/libhexagon_dsp_skel.so /data/local/tmp/schuermans-roofline/upstream/lib/hexagon ../iree-build-android/experimental/runtime/src/iree/hal/drivers/hexagon/dsp/libhexagon_dsp_skel.so: 1 file pushed, 0 skipped. 127.3 MB/s (9128 bytes in 0.000s) ~/iree$ adb shell 'cd /data/local/tmp/schuermans-roofline/upstream/; bin/iree-run-module --list_drivers' # ============================================================================ # Available HAL drivers # ============================================================================ # Use --list_devices={driver name} to enumerate available devices. local-sync: Local execution using a lightweight inline synchronous queue local-task: Local execution using the IREE multithreading task system vulkan: Vulkan HAL Rewrite Scaffold hexagon: Qualcomm Hexagon DSP (experimental) ~/iree$ adb shell 'cd /data/local/tmp/schuermans-roofline/upstream/; bin/iree-run-module --list_devices' local-sync:// local-task:// vulkan://GPU-435100000700000000d57000140000d5 hexagon://CDSP ~/iree$ adb shell 'cd /data/local/tmp/schuermans-roofline/upstream/; bin/iree-run-module --device=hexagon://CDSP --module=model.vmfb' iree/experimental/runtime/src/iree/hal/drivers/hexagon/device.c:586: UNIMPLEMENTED; hexagon executables not implemented; creating VM context; creating run context ~/iree$ ``` The last UNIMPLEMENTED error is expected for now, becuase the runtime implementation is still very incomplete. --------- Signed-off-by: Stefan Schuermans <schuermans@roofline.ai> Co-authored-by: L-roro <115032777+L-roro@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
diff --git a/.bazel_to_cmake.cfg.py b/.bazel_to_cmake.cfg.py index 4f6ad55..c686c14 100644 --- a/.bazel_to_cmake.cfg.py +++ b/.bazel_to_cmake.cfg.py
@@ -7,7 +7,15 @@ import bazel_to_cmake_converter import bazel_to_cmake_targets -DEFAULT_ROOT_DIRS = ["compiler", "core", "runtime", "samples", "tests", "tools"] +DEFAULT_ROOT_DIRS = [ + "compiler", + "core", + "experimental/runtime", + "runtime", + "samples", + "tests", + "tools", +] REPO_MAP = { # Since this is the @iree_core repo, map to empty since all internal @@ -65,6 +73,9 @@ { "//compiler/src:defs": [], "//runtime/src:runtime_defines": [], + # Handled by iree_setup_c_src_root() in + # experimental/runtime/src/CMakeLists.txt. + "//experimental/runtime/src:runtime_defines": [], } )
diff --git a/.bazelignore b/.bazelignore index d61886c..1652ac6 100644 --- a/.bazelignore +++ b/.bazelignore
@@ -5,9 +5,10 @@ # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # Ignore 'experimental' folders. These builds are not regularly maintained. -# If you wish to build/run a target under experimental/, you must remove this -# line from this file. -experimental +# If you wish to build/run a target under experimental/, you must remove its +# line from this file. experimental/runtime/ is built with Bazel, so it is not +# listed here. +experimental/hal_executable_library_call_hooks # Ignore third_party directories which contain BUILD files so that recursive # from root works.
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 8668d7a..3521cd6 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS
@@ -26,6 +26,7 @@ # Experimental # It's experimental, but we still don't want any old directory added here. /experimental/ @benvanik @jschuhmacher @maxbartel @stellaraccident +/experimental/runtime/src/iree/hal/drivers/hexagon/ @jschuhmacher @maxbartel @schuermans-roofline # Infra Top-Level Directories /.github/ @AGindinson @kuhar @schuermans-roofline
diff --git a/CMakeLists.txt b/CMakeLists.txt index b205be8..f146eee 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt
@@ -699,6 +699,8 @@ include(iree_c_embed_data) include(iree_amdgpu_binary) include(iree_bitcode_library) +include(iree_hexagon_dsp_library) +include(iree_hexagon_interface) include(iree_bytecode_module) include(iree_vmasm_module) include(iree_hal_executable) @@ -723,6 +725,25 @@ set(IREE_PACKAGE_ROOT_PREFIX "iree") #------------------------------------------------------------------------------- +# Experimental Qualcomm Hexagon DSP HAL driver (Android arm64 only). +# Enable with: -DIREE_EXTERNAL_HAL_DRIVERS=hexagon -DHEXAGON_SDK_ROOT=<path> +# See experimental/runtime/src/iree/hal/drivers/hexagon/README.md. +#------------------------------------------------------------------------------- + +iree_register_external_hal_driver( + NAME + hexagon + SOURCE_DIR + "${CMAKE_CURRENT_SOURCE_DIR}/experimental/runtime/src" + BINARY_DIR + "${CMAKE_CURRENT_BINARY_DIR}/experimental/runtime/src" + DRIVER_TARGET + iree::hal::drivers::hexagon::registration + REGISTER_FN + iree_hal_hexagon_driver_module_register +) + +#------------------------------------------------------------------------------- # IREE compilation flags #-------------------------------------------------------------------------------
diff --git a/MODULE.bazel b/MODULE.bazel index fd84fe3..9129c49 100644 --- a/MODULE.bazel +++ b/MODULE.bazel
@@ -87,9 +87,11 @@ "com_google_googletest", "dawn", "dlmalloc", + "hexagon_sdk", "hip_api_headers", "hsa_runtime_headers", "iree_amdgpu_device_toolchain", + "iree_android_ndk", "iree_cuda", "iree_external_hal_drivers", "llvm-raw", @@ -106,6 +108,14 @@ "webgpu_headers", ) +# Experimental Qualcomm Hexagon DSP HAL driver. Only built and registered with +# --config=hexagon, see experimental/runtime/src/iree/hal/drivers/hexagon. +iree_ext.external_hal_driver( + enabled_by = "//experimental/runtime/src/iree/hal/drivers/hexagon/registration:enabled", + register_fn = "iree_hal_hexagon_driver_module_register", + target = "//experimental/runtime/src/iree/hal/drivers/hexagon/registration", +) + # The LLVM overlay imports @llvm-raw from its own llvm_repos_extension, which # only generates it when the overlay is the root module. IREE is the root # module here, so inject IREE's @llvm-raw (created by iree_extension) into the @@ -137,3 +147,7 @@ name = "torch-mlir", src_workspace = "@torch-mlir-raw//:CMakeLists.txt", ) + +# Android aarch64 cross-compilation toolchain using the Android NDK. Only +# selected when building for the android_arm64 platform (--config=android_arm64). +register_toolchains("//build_tools/bazel/android:aarch64_android_toolchain")
diff --git a/build_tools/bazel/BUILD.bazel b/build_tools/bazel/BUILD.bazel index ec62cd5..7ad5e2f 100644 --- a/build_tools/bazel/BUILD.bazel +++ b/build_tools/bazel/BUILD.bazel
@@ -48,21 +48,18 @@ }, ) -# Detect Android from platform OS setting. config_setting( - name = "iree_is_android_platforms_os", - constraint_values = [ - "@platforms//os:android", - ], + name = "iree_is_android_platform", + constraint_values = ["@platforms//os:android"], ) -# Matches Android, either via the define or via the platform OS. Use this in -# select() conditions instead of the two settings above. +# Android, either via --define=iree_is_android=true with a user-provided +# toolchain or via an Android platform (e.g. --config=android_arm64). selects.config_setting_group( name = "iree_is_android", match_any = [ ":iree_is_android_define", - ":iree_is_android_platforms_os", + ":iree_is_android_platform", ], )
diff --git a/build_tools/bazel/android/BUILD.bazel b/build_tools/bazel/android/BUILD.bazel new file mode 100644 index 0000000..d2a45c5 --- /dev/null +++ b/build_tools/bazel/android/BUILD.bazel
@@ -0,0 +1,69 @@ +# Copyright 2026 The IREE Authors +# +# Licensed 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 + +# Android aarch64 cross-compilation using the Android NDK. +# +# Build with: bazel build --config=android_arm64 //tools:iree-run-module +# The NDK is located via ANDROID_NDK (see android_ndk_repo.bzl). + +load("@rules_cc//cc/toolchains:cc_toolchain.bzl", "cc_toolchain") +load(":aarch64_android_toolchain_config.bzl", "aarch64_android_toolchain_config") + +package( + default_visibility = ["//visibility:public"], + licenses = ["notice"], # Apache 2.0 +) + +platform( + name = "android_arm64", + constraint_values = [ + "@platforms//cpu:aarch64", + "@platforms//os:android", + ], +) + +filegroup( + name = "empty", + srcs = [], +) + +# Only analyzed for Android, so that host builds (e.g. `bazel build //...`) +# do not require the NDK. +_ANDROID_ARM64 = [ + "@platforms//cpu:aarch64", + "@platforms//os:android", +] + +aarch64_android_toolchain_config( + name = "aarch64_android_toolchain_config", + target_compatible_with = _ANDROID_ARM64, +) + +cc_toolchain( + name = "aarch64_android_cc_toolchain", + all_files = ":empty", + compiler_files = ":empty", + dwp_files = ":empty", + linker_files = ":empty", + objcopy_files = ":empty", + strip_files = ":empty", + supports_param_files = 0, + target_compatible_with = _ANDROID_ARM64, + toolchain_config = ":aarch64_android_toolchain_config", +) + +toolchain( + name = "aarch64_android_toolchain", + target_compatible_with = _ANDROID_ARM64, + toolchain = ":aarch64_android_cc_toolchain", + toolchain_type = "@bazel_tools//tools/cpp:toolchain_type", +) + +# libc++_shared.so from the NDK, to be deployed next to Android binaries. +alias( + name = "libcxx_shared", + actual = "@iree_android_ndk//:libcxx_shared", +)
diff --git a/build_tools/bazel/android/aarch64_android_toolchain_config.bzl b/build_tools/bazel/android/aarch64_android_toolchain_config.bzl new file mode 100644 index 0000000..6c59ce6 --- /dev/null +++ b/build_tools/bazel/android/aarch64_android_toolchain_config.bzl
@@ -0,0 +1,208 @@ +# Copyright 2026 The IREE Authors +# +# Licensed 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 + +"""C/C++ toolchain configuration for Android aarch64 using the Android NDK.""" + +load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") +load( + "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", + "feature", + "flag_group", + "flag_set", + "tool_path", +) +load( + "@iree_android_ndk//:defs.bzl", + "ANDROID_API_LEVEL", + "ANDROID_NDK_AVAILABLE", + "ANDROID_NDK_ERROR", + "ANDROID_NDK_LIB_CLANG_DIR", + "ANDROID_NDK_TOOLCHAIN_DIR", +) +load("@rules_cc//cc/common:cc_common.bzl", "cc_common") + +_COMPILE_ACTIONS = [ + ACTION_NAMES.c_compile, + ACTION_NAMES.cpp_compile, +] + +# Bazel selects the link action based on the target type: +# cpp_link_executable - cc_binary / cc_test +# cpp_link_dynamic_library - cc_binary(linkshared = True) +# cpp_link_nodeps_dynamic_library - .so Bazel creates for a cc_library +_EXECUTABLE_LINK_ACTIONS = [ + ACTION_NAMES.cpp_link_executable, +] +_DYNAMIC_LIBRARY_LINK_ACTIONS = [ + ACTION_NAMES.cpp_link_dynamic_library, + ACTION_NAMES.cpp_link_nodeps_dynamic_library, +] +_ALL_LINK_ACTIONS = _EXECUTABLE_LINK_ACTIONS + _DYNAMIC_LIBRARY_LINK_ACTIONS + +def _aarch64_android_toolchain_config_impl(ctx): + # The toolchain is only analyzed when building for Android, so a missing + # NDK does not affect host builds. + if not ANDROID_NDK_AVAILABLE: + fail(ANDROID_NDK_ERROR) + + target = "aarch64-linux-android" + ANDROID_API_LEVEL + bin_dir = ANDROID_NDK_TOOLCHAIN_DIR + "/bin" + sysroot_lib_dir = (ANDROID_NDK_TOOLCHAIN_DIR + + "/sysroot/usr/lib/aarch64-linux-android/" + + ANDROID_API_LEVEL) + + clang = bin_dir + "/" + target + "-clang" + tool_paths = [ + tool_path(name = "cpp", path = clang), + tool_path(name = "gcc", path = clang), + tool_path(name = "ld", path = bin_dir + "/ld.lld"), + ] + [ + tool_path(name = tool, path = bin_dir + "/llvm-" + tool) + for tool in ["ar", "nm", "objcopy", "objdump", "strip"] + ] + + arch_flags = feature( + name = "aarch64_arch_flags", + enabled = True, + flag_sets = [ + flag_set( + actions = _COMPILE_ACTIONS, + flag_groups = [flag_group(flags = ["-march=" + ctx.attr.march])], + ), + flag_set( + actions = [ + ACTION_NAMES.assemble, + ACTION_NAMES.preprocess_assemble, + ] + _ALL_LINK_ACTIONS, + flag_groups = [flag_group(flags = [ + "--target=" + target, + "-march=" + ctx.attr.march, + ])], + ), + ], + ) + + compile_flags = feature( + name = "android_compile_flags", + enabled = True, + flag_sets = [ + flag_set( + actions = _COMPILE_ACTIONS, + flag_groups = [flag_group(flags = [ + "-fPIC", + "-DANDROID", + ])], + ), + ], + ) + + # Enabled by "bazel build -c opt ...". + opt = feature( + name = "opt", + flag_sets = [ + flag_set( + actions = _COMPILE_ACTIONS, + flag_groups = [flag_group(flags = [ + "-O2", + "-DNDEBUG", + ])], + ), + ], + ) + + dbg = feature( + name = "dbg", + flag_sets = [ + flag_set( + actions = _COMPILE_ACTIONS, + flag_groups = [flag_group(flags = ["-g", "-O0"])], + ), + ], + ) + + linker_flags = feature( + name = "android_linker_flags", + enabled = True, + flag_sets = [ + flag_set( + actions = _ALL_LINK_ACTIONS, + flag_groups = [flag_group(flags = [ + "-Wl,-z,nocopyreloc", + "-Wl,-rpath-link=" + sysroot_lib_dir, + "-nostdlib", + "-Bdynamic", + "-L" + sysroot_lib_dir, + "-lc++", + "-lm", + "-lc", + "-ldl", + "-llog", + "-lunwind", + "-L" + ANDROID_NDK_LIB_CLANG_DIR + "/lib/linux", + "-lclang_rt.builtins-aarch64-android", + ])], + ), + flag_set( + actions = _EXECUTABLE_LINK_ACTIONS, + flag_groups = [flag_group(flags = [ + "-fPIE", + "-pie", + "-Wl,-dynamic-linker,/system/bin/linker64", + # Allows deploying libc++_shared.so in ../lib. + "-Wl,-rpath,$ORIGIN/../lib", + sysroot_lib_dir + "/crtbegin_dynamic.o", + sysroot_lib_dir + "/crtend_android.o", + ])], + ), + flag_set( + actions = _DYNAMIC_LIBRARY_LINK_ACTIONS, + flag_groups = [flag_group(flags = [ + "-fPIC", + "-Wl,-rpath,$ORIGIN/../lib", + "-Wl,-unresolved-symbols=ignore-in-shared-libs", + sysroot_lib_dir + "/crtbegin_so.o", + sysroot_lib_dir + "/crtend_so.o", + ])], + ), + ], + ) + + return cc_common.create_cc_toolchain_config_info( + ctx = ctx, + toolchain_identifier = "aarch64-android", + host_system_name = "local", + target_system_name = target, + target_cpu = "aarch64", + target_libc = "bionic", + compiler = "clang", + abi_version = "unknown", + abi_libc_version = "unknown", + tool_paths = tool_paths, + cxx_builtin_include_directories = [ + ANDROID_NDK_LIB_CLANG_DIR + "/include", + ANDROID_NDK_TOOLCHAIN_DIR + "/sysroot/usr/include/c++/v1", + ANDROID_NDK_TOOLCHAIN_DIR + "/sysroot/usr/include/aarch64-linux-android", + ANDROID_NDK_TOOLCHAIN_DIR + "/sysroot/usr/include", + ], + features = [ + arch_flags, + compile_flags, + opt, + dbg, + linker_flags, + ], + ) + +aarch64_android_toolchain_config = rule( + implementation = _aarch64_android_toolchain_config_impl, + attrs = { + "march": attr.string( + default = "armv8-a", + doc = "aarch64 architecture to target (e.g., armv8-a).", + ), + }, + provides = [CcToolchainConfigInfo], +)
diff --git a/build_tools/bazel/android/android_ndk_repo.bzl b/build_tools/bazel/android/android_ndk_repo.bzl new file mode 100644 index 0000000..1886e3a --- /dev/null +++ b/build_tools/bazel/android/android_ndk_repo.bzl
@@ -0,0 +1,131 @@ +# Copyright 2026 The IREE Authors +# +# Licensed 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 + +"""Repository rule detecting the Android NDK used for Android builds. + +The NDK is located via the `ANDROID_NDK` environment variable (the same one +used by the CMake Android build), falling back to `ANDROID_NDK_HOME`. + +The repository is always created. When no suitable NDK is found it is a stub +that records the reason in `ANDROID_NDK_ERROR`, so host builds never fail and +the error is only reported once something is actually built for Android (see +aarch64_android_toolchain_config.bzl). + +The repository provides: + - defs.bzl: Starlark constants describing the NDK. + - :libcxx_shared: libc++_shared.so from the NDK sysroot, which has to be + deployed next to binaries built with the NDK. +""" + +# Supported NDK release (r28c is 28.2.13676358). +ANDROID_NDK_MAJOR_VERSION = "28" + +# Android API level targeted by Bazel Android builds. +ANDROID_API_LEVEL = "28" + +_NDK_ENV_VARS = ["ANDROID_NDK", "ANDROID_NDK_HOME"] + +_LIBCXX_SHARED_REL_PATH = "sysroot/usr/lib/aarch64-linux-android/libc++_shared.so" + +def _host_tag(repository_ctx): + os_name = repository_ctx.os.name.lower() + if os_name.startswith("linux"): + return "linux-x86_64" + if os_name.startswith("mac os"): + return "darwin-x86_64" + return None + +def _find_ndk(repository_ctx): + """Returns (ndk_dir, error) for the NDK configured in the environment.""" + ndk_dir = None + for env_var in _NDK_ENV_VARS: + value = repository_ctx.getenv(env_var) + if value: + ndk_dir = value + break + if not ndk_dir: + return None, ("Android NDK not found: set ANDROID_NDK (or " + + "ANDROID_NDK_HOME) to an NDK r{} installation.").format( + ANDROID_NDK_MAJOR_VERSION, + ) + + source_properties = repository_ctx.path(ndk_dir + "/source.properties") + if not source_properties.exists: + return None, "Android NDK at '{}' has no source.properties.".format(ndk_dir) + revision = None + for line in repository_ctx.read(source_properties).splitlines(): + key, _, value = line.partition("=") + if key.strip() == "Pkg.Revision": + revision = value.strip() + if not revision or revision.split(".")[0] != ANDROID_NDK_MAJOR_VERSION: + return None, ("Android NDK at '{}' has revision '{}' but Bazel " + + "Android builds require NDK r{}.").format( + ndk_dir, + revision, + ANDROID_NDK_MAJOR_VERSION, + ) + + if not _host_tag(repository_ctx): + return None, "Android NDK builds are not supported on host '{}'.".format( + repository_ctx.os.name, + ) + return ndk_dir, None + +def _android_ndk_repo_impl(repository_ctx): + ndk_dir, error = _find_ndk(repository_ctx) + toolchain_dir = "" + lib_clang_dir = "" + libcxx_shared_srcs = [] + if ndk_dir: + toolchain_dir = "{}/toolchains/llvm/prebuilt/{}".format( + ndk_dir, + _host_tag(repository_ctx), + ) + + # lib/clang/ contains exactly one directory named after the version of + # the bundled clang. + lib_clang_dir = str(repository_ctx.path(toolchain_dir + "/lib/clang").readdir()[0]) + repository_ctx.symlink( + toolchain_dir + "/" + _LIBCXX_SHARED_REL_PATH, + "libc++_shared.so", + ) + libcxx_shared_srcs = ["libc++_shared.so"] + + repository_ctx.file("defs.bzl", content = """\ +# AUTO-GENERATED by android_ndk_repo.bzl - do not edit. + +ANDROID_NDK_AVAILABLE = {available} +ANDROID_NDK_ERROR = {error} +ANDROID_API_LEVEL = {api_level} +ANDROID_NDK_TOOLCHAIN_DIR = {toolchain_dir} +ANDROID_NDK_LIB_CLANG_DIR = {lib_clang_dir} +""".format( + available = ndk_dir != None, + error = repr(error or ""), + api_level = repr(ANDROID_API_LEVEL), + toolchain_dir = repr(toolchain_dir), + lib_clang_dir = repr(lib_clang_dir), + )) + + repository_ctx.file("BUILD.bazel", content = """\ +# AUTO-GENERATED by android_ndk_repo.bzl - do not edit. + +package(default_visibility = ["//visibility:public"]) + +exports_files(["defs.bzl"]) + +filegroup( + name = "libcxx_shared", + srcs = {libcxx_shared_srcs}, +) +""".format(libcxx_shared_srcs = repr(libcxx_shared_srcs))) + +android_ndk_repo = repository_rule( + implementation = _android_ndk_repo_impl, + environ = _NDK_ENV_VARS, + local = True, + doc = "Detects the Android NDK configured via ANDROID_NDK/ANDROID_NDK_HOME.", +)
diff --git a/build_tools/bazel/extensions.bzl b/build_tools/bazel/extensions.bzl index 1e1f403..a594aaa 100644 --- a/build_tools/bazel/extensions.bzl +++ b/build_tools/bazel/extensions.bzl
@@ -11,7 +11,9 @@ load("//build_tools/bazel:amdgpu_device_libs_repository.bzl", "amdgpu_device_libs_repository") load("//build_tools/bazel:amdgpu_device_toolchain_repo.bzl", "amdgpu_device_toolchain_repo") load("//build_tools/bazel:external_hal_drivers.bzl", "external_hal_driver_tag", "iree_external_hal_drivers_repo") +load("//build_tools/bazel:hexagon_sdk_repo.bzl", "hexagon_sdk_repo") load("//build_tools/bazel:workspace.bzl", "cuda_auto_configure") +load("//build_tools/bazel/android:android_ndk_repo.bzl", "android_ndk_repo") load("//build_tools/wasm:wasi_sdk_repo.bzl", "wasi_sdk_repo") def _iree_extension_impl(module_ctx): @@ -169,6 +171,18 @@ name = "iree_amdgpu_device_toolchain", ) + # Android NDK detection for Android cross-compilation. A stub when no NDK + # is configured; see build_tools/bazel/android/android_ndk_repo.bzl. + android_ndk_repo( + name = "iree_android_ndk", + ) + + # Hexagon SDK for the experimental Hexagon HAL driver. Only fetched when a + # Hexagon target is built. + hexagon_sdk_repo( + name = "hexagon_sdk", + ) + # wasi-sdk: clang + lld + wasi-libc + libc++ + compiler-rt for wasm targets. # Downloads the host-appropriate release from GitHub on first build. wasi_sdk_repo(
diff --git a/build_tools/bazel/hexagon_sdk_repo.bzl b/build_tools/bazel/hexagon_sdk_repo.bzl new file mode 100644 index 0000000..acc50a8 --- /dev/null +++ b/build_tools/bazel/hexagon_sdk_repo.bzl
@@ -0,0 +1,150 @@ +# Copyright 2026 The IREE Authors +# +# Licensed 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 + +"""Repository rule providing the Qualcomm Hexagon SDK. + +Used by the experimental Hexagon HAL driver +(experimental/runtime/src/iree/hal/drivers/hexagon). The repository is only +fetched when a Hexagon target is built. + +By default the free-to-download Hexagon SDK release is downloaded. An existing +SDK installation can be used instead with: + --repo_env=HEXAGON_SDK_ROOT=/path/to/hexagon-sdk +""" + +_HEXAGON_SDK_URL = "https://github.com/snapdragon-toolchain/hexagon-sdk/releases/download/v6.7.0.0/hexagon-sdk-v6.7.0.0-amd64-lnx.tar.xz" +_HEXAGON_SDK_SHA256 = "00725fc449916d7b9af2c2a3c6b54d61f3c872d5dbc1d3ca3fd2f839b1d5dc70" +_HEXAGON_SDK_STRIP_PREFIX = "6.7.0.0" + +_HEXAGON_ARCH = "v79" + +_BUILD_FILE = """\ +# AUTO-GENERATED by hexagon_sdk_repo.bzl - do not edit. + +load("@rules_cc//cc:cc_import.bzl", "cc_import") +load("@rules_cc//cc:cc_library.bzl", "cc_library") + +package(default_visibility = ["//visibility:public"]) + +# RPC interface compiler. +filegroup( + name = "qaic", + srcs = ["ipc/fastrpc/qaic/bin/qaic"], +) + +# IDL files included by RPC interface definitions. +filegroup( + name = "qaic_includes", + srcs = glob([ + "incs/*.idl", + "incs/stddef/*.idl", + ]), +) + +# FastRPC headers and client library for Android aarch64. The library itself +# is provided by the device at runtime. +cc_library( + name = "fastrpc_headers", + hdrs = glob([ + "incs/*.h", + "incs/stddef/*.h", + "ipc/fastrpc/rpcmem/inc/*.h", + ]), + includes = [ + "incs", + "incs/stddef", + "ipc/fastrpc/rpcmem/inc", + ], +) + +cc_import( + name = "cdsprpc_android_aarch64_import", + shared_library = "ipc/fastrpc/remote/ship/android_aarch64/libcdsprpc.so", +) + +cc_library( + name = "cdsprpc_android_aarch64", + deps = [ + ":cdsprpc_android_aarch64_import", + ":fastrpc_headers", + ], +) + +# Hexagon compiler driver used to build code running on the DSP. +filegroup( + name = "hexagon_clang", + srcs = ["{tools}/bin/hexagon-clang"], +) + +# Files used by hexagon-clang when compiling and linking for the DSP. +filegroup( + name = "hexagon_toolchain_files", + srcs = glob([ + "{tools}/bin/clang*", + "{tools}/bin/hexagon-clang", + "{tools}/bin/hexagon-link", + "{tools}/bin/ld.*", + "{tools}/lib/*.so*", + "{tools}/lib/clang/*/include/**", + "{tools}/target/hexagon/include/**", + "{tools}/target/hexagon/lib/{arch}/**", + ]), +) + +# Headers for code running on the DSP. +filegroup( + name = "dsp_headers", + srcs = glob([ + "incs/*.h", + "incs/stddef/*.h", + "rtos/qurt/compute{arch}/include/posix/**/*.h", + "rtos/qurt/compute{arch}/include/qurt/**/*.h", + ]), +) +""" + +def _find_tools_dir(repository_ctx): + """Returns the path of the Hexagon compiler toolchain in the SDK. + + The toolchain lives in tools/HEXAGON_Tools/<version>/Tools, where the + version differs between SDK releases (e.g. 19.0.04 in 6.4.0.2 and 21.0.04 + in 6.7.0.0). Picks the newest version if there are several. + Must be kept in sync with build_tools/cmake/iree_hexagon_sdk.cmake. + """ + tools_root = repository_ctx.path("tools/HEXAGON_Tools") + versions = [entry.basename for entry in tools_root.readdir()] if tools_root.exists else [] + if not versions: + fail("No compiler toolchain found in tools/HEXAGON_Tools of the Hexagon SDK.") + newest = sorted( + versions, + key = lambda version: [int(part) if part.isdigit() else 0 for part in version.split(".")], + )[-1] + return "tools/HEXAGON_Tools/{}/Tools".format(newest) + +def _hexagon_sdk_repo_impl(repository_ctx): + sdk_root = repository_ctx.getenv("HEXAGON_SDK_ROOT") + if sdk_root: + sdk_path = repository_ctx.path(sdk_root) + if not sdk_path.exists: + fail("HEXAGON_SDK_ROOT '{}' does not exist.".format(sdk_root)) + for entry in sdk_path.readdir(): + repository_ctx.symlink(entry, entry.basename) + else: + repository_ctx.download_and_extract( + url = _HEXAGON_SDK_URL, + sha256 = _HEXAGON_SDK_SHA256, + stripPrefix = _HEXAGON_SDK_STRIP_PREFIX, + ) + repository_ctx.file("BUILD.bazel", content = _BUILD_FILE.format( + tools = _find_tools_dir(repository_ctx), + arch = _HEXAGON_ARCH, + )) + +hexagon_sdk_repo = repository_rule( + implementation = _hexagon_sdk_repo_impl, + environ = ["HEXAGON_SDK_ROOT"], + doc = "Downloads (or symlinks via HEXAGON_SDK_ROOT) the Hexagon SDK.", +)
diff --git a/build_tools/bazel/iree.bazelrc b/build_tools/bazel/iree.bazelrc index 0e0b607..bf02d8f 100644 --- a/build_tools/bazel/iree.bazelrc +++ b/build_tools/bazel/iree.bazelrc
@@ -72,6 +72,23 @@ build:localdev --experimental_merged_skyframe_analysis_execution ############################################################################### +# Android aarch64 cross-compilation using the Android NDK r28 found via the +# ANDROID_NDK (or ANDROID_NDK_HOME) environment variable. +# Use with: bazel build --config=android_arm64 //tools:iree-run-module +############################################################################### + +build:android_arm64 --platforms=//build_tools/bazel/android:android_arm64 + +############################################################################### +# Experimental Qualcomm Hexagon DSP HAL driver for Android aarch64, see +# experimental/runtime/src/iree/hal/drivers/hexagon/README.md. +# Use with: bazel build --config=hexagon //tools:iree-run-module +############################################################################### + +build:hexagon --config=android_arm64 +build:hexagon --//experimental/runtime/src/iree/hal/drivers/hexagon/registration:enable + +############################################################################### # Options for "generic_gcc" builds ###############################################################################
diff --git a/build_tools/bazel/iree_hexagon_dsp_library.bzl b/build_tools/bazel/iree_hexagon_dsp_library.bzl new file mode 100644 index 0000000..c41b9a5 --- /dev/null +++ b/build_tools/bazel/iree_hexagon_dsp_library.bzl
@@ -0,0 +1,100 @@ +# Copyright 2026 The IREE Authors +# +# Licensed 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 + +"""Rules for building shared libraries running on the Hexagon DSP. + +The Hexagon SDK compiler is invoked directly (similar to iree_amdgpu_binary) +instead of via a cc_toolchain, as the libraries only contain self-contained C +sources. See build_tools/cmake/iree_hexagon_dsp_library.cmake for the CMake +equivalent. +""" + +def iree_hexagon_dsp_library( + name, + srcs, + interface, + arch = "v79", + copts = [], + linkopts = [], + **kwargs): + """Builds a FastRPC skeleton shared library (lib<name>.so) for the DSP. + + Args: + name: Name of the target; the output is lib<name>.so. + srcs: C sources and headers implementing the interface. + interface: iree_hexagon_interface target whose skeleton is linked in. + arch: Hexagon architecture version (e.g. v79). + copts: Additional flags passed to hexagon-clang when compiling. + linkopts: Additional flags passed to hexagon-clang when linking. + **kwargs: Additional attributes passed to the genrule. + """ + + # The library is deployed with the Hexagon driver on Android aarch64 + # devices. Restricting it to that platform keeps host builds (e.g. + # `bazel build //...`) from fetching the Hexagon SDK. + kwargs.setdefault("target_compatible_with", [ + "@platforms//cpu:aarch64", + "@platforms//os:android", + ]) + clang = "@hexagon_sdk//:hexagon_clang" + skel_srcs = interface + "_skel_srcs" + out = "lib{}.so".format(name) + + # The SDK root is 5 levels above tools/HEXAGON_Tools/<ver>/Tools/bin. + sdk_dir = "$$(dirname $(location {}))/../../../../..".format(clang) + base_copts = [ + "-m" + arch, + "-G0", + "-fpic", + "-O2", + "-Wall", + # FastRPC loads the skeleton via dlopen and looks up + # <interface>_skel_handle_invoke, so symbols have to be exported. + "-fvisibility=default", + "-I$${interface_dir}", + "-I" + sdk_dir + "/incs", + "-I" + sdk_dir + "/incs/stddef", + "-I" + sdk_dir + "/rtos/qurt/compute" + arch + "/include/qurt", + "-I" + sdk_dir + "/rtos/qurt/compute" + arch + "/include/posix", + ] + base_linkopts = [ + "-m" + arch, + "-G0", + "-fpic", + "-shared", + "-Wl,-Bsymbolic", + ] + + object_dir = "$(@D)/{}.objects".format(name) + native.genrule( + name = name, + srcs = srcs + [skel_srcs, "@hexagon_sdk//:dsp_headers"], + outs = [out], + cmd = " && ".join([ + "set -e", + "object_dir=\"{}\"".format(object_dir), + "rm -rf \"$${object_dir}\"", + "mkdir -p \"$${object_dir}\"", + "interface_dir=\"\"", + "for src in $(locations {}); do case \"$${{src}}\" in *.h) interface_dir=$$(dirname \"$${{src}}\");; esac; done".format(skel_srcs), + "object_index=0", + "for src in $(locations {}) {}; do case \"$${{src}}\" in *.c) {} -c \"$${{src}}\" -o \"$${{object_dir}}/$${{object_index}}.o\"; object_index=$$((object_index + 1));; esac; done".format( + skel_srcs, + " ".join(["$(locations {})".format(src) for src in srcs]), + " ".join(["$(location {})".format(clang)] + base_copts + copts), + ), + " ".join(["$(location {})".format(clang)] + base_linkopts + linkopts + [ + "\"$${object_dir}\"/*.o", + "-o $(location {})".format(out), + ]), + ]), + tools = [ + clang, + "@hexagon_sdk//:hexagon_toolchain_files", + ], + message = "Building Hexagon DSP library {}...".format(out), + **kwargs + )
diff --git a/build_tools/bazel/iree_hexagon_interface.bzl b/build_tools/bazel/iree_hexagon_interface.bzl new file mode 100644 index 0000000..ea01277 --- /dev/null +++ b/build_tools/bazel/iree_hexagon_interface.bzl
@@ -0,0 +1,115 @@ +# Copyright 2026 The IREE Authors +# +# Licensed 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 + +"""Rules for generating Hexagon FastRPC interfaces with the qaic IDL compiler. + +See build_tools/cmake/iree_hexagon_interface.cmake for the CMake equivalent. +""" + +load("@rules_cc//cc:cc_library.bzl", "cc_library") + +# The Hexagon driver runs on Android aarch64 devices. Restricting all targets +# to that platform keeps host builds (e.g. `bazel build //...`) from fetching +# the Hexagon SDK. +_TARGET_COMPATIBLE_WITH = [ + "@platforms//cpu:aarch64", + "@platforms//os:android", +] + +def _iree_hexagon_qaic_impl(ctx): + include_dirs = [] + for include in ctx.files._qaic_includes: + include_dir = include.dirname + if include_dir not in include_dirs: + include_dirs.append(include_dir) + + basename = ctx.file.idl.basename.removesuffix(".idl") + header = ctx.actions.declare_file("{}/{}.h".format(ctx.attr.out_dir, basename)) + stub = ctx.actions.declare_file("{}/{}_stub.c".format(ctx.attr.out_dir, basename)) + skel = ctx.actions.declare_file("{}/{}_skel.c".format(ctx.attr.out_dir, basename)) + ctx.actions.run( + executable = ctx.file._qaic, + arguments = ["-mdll", "-o", header.dirname] + + ["-I" + include_dir for include_dir in include_dirs] + + [ctx.file.idl.path], + inputs = [ctx.file.idl] + ctx.files._qaic_includes, + outputs = [header, stub, skel], + mnemonic = "HexagonQaic", + progress_message = "Generating Hexagon RPC interface from %{input}", + ) + return [ + DefaultInfo(files = depset([header, stub, skel])), + OutputGroupInfo( + header = depset([header]), + stub = depset([stub]), + skel = depset([skel]), + ), + ] + +_iree_hexagon_qaic = rule( + implementation = _iree_hexagon_qaic_impl, + attrs = { + "idl": attr.label(allow_single_file = [".idl"], mandatory = True), + "out_dir": attr.string(mandatory = True), + "_qaic": attr.label( + default = "@hexagon_sdk//:qaic", + allow_single_file = True, + executable = True, + cfg = "exec", + ), + "_qaic_includes": attr.label( + default = "@hexagon_sdk//:qaic_includes", + allow_files = True, + ), + }, +) + +def iree_hexagon_interface(name, idl, **kwargs): + """Generates a Hexagon FastRPC interface from an IDL file. + + Creates the following targets: + name: cc_library with the generated header and the client stub for + Android aarch64 (the host calling into the DSP). + name_skel_srcs: filegroup with the generated header and DSP skeleton + source, consumed by iree_hexagon_dsp_library. + + Args: + name: Name of the interface; also names the output directory. + idl: The *.idl interface definition. + **kwargs: Additional attributes passed to all generated targets. + """ + kwargs.setdefault("target_compatible_with", _TARGET_COMPATIBLE_WITH) + _iree_hexagon_qaic( + name = name + "_gen", + idl = idl, + out_dir = name, + **kwargs + ) + for group in ["header", "stub", "skel"]: + native.filegroup( + name = "{}_{}".format(name, group), + srcs = [":{}_gen".format(name)], + output_group = group, + **kwargs + ) + native.filegroup( + name = name + "_skel_srcs", + srcs = [ + ":{}_header".format(name), + ":{}_skel".format(name), + ], + **kwargs + ) + cc_library( + name = name, + srcs = [":{}_stub".format(name)], + hdrs = [":{}_header".format(name)], + # The generated code is not warning-free. + copts = ["-w"], + includes = [name], + deps = ["@hexagon_sdk//:cdsprpc_android_aarch64"], + **kwargs + )
diff --git a/build_tools/bazel_to_cmake/bazel_to_cmake_converter.py b/build_tools/bazel_to_cmake/bazel_to_cmake_converter.py index 17685e5..6b91438 100644 --- a/build_tools/bazel_to_cmake/bazel_to_cmake_converter.py +++ b/build_tools/bazel_to_cmake/bazel_to_cmake_converter.py
@@ -43,6 +43,7 @@ "@platforms//os:macos": "Darwin", "@platforms//os:windows": "Windows", # CPU architecture constraints. + "@platforms//cpu:aarch64": "arm_64", "@platforms//cpu:wasm32": "wasm_32", } @@ -1245,6 +1246,37 @@ f")\n\n" ) + def iree_hexagon_interface(self, name, idl, **kwargs): + name_block = self._convert_string_arg_block("NAME", name, quote=False) + idl_block = self._convert_string_arg_block("IDL", idl) + + self._converter.body += ( + f"iree_hexagon_interface(\n" f"{name_block}" f"{idl_block}" f")\n\n" + ) + + def iree_hexagon_dsp_library( + self, name, srcs, interface, arch="v79", copts=None, linkopts=None, **kwargs + ): + name_block = self._convert_string_arg_block("NAME", name, quote=False) + interface_block = self._convert_target_block("INTERFACE", interface) + arch_block = self._convert_string_arg_block("ARCH", arch, quote=False) + srcs_block = self._convert_srcs_block(srcs) + copts_block = self._convert_string_list_block("COPTS", copts, sort=False) + linkopts_block = self._convert_string_list_block( + "LINKOPTS", linkopts, sort=False + ) + + self._converter.body += ( + f"iree_hexagon_dsp_library(\n" + f"{name_block}" + f"{interface_block}" + f"{arch_block}" + f"{srcs_block}" + f"{copts_block}" + f"{linkopts_block}" + f")\n\n" + ) + def iree_hal_amdgpu_source_device_binaries(self): self._converter.body += ( "# Source-built AMDGPU device binary targets are wired manually by\n"
diff --git a/build_tools/bazel_to_cmake/bazel_to_cmake_targets.py b/build_tools/bazel_to_cmake/bazel_to_cmake_targets.py index 81473e3..3d9462d 100644 --- a/build_tools/bazel_to_cmake/bazel_to_cmake_targets.py +++ b/build_tools/bazel_to_cmake/bazel_to_cmake_targets.py
@@ -182,6 +182,11 @@ "@com_google_googletest//:gtest": ["gmock", "gtest"], "@spirv_cross//:spirv_cross_lib": ["spirv-cross-msl"], "@hsa_runtime_headers": ["hsa_runtime::headers"], + # Hexagon SDK (see build_tools/cmake/iree_hexagon_sdk.cmake). + "@hexagon_sdk//:cdsprpc_android_aarch64": [ + "hexagon_sdk::cdsprpc_android_aarch64" + ], + "@hexagon_sdk//:fastrpc_headers": ["hexagon_sdk::fastrpc_headers"], "@libbacktrace": ["libbacktrace::libbacktrace"], "@webgpu_headers": [], # py_binary targets have no CMake equivalent. @@ -301,6 +306,13 @@ if m: return ["iree::" + self._convert_to_cmake_path(m.group(1))] + # Map //experimental/runtime/src/iree/(.*) -> iree::\1 + # experimental/runtime/src/ is a separate package root that mirrors + # runtime/src/ (see experimental/runtime/src/CMakeLists.txt). + m = re.match(f"^{iree_core_repo}//experimental/runtime/src/iree/(.+)", target) + if m: + return ["iree::" + self._convert_to_cmake_path(m.group(1))] + # Map //tools:(.*) -> \1 m = re.match(f"^{iree_core_repo}//tools[|:](.+)", target) if m:
diff --git a/build_tools/cmake/iree_hexagon_dsp_library.cmake b/build_tools/cmake/iree_hexagon_dsp_library.cmake new file mode 100644 index 0000000..5498cfe --- /dev/null +++ b/build_tools/cmake/iree_hexagon_dsp_library.cmake
@@ -0,0 +1,126 @@ +# Copyright 2026 The IREE Authors +# +# Licensed 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(CMakeParseArguments) + +# Builds a FastRPC skeleton shared library (lib${NAME}.so) for the Hexagon DSP +# by invoking the Hexagon SDK compiler directly. Requires +# build_tools/cmake/iree_hexagon_sdk.cmake. +# +# CMake equivalent of build_tools/bazel/iree_hexagon_dsp_library.bzl. +# +# Parameters: +# NAME: Name of the target; the output is lib${NAME}.so. +# INTERFACE: Target created by iree_hexagon_interface() whose skeleton is +# linked in. +# ARCH: Hexagon architecture version (e.g. v79). +# SRCS: C sources and headers implementing the interface. +# COPTS: Additional flags passed to hexagon-clang when compiling. +# LINKOPTS: Additional flags passed to hexagon-clang when linking. +function(iree_hexagon_dsp_library) + cmake_parse_arguments( + _RULE + "" + "NAME;INTERFACE;ARCH" + "SRCS;COPTS;LINKOPTS" + ${ARGN} + ) + + iree_package_name(_PACKAGE_NAME) + + if(NOT _RULE_ARCH) + set(_RULE_ARCH "v79") + endif() + + # The interface target may be defined in a directory processed after this + # one, so its properties are read with generator expressions. + set(_INTERFACE_DIR + "$<TARGET_PROPERTY:${_RULE_INTERFACE},IREE_HEXAGON_INTERFACE_DIR>") + set(_INTERFACE_HEADER + "$<TARGET_PROPERTY:${_RULE_INTERFACE},IREE_HEXAGON_INTERFACE_HEADER>") + set(_INTERFACE_SKEL + "$<TARGET_PROPERTY:${_RULE_INTERFACE},IREE_HEXAGON_INTERFACE_SKEL>") + + set(_CLANG "${IREE_HEXAGON_TOOLS_DIR}/bin/hexagon-clang") + set(_COPTS + "-m${_RULE_ARCH}" + "-G0" + "-fpic" + "-O2" + "-Wall" + # FastRPC loads the skeleton via dlopen and looks up + # <interface>_skel_handle_invoke, so symbols have to be exported. + "-fvisibility=default" + "-I${_INTERFACE_DIR}" + "-I${HEXAGON_SDK_ROOT}/incs" + "-I${HEXAGON_SDK_ROOT}/incs/stddef" + "-I${HEXAGON_SDK_ROOT}/rtos/qurt/compute${_RULE_ARCH}/include/qurt" + "-I${HEXAGON_SDK_ROOT}/rtos/qurt/compute${_RULE_ARCH}/include/posix" + ${_RULE_COPTS} + ) + set(_LINKOPTS + "-m${_RULE_ARCH}" + "-G0" + "-fpic" + "-shared" + "-Wl,-Bsymbolic" + ${_RULE_LINKOPTS} + ) + + # Headers invalidate all objects; .c files are compiled. The generated + # interface skeleton is compiled as <name>.objects/interface_skel.o. + set(_HDRS "${_INTERFACE_HEADER}") + set(_C_SRCS "${_INTERFACE_SKEL}") + set(_C_SRC_NAMES "interface_skel") + foreach(_SRC ${_RULE_SRCS}) + get_filename_component(_SRC "${_SRC}" ABSOLUTE) + if(_SRC MATCHES "\\.c$") + get_filename_component(_SRC_NAME "${_SRC}" NAME_WE) + list(APPEND _C_SRCS "${_SRC}") + list(APPEND _C_SRC_NAMES "${_SRC_NAME}") + else() + list(APPEND _HDRS "${_SRC}") + endif() + endforeach() + + set(_OBJECT_DIR "${CMAKE_CURRENT_BINARY_DIR}/${_RULE_NAME}.objects") + set(_OBJECTS) + foreach(_SRC _SRC_NAME IN ZIP_LISTS _C_SRCS _C_SRC_NAMES) + set(_OBJECT "${_OBJECT_DIR}/${_SRC_NAME}.o") + add_custom_command( + OUTPUT + "${_OBJECT}" + COMMAND + "${CMAKE_COMMAND}" -E make_directory "${_OBJECT_DIR}" + COMMAND + "${_CLANG}" ${_COPTS} -c "${_SRC}" -o "${_OBJECT}" + DEPENDS + "${_SRC}" + ${_HDRS} + COMMENT "Compiling ${_SRC_NAME} for the Hexagon DSP" + VERBATIM + ) + list(APPEND _OBJECTS "${_OBJECT}") + endforeach() + + set(_OUT "${CMAKE_CURRENT_BINARY_DIR}/lib${_RULE_NAME}.so") + add_custom_command( + OUTPUT + "${_OUT}" + COMMAND + "${_CLANG}" ${_LINKOPTS} ${_OBJECTS} -o "${_OUT}" + DEPENDS + ${_OBJECTS} + COMMENT "Linking Hexagon DSP library lib${_RULE_NAME}.so" + VERBATIM + ) + add_custom_target(${_PACKAGE_NAME}_${_RULE_NAME} ALL + DEPENDS + "${_OUT}" + ) + # Name of the target generating the interface, see iree_hexagon_interface(). + add_dependencies(${_PACKAGE_NAME}_${_RULE_NAME} ${_RULE_INTERFACE}_gen) +endfunction()
diff --git a/build_tools/cmake/iree_hexagon_interface.cmake b/build_tools/cmake/iree_hexagon_interface.cmake new file mode 100644 index 0000000..2005847 --- /dev/null +++ b/build_tools/cmake/iree_hexagon_interface.cmake
@@ -0,0 +1,89 @@ +# Copyright 2026 The IREE Authors +# +# Licensed 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(CMakeParseArguments) + +# Generates a Hexagon FastRPC interface from an IDL file with the Hexagon SDK +# qaic IDL compiler. Requires build_tools/cmake/iree_hexagon_sdk.cmake. +# +# CMake equivalent of build_tools/bazel/iree_hexagon_interface.bzl. +# +# Parameters: +# NAME: Name of the interface. Creates a library ${NAME} with the generated +# header and the client stub for Android aarch64 (the host calling into +# the DSP). The generated DSP skeleton is consumed by +# iree_hexagon_dsp_library(INTERFACE ...). The IDL file and the interface +# defined in it must be named ${NAME}. +# IDL: The *.idl interface definition. +function(iree_hexagon_interface) + cmake_parse_arguments( + _RULE + "" + "NAME;IDL" + "" + ${ARGN} + ) + + iree_package_name(_PACKAGE_NAME) + + get_filename_component(_IDL "${_RULE_IDL}" ABSOLUTE) + set(_OUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/${_RULE_NAME}") + set(_HEADER "${_OUT_DIR}/${_RULE_NAME}.h") + set(_STUB "${_OUT_DIR}/${_RULE_NAME}_stub.c") + set(_SKEL "${_OUT_DIR}/${_RULE_NAME}_skel.c") + + file(MAKE_DIRECTORY "${_OUT_DIR}") + add_custom_command( + OUTPUT + "${_HEADER}" + "${_STUB}" + "${_SKEL}" + COMMAND + hexagon_sdk::qaic + -mdll + -o "${_OUT_DIR}" + "-I${HEXAGON_SDK_ROOT}/incs" + "-I${HEXAGON_SDK_ROOT}/incs/stddef" + "${_IDL}" + DEPENDS + "${_IDL}" + hexagon_sdk::qaic + COMMENT "Generating Hexagon RPC interface from ${_RULE_IDL}" + VERBATIM + ) + set(_GEN_TARGET "${_PACKAGE_NAME}_${_RULE_NAME}_gen") + add_custom_target(${_GEN_TARGET} + DEPENDS + "${_HEADER}" + "${_STUB}" + "${_SKEL}" + ) + + iree_cc_library( + NAME + ${_RULE_NAME} + HDRS + "${_HEADER}" + SRCS + "${_STUB}" + COPTS + # The generated code is not warning-free. + "-w" + DEPS + hexagon_sdk::cdsprpc_android_aarch64 + INCLUDES + "$<BUILD_INTERFACE:${_OUT_DIR}>" + PUBLIC + ) + add_dependencies(${_PACKAGE_NAME}_${_RULE_NAME} ${_GEN_TARGET}) + + # Used by iree_hexagon_dsp_library(). + set_target_properties(${_PACKAGE_NAME}_${_RULE_NAME} PROPERTIES + IREE_HEXAGON_INTERFACE_DIR "${_OUT_DIR}" + IREE_HEXAGON_INTERFACE_HEADER "${_HEADER}" + IREE_HEXAGON_INTERFACE_SKEL "${_SKEL}" + ) +endfunction()
diff --git a/build_tools/cmake/iree_hexagon_sdk.cmake b/build_tools/cmake/iree_hexagon_sdk.cmake new file mode 100644 index 0000000..63155bc --- /dev/null +++ b/build_tools/cmake/iree_hexagon_sdk.cmake
@@ -0,0 +1,63 @@ +# Copyright 2026 The IREE Authors +# +# Licensed 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 + +# Locates the Qualcomm Hexagon SDK and defines imported targets for it. +# +# Used by the experimental Hexagon HAL driver +# (experimental/runtime/src/iree/hal/drivers/hexagon). The SDK location is +# taken from the HEXAGON_SDK_ROOT CMake or environment variable. +# +# Must be kept in sync with build_tools/bazel/hexagon_sdk_repo.bzl. + +if(TARGET hexagon_sdk::qaic) + return() +endif() + +set(HEXAGON_SDK_ROOT "$ENV{HEXAGON_SDK_ROOT}" CACHE PATH + "Path to the Qualcomm Hexagon SDK") +if(NOT HEXAGON_SDK_ROOT OR NOT EXISTS "${HEXAGON_SDK_ROOT}/incs/remote.h") + message(FATAL_ERROR + "The Hexagon HAL driver requires the Qualcomm Hexagon SDK. Set " + "HEXAGON_SDK_ROOT to the SDK directory (got '${HEXAGON_SDK_ROOT}'). The " + "SDK can be downloaded from https://github.com/snapdragon-toolchain/hexagon-sdk/releases") +endif() + +# The compiler toolchain lives in tools/HEXAGON_Tools/<version>/Tools, where the +# version differs between SDK releases (e.g. 19.0.04 in 6.4.0.2 and 21.0.04 in +# 6.7.0.0). Pick the newest version if there are several. +file(GLOB _HEXAGON_TOOLS_VERSIONS LIST_DIRECTORIES true + RELATIVE "${HEXAGON_SDK_ROOT}/tools/HEXAGON_Tools" + "${HEXAGON_SDK_ROOT}/tools/HEXAGON_Tools/*") +if(NOT _HEXAGON_TOOLS_VERSIONS) + message(FATAL_ERROR + "No compiler toolchain found in ${HEXAGON_SDK_ROOT}/tools/HEXAGON_Tools") +endif() +list(SORT _HEXAGON_TOOLS_VERSIONS COMPARE NATURAL ORDER DESCENDING) +list(GET _HEXAGON_TOOLS_VERSIONS 0 _HEXAGON_TOOLS_VERSION) +set(IREE_HEXAGON_TOOLS_DIR + "${HEXAGON_SDK_ROOT}/tools/HEXAGON_Tools/${_HEXAGON_TOOLS_VERSION}/Tools" + CACHE INTERNAL "Hexagon compiler toolchain directory in the Hexagon SDK") + +# RPC interface compiler. +add_executable(hexagon_sdk::qaic IMPORTED GLOBAL) +set_target_properties(hexagon_sdk::qaic PROPERTIES + IMPORTED_LOCATION "${HEXAGON_SDK_ROOT}/ipc/fastrpc/qaic/bin/qaic" +) + +# FastRPC headers and client library for Android aarch64. The library itself is +# provided by the device at runtime. +add_library(hexagon_sdk::fastrpc_headers INTERFACE IMPORTED GLOBAL) +set_target_properties(hexagon_sdk::fastrpc_headers PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES + "${HEXAGON_SDK_ROOT}/incs;${HEXAGON_SDK_ROOT}/incs/stddef;${HEXAGON_SDK_ROOT}/ipc/fastrpc/rpcmem/inc" +) + +add_library(hexagon_sdk::cdsprpc_android_aarch64 SHARED IMPORTED GLOBAL) +set_target_properties(hexagon_sdk::cdsprpc_android_aarch64 PROPERTIES + IMPORTED_LOCATION + "${HEXAGON_SDK_ROOT}/ipc/fastrpc/remote/ship/android_aarch64/libcdsprpc.so" + INTERFACE_LINK_LIBRARIES hexagon_sdk::fastrpc_headers +)
diff --git a/docs/website/docs/building-from-source/android.md b/docs/website/docs/building-from-source/android.md index 6daa9a1..2b68002 100644 --- a/docs/website/docs/building-from-source/android.md +++ b/docs/website/docs/building-from-source/android.md
@@ -110,6 +110,23 @@ The specific `ANDROID_ABI` and `ANDROID_PLATFORM` used should match your target device. +### Building with Bazel + +The runtime can also be built for Android arm64 with Bazel. This requires +Android NDK r28 (e.g. r28c) with the `ANDROID_NDK` (or `ANDROID_NDK_HOME`) +environment variable set to its location. Binaries target Android API level +28. + +``` shell +bazel build --config=android_arm64 //tools:iree-run-module +``` + +Binaries built with Bazel link the shared C++ library of the NDK. Push +`libc++_shared.so` from +`${ANDROID_NDK}/toolchains/llvm/prebuilt/<host>/sysroot/usr/lib/aarch64-linux-android/` +to the device into a `lib/` directory next to the `bin/` directory containing +the binaries. + ## :octicons-code-16: Running Android tests Make sure you
diff --git a/experimental/runtime/src/BUILD.bazel b/experimental/runtime/src/BUILD.bazel new file mode 100644 index 0000000..b5f8797 --- /dev/null +++ b/experimental/runtime/src/BUILD.bazel
@@ -0,0 +1,22 @@ +# Copyright 2026 The IREE Authors +# +# Licensed 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 + +load("//build_tools/bazel:build_defs.oss.bzl", "iree_cc_library") + +package( + default_visibility = ["//visibility:public"], + features = ["layering_check"], + licenses = ["notice"], # Apache 2.0 +) + +# Experimental runtime code mirroring the runtime/src/ layout. Makes includes +# like "iree/hal/drivers/hexagon/api.h" resolve relative to this directory. +iree_cc_library( + name = "runtime_defines", + includes = [ + ".", + ], +)
diff --git a/experimental/runtime/src/CMakeLists.txt b/experimental/runtime/src/CMakeLists.txt new file mode 100644 index 0000000..93cc373 --- /dev/null +++ b/experimental/runtime/src/CMakeLists.txt
@@ -0,0 +1,25 @@ +# Copyright 2026 The IREE Authors +# +# Licensed 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 + +# Experimental runtime code mirroring the runtime/src/ layout. Package names +# start here, e.g. iree/hal/drivers/hexagon/ -> iree::hal::drivers::hexagon. +# +# Included via the external HAL driver registration of the experimental Hexagon +# HAL driver in the root CMakeLists.txt (-DIREE_EXTERNAL_HAL_DRIVERS=hexagon). + +iree_setup_c_src_root( + DEFAULT_EXPORT_SET Runtime + DEFAULT_INSTALL_COMPONENT IREEDevLibraries-Runtime + IMPLICIT_DEFS_TARGET iree_experimental_runtime_defs +) + +if(NOT CMAKE_SYSTEM_NAME STREQUAL "Android" OR NOT IREE_ARCH STREQUAL "arm_64") + message(FATAL_ERROR + "The experimental Hexagon HAL driver requires an Android arm64 build; see " + "experimental/runtime/src/iree/hal/drivers/hexagon/README.md") +endif() +include(iree_hexagon_sdk) +add_subdirectory(iree/hal/drivers/hexagon)
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/BUILD.bazel b/experimental/runtime/src/iree/hal/drivers/hexagon/BUILD.bazel new file mode 100644 index 0000000..e5b379e --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/BUILD.bazel
@@ -0,0 +1,45 @@ +# Copyright 2026 The IREE Authors +# +# Licensed 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 + +load("//build_tools/bazel:build_defs.oss.bzl", "iree_runtime_cc_library") + +package( + default_visibility = ["//visibility:public"], + features = ["layering_check"], + licenses = ["notice"], # Apache 2.0 +) + +# Experimental Qualcomm Hexagon DSP HAL driver. Runs on Android aarch64 hosts. +iree_runtime_cc_library( + name = "hexagon", + srcs = [ + "allocator.c", + "allocator.h", + "device.c", + "device.h", + "driver.c", + "driver.h", + "rpc_types.c", + "rpc_types.h", + "utils.c", + "utils.h", + ], + hdrs = [ + "api.h", + ], + target_compatible_with = [ + "@platforms//cpu:aarch64", + "@platforms//os:android", + ], + deps = [ + "//experimental/runtime/src:runtime_defines", + "//experimental/runtime/src/iree/hal/drivers/hexagon/interface:hexagon_dsp", + "//runtime/src/iree/async", + "//runtime/src/iree/base", + "//runtime/src/iree/hal", + "@hexagon_sdk//:fastrpc_headers", + ], +)
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/CMakeLists.txt b/experimental/runtime/src/iree/hal/drivers/hexagon/CMakeLists.txt new file mode 100644 index 0000000..12e9d8e --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/CMakeLists.txt
@@ -0,0 +1,40 @@ +################################################################################ +# Autogenerated by build_tools/bazel_to_cmake/bazel_to_cmake.py from # +# experimental/runtime/src/iree/hal/drivers/hexagon/BUILD.bazel # +# # +# Use iree_cmake_extra_content from iree/build_defs.oss.bzl to add arbitrary # +# CMake-only content. # +# # +# To disable autogeneration for this file entirely, delete this header. # +################################################################################ + +iree_add_all_subdirs() + +if(IREE_ARCH STREQUAL "arm_64" AND CMAKE_SYSTEM_NAME STREQUAL "Android") +iree_cc_library( + NAME + hexagon + HDRS + "api.h" + SRCS + "allocator.c" + "allocator.h" + "device.c" + "device.h" + "driver.c" + "driver.h" + "rpc_types.c" + "rpc_types.h" + "utils.c" + "utils.h" + DEPS + hexagon_sdk::fastrpc_headers + iree::async + iree::base + iree::hal + iree::hal::drivers::hexagon::interface::hexagon_dsp + PUBLIC +) +endif() + +### BAZEL_TO_CMAKE_PRESERVES_ALL_CONTENT_BELOW_THIS_LINE ###
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/README.md b/experimental/runtime/src/iree/hal/drivers/hexagon/README.md new file mode 100644 index 0000000..a5585fe --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/README.md
@@ -0,0 +1,148 @@ +# Qualcomm Hexagon DSP HAL driver (`hexagon`) + +**Experimental.** A HAL driver running programs on the Hexagon DSP of Qualcomm +Snapdragon SoCs from an Android aarch64 host via FastRPC. + +Status: the driver lists the DSP domains of the device and creates devices, +which opens a FastRPC session with the DSP. Buffers, executables, command +buffers, and queue operations are not implemented yet and fail with +`UNIMPLEMENTED`. + +## Directory structure + +- `.`: host side of the driver (Android aarch64). +- `registration/`: registration of the driver with the HAL driver registry. +- `interface/`: FastRPC interface definition (`hexagon_dsp.idl`). The Hexagon + SDK `qaic` compiler generates the host stub and the DSP skeleton from it. +- `dsp/`: DSP side, built as `libhexagon_dsp_skel.so` for Hexagon v79. + +## Prerequisites + +- An Android device with a Snapdragon SoC whose compute DSP (CDSP) allows + unsigned protection domains (e.g. Snapdragon 8 Elite / SM8750). +- [Android NDK r28](https://developer.android.com/ndk/downloads) (tested with + r28c, `28.2.13676358`) with `ANDROID_NDK` set to its location. +- The [Qualcomm Hexagon SDK](https://github.com/snapdragon-toolchain/hexagon-sdk/releases) + (free download, see its license). Tested with 6.7.0.0, which Bazel downloads + automatically, and 6.4.0.2. + +## Building + +### Bazel + +```shell +export ANDROID_NDK=/path/to/android-ndk-r28c +bazel build --config=hexagon \ + //tools:iree-run-module \ + //experimental/runtime/src/iree/hal/drivers/hexagon/dsp:hexagon_dsp_skel +``` + +`--config=hexagon` builds for Android aarch64 and links the driver into the +tools. To use an existing Hexagon SDK installation instead of downloading it, +add `--repo_env=HEXAGON_SDK_ROOT=/path/to/hexagon-sdk`. + +### CMake + +Build the host tools as described in the +[Android cross-compilation guide](https://iree.dev/building-from-source/android/), +then configure the Android build with the driver enabled: + +```shell +cmake -GNinja -B ../iree-build-android/ \ + -DCMAKE_TOOLCHAIN_FILE="${ANDROID_NDK?}/build/cmake/android.toolchain.cmake" \ + -DIREE_HOST_BIN_DIR="$PWD/../iree-build/install/bin" \ + -DANDROID_ABI="arm64-v8a" \ + -DANDROID_PLATFORM="android-28" \ + -DIREE_BUILD_COMPILER=OFF \ + -DIREE_EXTERNAL_HAL_DRIVERS=hexagon \ + -DHEXAGON_SDK_ROOT=/path/to/hexagon-sdk \ + . +cmake --build ../iree-build-android/ --target \ + iree-run-module iree_hal_drivers_hexagon_dsp_hexagon_dsp_skel +``` + +The DSP library is built at +`experimental/runtime/src/iree/hal/drivers/hexagon/dsp/libhexagon_dsp_skel.so` +in the build directory. + +## Deployment + +The driver loads the DSP library from `../lib/hexagon/` relative to the +directory of the running executable: + +```text +<dir>/bin/iree-run-module +<dir>/lib/hexagon/libhexagon_dsp_skel.so +<dir>/lib/libc++_shared.so (Bazel builds only, from the NDK sysroot) +``` + +```shell +adb shell mkdir -p /data/local/tmp/iree/bin /data/local/tmp/iree/lib/hexagon +adb push iree-run-module /data/local/tmp/iree/bin/ +adb push libhexagon_dsp_skel.so /data/local/tmp/iree/lib/hexagon/ +adb push "${ANDROID_NDK}/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/lib/aarch64-linux-android/libc++_shared.so" \ + /data/local/tmp/iree/lib/ +``` + +## Devices + +Each DSP domain that supports unsigned protection domains is a device: + +```text +$ iree-run-module --list_devices=hexagon +hexagon://CDSP +``` + +Devices are selected by domain name (`hexagon://CDSP`) or domain ID +(`hexagon://3`). `hexagon://` selects the CDSP. Device parameters: + +| Parameter | Description | +| --- | --- | +| `verbose=1` | Prints diagnostics such as the FastRPC session URI to stderr. | +| `dsp_status_notify=1` | Prints DSP protection domain status changes to stderr. | + +Example: `--device="hexagon://CDSP?verbose=1&dsp_status_notify=1"`. + +## Manual verification + +There are no automated tests yet. On a device: + +1. Listing devices: + + ```shell + adb shell 'cd /data/local/tmp/iree && bin/iree-run-module --list_devices=hexagon' + ``` + + Expected output: `hexagon://CDSP`. + +2. Opening a device: `--list_devices` does not create devices. The tools only + create devices for modules that import the `hal` module, so compile a small + module for any target on the host: + + ```mlir + func.func @main(%arg0: tensor<4xf32>) -> tensor<4xf32> { + %0 = arith.addf %arg0, %arg0 : tensor<4xf32> + return %0 : tensor<4xf32> + } + ``` + + ```shell + iree-compile --iree-hal-target-device=local \ + --iree-hal-local-target-device-backends=vmvx add.mlir -o add.vmfb + adb push add.vmfb /data/local/tmp/iree/ + adb shell 'cd /data/local/tmp/iree && bin/iree-run-module \ + --device="hexagon://CDSP?verbose=1&dsp_status_notify=1" \ + --module=add.vmfb --function=main --input=4xf32=1,2,3,4' + ``` + + Expected output: the device opens the session, the DSP library is loaded + (`adb logcat` shows `libhexagon_dsp_skel.so` being opened), and the run + then fails as executables are not implemented yet: + + ```text + hexagon: opening DSP session 'file:////data/local/tmp/iree/bin/../lib/hexagon/libhexagon_dsp_skel.so?hexagon_dsp_skel_handle_invoke&_modver=1.0&_idlver=0.1.0&_dom=cdsp' + hexagon: DSP CDSP status: PD is up + hexagon: DSP CDSP status: PD closed + hexagon: closed DSP session (result 0x0) + .../hexagon/device.c:...: UNIMPLEMENTED; hexagon executables not implemented; creating VM context; creating run context + ```
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/allocator.c b/experimental/runtime/src/iree/hal/drivers/hexagon/allocator.c new file mode 100644 index 0000000..13a77d6 --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/allocator.c
@@ -0,0 +1,245 @@ +// Copyright 2026 The IREE Authors +// +// Licensed 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 "iree/hal/drivers/hexagon/allocator.h" + +//===----------------------------------------------------------------------===// +// iree_hal_hexagon_allocator_t +//===----------------------------------------------------------------------===// + +typedef struct iree_hal_hexagon_allocator_t { + iree_hal_resource_t resource; + iree_allocator_t host_allocator; +} iree_hal_hexagon_allocator_t; + +static const iree_hal_allocator_vtable_t iree_hal_hexagon_allocator_vtable; + +static iree_hal_hexagon_allocator_t* iree_hal_hexagon_allocator_cast( + iree_hal_allocator_t* base_value) { + IREE_HAL_ASSERT_TYPE(base_value, &iree_hal_hexagon_allocator_vtable); + return (iree_hal_hexagon_allocator_t*)base_value; +} + +iree_status_t iree_hal_hexagon_allocator_create( + iree_allocator_t host_allocator, iree_hal_allocator_t** out_allocator) { + IREE_ASSERT_ARGUMENT(out_allocator); + IREE_TRACE_ZONE_BEGIN(z0); + *out_allocator = NULL; + + iree_hal_hexagon_allocator_t* allocator = NULL; + IREE_RETURN_AND_END_ZONE_IF_ERROR( + z0, iree_allocator_malloc(host_allocator, sizeof(*allocator), + (void**)&allocator)); + iree_hal_resource_initialize(&iree_hal_hexagon_allocator_vtable, + &allocator->resource); + allocator->host_allocator = host_allocator; + + *out_allocator = (iree_hal_allocator_t*)allocator; + IREE_TRACE_ZONE_END(z0); + return iree_ok_status(); +} + +static void iree_hal_hexagon_allocator_destroy( + iree_hal_allocator_t* IREE_RESTRICT base_allocator) { + IREE_ASSERT_ARGUMENT(base_allocator); + iree_hal_hexagon_allocator_t* allocator = + iree_hal_hexagon_allocator_cast(base_allocator); + IREE_TRACE_ZONE_BEGIN(z0); + + iree_allocator_free(allocator->host_allocator, allocator); + + IREE_TRACE_ZONE_END(z0); +} + +static iree_allocator_t iree_hal_hexagon_allocator_host_allocator( + const iree_hal_allocator_t* IREE_RESTRICT base_allocator) { + iree_hal_hexagon_allocator_t* allocator = + (iree_hal_hexagon_allocator_t*)base_allocator; + return allocator->host_allocator; +} + +static iree_status_t iree_hal_hexagon_allocator_trim( + iree_hal_allocator_t* IREE_RESTRICT base_allocator) { + return iree_ok_status(); +} + +static void iree_hal_hexagon_allocator_query_statistics( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + iree_hal_allocator_statistics_t* IREE_RESTRICT out_statistics) { + memset(out_statistics, 0, sizeof(*out_statistics)); +} + +static iree_status_t iree_hal_hexagon_allocator_query_memory_heaps( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + iree_host_size_t capacity, + iree_hal_allocator_memory_heap_t* IREE_RESTRICT heaps, + iree_host_size_t* IREE_RESTRICT out_count) { + // TODO(hexagon): report the heaps once buffer allocation is implemented. + *out_count = 0; + return iree_ok_status(); +} + +static iree_hal_buffer_compatibility_t +iree_hal_hexagon_allocator_query_buffer_compatibility( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + iree_hal_buffer_params_t* IREE_RESTRICT params, + iree_device_size_t* IREE_RESTRICT allocation_size) { + // TODO(hexagon): set compatibility rules once buffer allocation is + // implemented. + return IREE_HAL_BUFFER_COMPATIBILITY_NONE; +} + +static iree_status_t iree_hal_hexagon_allocator_allocate_buffer( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + const iree_hal_buffer_params_t* IREE_RESTRICT params, + iree_device_size_t allocation_size, + iree_hal_buffer_t** IREE_RESTRICT out_buffer) { + *out_buffer = NULL; + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon buffer allocation not implemented"); +} + +static void iree_hal_hexagon_allocator_deallocate_buffer( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + iree_hal_buffer_t* IREE_RESTRICT base_buffer) { + // No buffers are ever allocated from this allocator. + iree_hal_buffer_destroy(base_buffer); +} + +static iree_status_t iree_hal_hexagon_allocator_import_buffer( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + const iree_hal_buffer_params_t* IREE_RESTRICT params, + iree_hal_external_buffer_t* IREE_RESTRICT external_buffer, + iree_hal_buffer_release_callback_t release_callback, + iree_hal_buffer_t** IREE_RESTRICT out_buffer) { + *out_buffer = NULL; + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon buffer import not implemented"); +} + +static iree_status_t iree_hal_hexagon_allocator_export_buffer( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + iree_hal_buffer_t* IREE_RESTRICT buffer, + iree_hal_external_buffer_type_t requested_type, + iree_hal_external_buffer_flags_t requested_flags, + iree_hal_external_buffer_t* IREE_RESTRICT out_external_buffer) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon buffer export not implemented"); +} + +static bool iree_hal_hexagon_allocator_supports_virtual_memory( + iree_hal_allocator_t* IREE_RESTRICT base_allocator) { + return false; +} + +static iree_status_t +iree_hal_hexagon_allocator_virtual_memory_query_granularity( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + iree_hal_buffer_params_t params, + iree_device_size_t* IREE_RESTRICT out_minimum_page_size, + iree_device_size_t* IREE_RESTRICT out_recommended_page_size) { + *out_minimum_page_size = 0; + *out_recommended_page_size = 0; + return iree_make_status(IREE_STATUS_UNAVAILABLE, + "hexagon allocator does not support virtual memory"); +} + +static iree_status_t iree_hal_hexagon_allocator_virtual_memory_reserve( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + iree_hal_queue_affinity_t queue_affinity, iree_device_size_t size, + iree_hal_buffer_t** IREE_RESTRICT out_virtual_buffer) { + *out_virtual_buffer = NULL; + return iree_make_status(IREE_STATUS_UNAVAILABLE, + "hexagon allocator does not support virtual memory"); +} + +static iree_status_t iree_hal_hexagon_allocator_virtual_memory_release( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + iree_hal_buffer_t* IREE_RESTRICT virtual_buffer) { + return iree_make_status(IREE_STATUS_UNAVAILABLE, + "hexagon allocator does not support virtual memory"); +} + +static iree_status_t iree_hal_hexagon_allocator_physical_memory_allocate( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + iree_hal_buffer_params_t params, iree_device_size_t size, + iree_allocator_t host_allocator, + iree_hal_physical_memory_t** IREE_RESTRICT out_physical_memory) { + *out_physical_memory = NULL; + return iree_make_status(IREE_STATUS_UNAVAILABLE, + "hexagon allocator does not support virtual memory"); +} + +static iree_status_t iree_hal_hexagon_allocator_physical_memory_free( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + iree_hal_physical_memory_t* IREE_RESTRICT physical_memory) { + return iree_make_status(IREE_STATUS_UNAVAILABLE, + "hexagon allocator does not support virtual memory"); +} + +static iree_status_t iree_hal_hexagon_allocator_virtual_memory_map( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + iree_hal_buffer_t* IREE_RESTRICT virtual_buffer, + iree_device_size_t virtual_offset, + iree_hal_physical_memory_t* IREE_RESTRICT physical_memory, + iree_device_size_t physical_offset, iree_device_size_t size) { + return iree_make_status(IREE_STATUS_UNAVAILABLE, + "hexagon allocator does not support virtual memory"); +} + +static iree_status_t iree_hal_hexagon_allocator_virtual_memory_unmap( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + iree_hal_buffer_t* IREE_RESTRICT virtual_buffer, + iree_device_size_t virtual_offset, iree_device_size_t size) { + return iree_make_status(IREE_STATUS_UNAVAILABLE, + "hexagon allocator does not support virtual memory"); +} + +static iree_status_t iree_hal_hexagon_allocator_virtual_memory_protect( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + iree_hal_buffer_t* IREE_RESTRICT virtual_buffer, + iree_device_size_t virtual_offset, iree_device_size_t size, + iree_hal_queue_affinity_t queue_affinity, + iree_hal_memory_protection_t protection) { + return iree_make_status(IREE_STATUS_UNAVAILABLE, + "hexagon allocator does not support virtual memory"); +} + +static iree_status_t iree_hal_hexagon_allocator_virtual_memory_advise( + iree_hal_allocator_t* IREE_RESTRICT base_allocator, + iree_hal_buffer_t* IREE_RESTRICT virtual_buffer, + iree_device_size_t virtual_offset, iree_device_size_t size, + iree_hal_queue_affinity_t queue_affinity, iree_hal_memory_advice_t advice) { + return iree_make_status(IREE_STATUS_UNAVAILABLE, + "hexagon allocator does not support virtual memory"); +} + +static const iree_hal_allocator_vtable_t iree_hal_hexagon_allocator_vtable = { + .destroy = iree_hal_hexagon_allocator_destroy, + .host_allocator = iree_hal_hexagon_allocator_host_allocator, + .trim = iree_hal_hexagon_allocator_trim, + .query_statistics = iree_hal_hexagon_allocator_query_statistics, + .query_memory_heaps = iree_hal_hexagon_allocator_query_memory_heaps, + .query_buffer_compatibility = + iree_hal_hexagon_allocator_query_buffer_compatibility, + .allocate_buffer = iree_hal_hexagon_allocator_allocate_buffer, + .deallocate_buffer = iree_hal_hexagon_allocator_deallocate_buffer, + .import_buffer = iree_hal_hexagon_allocator_import_buffer, + .export_buffer = iree_hal_hexagon_allocator_export_buffer, + .supports_virtual_memory = + iree_hal_hexagon_allocator_supports_virtual_memory, + .virtual_memory_query_granularity = + iree_hal_hexagon_allocator_virtual_memory_query_granularity, + .virtual_memory_reserve = iree_hal_hexagon_allocator_virtual_memory_reserve, + .virtual_memory_release = iree_hal_hexagon_allocator_virtual_memory_release, + .physical_memory_allocate = + iree_hal_hexagon_allocator_physical_memory_allocate, + .physical_memory_free = iree_hal_hexagon_allocator_physical_memory_free, + .virtual_memory_map = iree_hal_hexagon_allocator_virtual_memory_map, + .virtual_memory_unmap = iree_hal_hexagon_allocator_virtual_memory_unmap, + .virtual_memory_protect = iree_hal_hexagon_allocator_virtual_memory_protect, + .virtual_memory_advise = iree_hal_hexagon_allocator_virtual_memory_advise, +};
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/allocator.h b/experimental/runtime/src/iree/hal/drivers/hexagon/allocator.h new file mode 100644 index 0000000..dab5726 --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/allocator.h
@@ -0,0 +1,25 @@ +// Copyright 2026 The IREE Authors +// +// Licensed 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 IREE_HAL_DRIVERS_HEXAGON_ALLOCATOR_H_ +#define IREE_HAL_DRIVERS_HEXAGON_ALLOCATOR_H_ + +#include "iree/base/api.h" +#include "iree/hal/api.h" + +//===----------------------------------------------------------------------===// +// iree_hal_hexagon_allocator_t +//===----------------------------------------------------------------------===// + +// Creates a Hexagon buffer allocator. +// +// Buffer allocation is not implemented yet: the allocator has no memory heaps +// and all allocation, import, and export requests fail with +// IREE_STATUS_UNIMPLEMENTED. +iree_status_t iree_hal_hexagon_allocator_create( + iree_allocator_t host_allocator, iree_hal_allocator_t** out_allocator); + +#endif // IREE_HAL_DRIVERS_HEXAGON_ALLOCATOR_H_
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/api.h b/experimental/runtime/src/iree/hal/drivers/hexagon/api.h new file mode 100644 index 0000000..2e5142d --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/api.h
@@ -0,0 +1,88 @@ +// Copyright 2026 The IREE Authors +// +// Licensed 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 + +// See iree/base/api.h for documentation on the API conventions used. + +#ifndef IREE_HAL_DRIVERS_HEXAGON_API_H_ +#define IREE_HAL_DRIVERS_HEXAGON_API_H_ + +#include "iree/base/api.h" +#include "iree/hal/api.h" + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +//===----------------------------------------------------------------------===// +// iree_hal_hexagon_device_t +//===----------------------------------------------------------------------===// + +// Hexagon DSP domain ID as defined by the Hexagon SDK (e.g. CDSP_DOMAIN_ID). +typedef int iree_hal_hexagon_domain_id_t; + +// Parameters configuring an iree_hal_hexagon_device_t. +// Must be initialized with iree_hal_hexagon_device_options_initialize prior to +// use. +typedef struct iree_hal_hexagon_device_options_t { + // Prints diagnostic information (e.g. the DSP session URI) to stderr. + int verbose; + // Prints notifications about DSP process domain status changes to stderr. + int dsp_status_notify; +} iree_hal_hexagon_device_options_t; + +// Initializes |out_options| to default values. +IREE_API_EXPORT void iree_hal_hexagon_device_options_initialize( + iree_hal_hexagon_device_options_t* out_options); + +// Creates a Qualcomm Hexagon HAL device on the DSP with the given |domain_id| +// and |options|. This opens a FastRPC session on the DSP that loads the +// device-side library (libhexagon_dsp_skel.so). +// +// The provided |identifier| will be used by programs to distinguish the device +// type from other HAL implementations. If compiling programs with the IREE +// compiler this must match the value used by `IREE::HAL::TargetDevice`. +// +// |out_device| must be released by the caller (see iree_hal_device_release). +IREE_API_EXPORT iree_status_t iree_hal_hexagon_device_create( + iree_string_view_t identifier, iree_hal_hexagon_domain_id_t domain_id, + const iree_hal_hexagon_device_options_t* options, + const iree_hal_device_create_params_t* create_params, + iree_allocator_t host_allocator, iree_hal_device_t** out_device); + +//===----------------------------------------------------------------------===// +// iree_hal_hexagon_driver_t +//===----------------------------------------------------------------------===// + +// Parameters for configuring an iree_hal_hexagon_driver_t. +// Must be initialized with iree_hal_hexagon_driver_options_initialize prior to +// use. +typedef struct iree_hal_hexagon_driver_options_t { + // Default device options when none are provided during device creation. + iree_hal_hexagon_device_options_t default_device_options; +} iree_hal_hexagon_driver_options_t; + +// Initializes the given |out_options| with default driver creation options. +IREE_API_EXPORT void iree_hal_hexagon_driver_options_initialize( + iree_hal_hexagon_driver_options_t* out_options); + +// Creates a Qualcomm Hexagon HAL driver with the given |options|, from which +// Hexagon devices can be enumerated and created with specific parameters. +// +// The provided |identifier| will be used by programs to distinguish the device +// type from other HAL implementations. If compiling programs with the IREE +// compiler this must match the value used by `IREE::HAL::TargetDevice`. +// +// |out_driver| must be released by the caller (see iree_hal_driver_release). +IREE_API_EXPORT iree_status_t iree_hal_hexagon_driver_create( + iree_string_view_t identifier, + const iree_hal_hexagon_driver_options_t* options, + iree_allocator_t host_allocator, iree_hal_driver_t** out_driver); + +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + +#endif // IREE_HAL_DRIVERS_HEXAGON_API_H_
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/device.c b/experimental/runtime/src/iree/hal/drivers/hexagon/device.c new file mode 100644 index 0000000..2626b01 --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/device.c
@@ -0,0 +1,807 @@ +// Copyright 2026 The IREE Authors +// +// Licensed 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 "iree/hal/drivers/hexagon/device.h" + +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +#include "iree/async/frontier.h" +#include "iree/async/frontier_tracker.h" +#include "iree/hal/drivers/hexagon/allocator.h" +#include "iree/hal/drivers/hexagon/rpc_types.h" +#include "iree/hal/drivers/hexagon/utils.h" + +// Hexagon SDK headers. +#include "AEEStdErr.h" +#include "remote.h" + +// Generated from interface/hexagon_dsp.idl. +#include "hexagon_dsp.h" + +//===----------------------------------------------------------------------===// +// Hexagon DSP domains +//===----------------------------------------------------------------------===// + +// LOOKUP_HEXAGON_DOMAIN(domain ID, domain name, FastRPC URI domain suffix) +#define LOOKUP_HEXAGON_DOMAINS \ + LOOKUP_HEXAGON_DOMAIN(ADSP_DOMAIN_ID, "ADSP", ADSP_DOMAIN) \ + LOOKUP_HEXAGON_DOMAIN(MDSP_DOMAIN_ID, "MDSP", MDSP_DOMAIN) \ + LOOKUP_HEXAGON_DOMAIN(SDSP_DOMAIN_ID, "SDSP", SDSP_DOMAIN) \ + LOOKUP_HEXAGON_DOMAIN(CDSP_DOMAIN_ID, "CDSP", CDSP_DOMAIN) \ + LOOKUP_HEXAGON_DOMAIN(CDSP1_DOMAIN_ID, "CDSP1", CDSP1_DOMAIN) + +bool iree_hal_hexagon_get_domain_name(iree_hal_hexagon_domain_id_t domain_id, + const char** out_name) { + switch (domain_id) { +#define LOOKUP_HEXAGON_DOMAIN(id, name, uri_suffix) \ + case id: \ + *out_name = name; \ + return true; + LOOKUP_HEXAGON_DOMAINS +#undef LOOKUP_HEXAGON_DOMAIN + default: + return false; + } +} + +bool iree_hal_hexagon_get_domain_id( + iree_string_view_t name, iree_hal_hexagon_domain_id_t* out_domain_id) { +#define LOOKUP_HEXAGON_DOMAIN(id, check_name, uri_suffix) \ + if (iree_string_view_equal(name, IREE_SV(check_name))) { \ + *out_domain_id = id; \ + return true; \ + } + LOOKUP_HEXAGON_DOMAINS +#undef LOOKUP_HEXAGON_DOMAIN + return false; +} + +// Returns the FastRPC URI suffix selecting the DSP domain with |domain_id| +// (e.g. "&_dom=cdsp") in |out_uri_suffix|. Returns false if the domain is +// unknown. +static bool iree_hal_hexagon_get_domain_uri_suffix( + iree_hal_hexagon_domain_id_t domain_id, const char** out_uri_suffix) { + switch (domain_id) { +#define LOOKUP_HEXAGON_DOMAIN(id, name, uri_suffix) \ + case id: \ + *out_uri_suffix = uri_suffix; \ + return true; + LOOKUP_HEXAGON_DOMAINS +#undef LOOKUP_HEXAGON_DOMAIN + default: + return false; + } +} + +void iree_hal_hexagon_fill_device_info( + iree_hal_hexagon_domain_id_t domain_id, + iree_hal_device_info_t* out_device_info) { + const char* name = "unknown"; + iree_hal_hexagon_get_domain_name(domain_id, &name); + out_device_info->device_id = + iree_hal_hexagon_device_id_from_domain_id(domain_id); + out_device_info->name = iree_make_cstring_view(name); + out_device_info->path = out_device_info->name; +} + +//===----------------------------------------------------------------------===// +// iree_hal_hexagon_device_options_t +//===----------------------------------------------------------------------===// + +IREE_API_EXPORT void iree_hal_hexagon_device_options_initialize( + iree_hal_hexagon_device_options_t* out_options) { + memset(out_options, 0, sizeof(*out_options)); +} + +static iree_status_t iree_hal_hexagon_device_options_verify( + const iree_hal_hexagon_device_options_t* options) { + return iree_ok_status(); +} + +//===----------------------------------------------------------------------===// +// iree_hal_hexagon_device_t +//===----------------------------------------------------------------------===// + +typedef struct iree_hal_hexagon_device_t { + iree_hal_resource_t resource; + iree_string_view_t identifier; + + // DSP domain the device runs on. + iree_hal_hexagon_domain_id_t domain_id; + + // Options the device was created with. + iree_hal_hexagon_device_options_t options; + + iree_allocator_t host_allocator; + iree_hal_allocator_t* device_allocator; + + // FastRPC session with the DSP or 0 if not opened. + rpc_session_handle_t rpc_session_handle; + + // Shared frontier tracker for cross-device causal ordering. Retained after + // topology assignment and released during device destruction. + iree_async_frontier_tracker_t* frontier_tracker; + + // This device's axis for frontier tracking. + iree_async_axis_t axis; + + // Optional provider used for creating/configuring collective channels. + iree_hal_channel_provider_t* channel_provider; + + // Topology information if this device is part of a multi-device topology. + iree_hal_device_topology_info_t topology_info; + + // + trailing identifier string storage +} iree_hal_hexagon_device_t; + +static const iree_hal_device_vtable_t iree_hal_hexagon_device_vtable; + +static iree_hal_hexagon_device_t* iree_hal_hexagon_device_cast( + iree_hal_device_t* base_value) { + IREE_HAL_ASSERT_TYPE(base_value, &iree_hal_hexagon_device_vtable); + return (iree_hal_hexagon_device_t*)base_value; +} + +// Prints DSP process domain status changes to stderr. +static int iree_hal_hexagon_device_status_notification( + void* context, int domain_id, int session, + remote_rpc_status_flags_t status) { + const char* status_str = "unknown status"; + switch (status) { + case FASTRPC_USER_PD_UP: + status_str = "PD is up"; + break; + case FASTRPC_USER_PD_EXIT: + status_str = "PD closed"; + break; + case FASTRPC_USER_PD_FORCE_KILL: + status_str = "PD force kill"; + break; + case FASTRPC_USER_PD_EXCEPTION: + status_str = "PD exception"; + break; + case FASTRPC_DSP_SSR: + status_str = "DSP subsystem restart"; + break; + case FASTRPC_USERPD_TIMEOUT: + status_str = "PD timeout"; + break; + default: + break; + } + const char* domain_name = "unknown"; + iree_hal_hexagon_get_domain_name(domain_id, &domain_name); + fprintf(stderr, "hexagon: DSP %s status: %s\n", domain_name, status_str); + return AEE_SUCCESS; +} + +// Registers iree_hal_hexagon_device_status_notification for the DSP domain. +static iree_status_t iree_hal_hexagon_device_request_status_notifications( + iree_hal_hexagon_domain_id_t domain_id) { + struct remote_dsp_capability capability = { + .domain = (uint32_t)domain_id, + .attribute_ID = STATUS_NOTIFICATION_SUPPORT, + .capability = 0, + }; + int dsp_err = remote_handle_control(DSPRPC_GET_DSP_INFO, &capability, + sizeof(capability)); + if ((dsp_err & 0xFF) == (AEE_EUNSUPPORTEDAPI & 0xFF)) { + return iree_make_status(IREE_STATUS_UNAVAILABLE, + "FastRPC capability API is not supported"); + } else if (dsp_err != AEE_SUCCESS) { + return IREE_HAL_HEXAGON_MAKE_STATUS_FROM_DSP_ERR( + dsp_err, "querying DSP status notification support failed"); + } else if (capability.capability != 1) { + return iree_make_status(IREE_STATUS_UNAVAILABLE, + "DSP status notifications are not supported"); + } + + // The device is not passed as context as notifications may arrive after it + // has been destroyed (e.g. when the session is closed). + struct remote_rpc_notif_register notification = { + .context = NULL, + .domain = domain_id, + .notifier_fn = iree_hal_hexagon_device_status_notification, + }; + dsp_err = remote_session_control(FASTRPC_REGISTER_STATUS_NOTIFICATIONS, + ¬ification, sizeof(notification)); + if (dsp_err != AEE_SUCCESS) { + return IREE_HAL_HEXAGON_MAKE_STATUS_FROM_DSP_ERR( + dsp_err, "enabling DSP status notifications failed"); + } + return iree_ok_status(); +} + +// Returns the directory of the running executable including a trailing slash +// in |out_binary_dir|. The caller must free it with |host_allocator|. +static iree_status_t iree_hal_hexagon_get_binary_dir( + iree_allocator_t host_allocator, char** out_binary_dir) { + *out_binary_dir = NULL; + + // Resolve the executable symlink, growing the buffer until the path fits. + char* path = NULL; + iree_host_size_t capacity = 256; + ssize_t length = 0; + while (true) { + IREE_RETURN_IF_ERROR(iree_allocator_malloc_uninitialized( + host_allocator, capacity, (void**)&path)); + length = readlink("/proc/self/exe", path, capacity); + if (length < 0) { + iree_status_t status = IREE_HAL_HEXAGON_MAKE_STATUS_FROM_ERRNO( + "resolving the path of the executable failed"); + iree_allocator_free(host_allocator, path); + return status; + } + // readlink() silently truncates, so a path filling the whole buffer may + // have been truncated. + if ((iree_host_size_t)length < capacity) break; + iree_allocator_free(host_allocator, path); + if (capacity >= 64 * 1024) { + return iree_make_status(IREE_STATUS_RESOURCE_EXHAUSTED, + "path of the executable exceeds 64KiB"); + } + capacity *= 2; + } + path[length] = 0; + + // Strip the executable name and keep the trailing slash. + char* last_slash = strrchr(path, '/'); + if (!last_slash) { + iree_status_t status = + iree_make_status(IREE_STATUS_UNAVAILABLE, + "no directory in the executable path '%s'", path); + iree_allocator_free(host_allocator, path); + return status; + } + last_slash[1] = 0; + + *out_binary_dir = path; + return iree_ok_status(); +} + +// Appends the FastRPC URI opening a session on the DSP domain with |domain_id| +// to |builder|. +// +// The generated hexagon_dsp_URI has the format +// "file:///" <library> "?" <skel invoke function> "&_modver=" <version> +// "&_idlver=" <version> +// and is completed by appending the domain suffix (e.g. "&_dom=cdsp"). FastRPC +// requires the library to be given as absolute path (or "./<library>"), so the +// directory <executable dir>/../lib/hexagon/ is prepended to it. This allows +// running without setting DSP_LIBRARY_PATH. +static iree_status_t iree_hal_hexagon_append_session_uri( + iree_hal_hexagon_domain_id_t domain_id, iree_allocator_t host_allocator, + iree_string_builder_t* builder) { + iree_string_view_t prefix = IREE_SV("file:///"); + iree_string_view_t library_uri = iree_make_cstring_view(hexagon_dsp_URI); + if (!iree_string_view_consume_prefix(&library_uri, prefix)) { + return iree_make_status(IREE_STATUS_INTERNAL, + "DSP URI '%s' does not start with '%.*s'", + hexagon_dsp_URI, (int)prefix.size, prefix.data); + } + + const char* domain_uri_suffix = NULL; + if (!iree_hal_hexagon_get_domain_uri_suffix(domain_id, &domain_uri_suffix)) { + return iree_make_status(IREE_STATUS_INVALID_ARGUMENT, + "unknown DSP domain ID %d", domain_id); + } + + char* binary_dir = NULL; + IREE_RETURN_IF_ERROR( + iree_hal_hexagon_get_binary_dir(host_allocator, &binary_dir)); + iree_status_t status = iree_string_builder_append_format( + builder, "%.*s%s../lib/hexagon/%.*s%s", (int)prefix.size, prefix.data, + binary_dir, (int)library_uri.size, library_uri.data, domain_uri_suffix); + iree_allocator_free(host_allocator, binary_dir); + return status; +} + +// Opens the FastRPC session with the DSP, which loads the device library. +static iree_status_t iree_hal_hexagon_device_open_session( + iree_hal_hexagon_device_t* device) { + IREE_TRACE_ZONE_BEGIN(z0); + + if (device->options.dsp_status_notify) { + IREE_RETURN_AND_END_ZONE_IF_ERROR( + z0, iree_hal_hexagon_device_request_status_notifications( + device->domain_id)); + } + + // The device library is not signed, so it has to run in an unsigned PD. + struct remote_rpc_control_unsigned_module unsigned_module = { + .domain = device->domain_id, + .enable = 1, + }; + int dsp_err = + remote_session_control(DSPRPC_CONTROL_UNSIGNED_MODULE, &unsigned_module, + sizeof(unsigned_module)); + if (dsp_err != AEE_SUCCESS) { + IREE_TRACE_ZONE_END(z0); + return IREE_HAL_HEXAGON_MAKE_STATUS_FROM_DSP_ERR( + dsp_err, "enabling unsigned modules on the DSP failed"); + } + + iree_string_builder_t uri_builder; + iree_string_builder_initialize(device->host_allocator, &uri_builder); + iree_status_t status = iree_hal_hexagon_append_session_uri( + device->domain_id, device->host_allocator, &uri_builder); + if (iree_status_is_ok(status)) { + const char* uri = iree_string_builder_buffer(&uri_builder); + if (device->options.verbose) { + fprintf(stderr, "hexagon: opening DSP session '%s'\n", uri); + } + remote_handle64 rpc_session_handle = 0; + dsp_err = hexagon_dsp_open(uri, &rpc_session_handle); + if (dsp_err == AEE_SUCCESS) { + device->rpc_session_handle = rpc_session_handle; + } else { + status = IREE_HAL_HEXAGON_MAKE_STATUS_FROM_DSP_ERR( + dsp_err, "opening the DSP session failed"); + } + } + iree_string_builder_deinitialize(&uri_builder); + + IREE_TRACE_ZONE_END(z0); + return status; +} + +IREE_API_EXPORT iree_status_t iree_hal_hexagon_device_create( + iree_string_view_t identifier, iree_hal_hexagon_domain_id_t domain_id, + const iree_hal_hexagon_device_options_t* options, + const iree_hal_device_create_params_t* create_params, + iree_allocator_t host_allocator, iree_hal_device_t** out_device) { + IREE_ASSERT_ARGUMENT(options); + IREE_ASSERT_ARGUMENT(create_params); + IREE_ASSERT_ARGUMENT(out_device); + IREE_TRACE_ZONE_BEGIN(z0); + *out_device = NULL; + + // Verify the parameters prior to creating resources. + IREE_RETURN_AND_END_ZONE_IF_ERROR( + z0, iree_hal_hexagon_device_options_verify(options)); + + iree_hal_hexagon_device_t* device = NULL; + iree_host_size_t total_size = sizeof(*device) + identifier.size; + IREE_RETURN_AND_END_ZONE_IF_ERROR( + z0, iree_allocator_malloc(host_allocator, total_size, (void**)&device)); + iree_hal_resource_initialize(&iree_hal_hexagon_device_vtable, + &device->resource); + iree_string_view_append_to_buffer( + identifier, &device->identifier, + (char*)device + total_size - identifier.size); + device->domain_id = domain_id; + device->options = *options; + device->host_allocator = host_allocator; + + iree_status_t status = iree_hal_hexagon_allocator_create( + host_allocator, &device->device_allocator); + if (iree_status_is_ok(status)) { + status = iree_hal_hexagon_device_open_session(device); + } + + if (iree_status_is_ok(status)) { + *out_device = (iree_hal_device_t*)device; + } else { + iree_hal_device_release((iree_hal_device_t*)device); + } + IREE_TRACE_ZONE_END(z0); + return status; +} + +static void iree_hal_hexagon_device_clear_topology_info( + iree_hal_hexagon_device_t* device) { + if (device->frontier_tracker) { + iree_async_frontier_tracker_retire_axis( + device->frontier_tracker, device->axis, + iree_status_from_code(IREE_STATUS_CANCELLED)); + iree_async_frontier_tracker_release(device->frontier_tracker); + device->frontier_tracker = NULL; + device->axis = 0; + } + memset(&device->topology_info, 0, sizeof(device->topology_info)); +} + +static void iree_hal_hexagon_device_destroy(iree_hal_device_t* base_device) { + iree_hal_hexagon_device_t* device = iree_hal_hexagon_device_cast(base_device); + iree_allocator_t host_allocator = iree_hal_device_host_allocator(base_device); + IREE_TRACE_ZONE_BEGIN(z0); + + if (device->rpc_session_handle) { + int dsp_err = hexagon_dsp_close(device->rpc_session_handle); + if (device->options.verbose) { + fprintf(stderr, "hexagon: closed DSP session (result 0x%x)\n", dsp_err); + } + } + + iree_hal_hexagon_device_clear_topology_info(device); + iree_hal_allocator_release(device->device_allocator); + iree_hal_channel_provider_release(device->channel_provider); + + iree_allocator_free(host_allocator, device); + + IREE_TRACE_ZONE_END(z0); +} + +static iree_string_view_t iree_hal_hexagon_device_id( + iree_hal_device_t* base_device) { + iree_hal_hexagon_device_t* device = iree_hal_hexagon_device_cast(base_device); + return device->identifier; +} + +static iree_allocator_t iree_hal_hexagon_device_host_allocator( + iree_hal_device_t* base_device) { + iree_hal_hexagon_device_t* device = iree_hal_hexagon_device_cast(base_device); + return device->host_allocator; +} + +static iree_hal_allocator_t* iree_hal_hexagon_device_allocator( + iree_hal_device_t* base_device) { + iree_hal_hexagon_device_t* device = iree_hal_hexagon_device_cast(base_device); + return device->device_allocator; +} + +static void iree_hal_hexagon_replace_device_allocator( + iree_hal_device_t* base_device, iree_hal_allocator_t* new_allocator) { + iree_hal_hexagon_device_t* device = iree_hal_hexagon_device_cast(base_device); + iree_hal_allocator_retain(new_allocator); + iree_hal_allocator_release(device->device_allocator); + device->device_allocator = new_allocator; +} + +static void iree_hal_hexagon_replace_channel_provider( + iree_hal_device_t* base_device, iree_hal_channel_provider_t* new_provider) { + iree_hal_hexagon_device_t* device = iree_hal_hexagon_device_cast(base_device); + iree_hal_channel_provider_retain(new_provider); + iree_hal_channel_provider_release(device->channel_provider); + device->channel_provider = new_provider; +} + +static iree_status_t iree_hal_hexagon_device_trim( + iree_hal_device_t* base_device) { + iree_hal_hexagon_device_t* device = iree_hal_hexagon_device_cast(base_device); + return iree_hal_allocator_trim(device->device_allocator); +} + +static iree_status_t iree_hal_hexagon_device_query_i64( + iree_hal_device_t* base_device, iree_string_view_t category, + iree_string_view_t key, int64_t* out_value) { + iree_hal_hexagon_device_t* device = iree_hal_hexagon_device_cast(base_device); + *out_value = 0; + + if (iree_string_view_equal(category, IREE_SV("hal.device.id"))) { + // NOTE: this is a fuzzy match and can allow a program to work with multiple + // device implementations. + *out_value = + iree_string_view_match_pattern(device->identifier, key) ? 1 : 0; + return iree_ok_status(); + } + + if (iree_string_view_equal(category, IREE_SV("hal.executable.format"))) { + // TODO(hexagon): report the supported executable formats once executables + // are implemented. + *out_value = 0; + return iree_ok_status(); + } + + if (iree_string_view_equal(category, IREE_SV("hal.device"))) { + if (iree_string_view_equal(key, IREE_SV("concurrency"))) { + *out_value = 1; + return iree_ok_status(); + } + } else if (iree_string_view_equal(category, IREE_SV("hal.dispatch"))) { + if (iree_string_view_equal(key, IREE_SV("concurrency"))) { + *out_value = 1; + return iree_ok_status(); + } + } + + return iree_make_status( + IREE_STATUS_NOT_FOUND, + "unknown device configuration key value '%.*s :: %.*s'", + (int)category.size, category.data, (int)key.size, key.data); +} + +static iree_status_t iree_hal_hexagon_device_query_capabilities( + iree_hal_device_t* base_device, + iree_hal_device_capabilities_t* out_capabilities) { + memset(out_capabilities, 0, sizeof(*out_capabilities)); + return iree_ok_status(); +} + +static const iree_hal_device_topology_info_t* +iree_hal_hexagon_device_topology_info(iree_hal_device_t* base_device) { + iree_hal_hexagon_device_t* device = iree_hal_hexagon_device_cast(base_device); + return &device->topology_info; +} + +static iree_status_t iree_hal_hexagon_device_refine_topology_edge( + iree_hal_device_t* src_device, iree_hal_device_t* dst_device, + iree_hal_topology_edge_t* edge) { + return iree_ok_status(); +} + +static iree_status_t iree_hal_hexagon_device_assign_topology_info( + iree_hal_device_t* base_device, + const iree_hal_device_topology_info_t* topology_info) { + iree_hal_hexagon_device_t* device = iree_hal_hexagon_device_cast(base_device); + if (!topology_info) { + iree_hal_hexagon_device_clear_topology_info(device); + return iree_ok_status(); + } + iree_async_frontier_tracker_t* frontier_tracker = + topology_info->frontier.tracker; + iree_async_axis_t axis = topology_info->frontier.base_axis; + IREE_RETURN_IF_ERROR(iree_async_frontier_tracker_register_axis( + frontier_tracker, axis, /*semaphore=*/NULL)); + device->topology_info = *topology_info; + device->frontier_tracker = frontier_tracker; + device->axis = axis; + iree_async_frontier_tracker_retain(device->frontier_tracker); + return iree_ok_status(); +} + +//===----------------------------------------------------------------------===// +// Unimplemented device functionality +//===----------------------------------------------------------------------===// + +// TODO(hexagon): implement resources and queue operations. Until then the +// device can only be created and queried. + +static iree_status_t iree_hal_hexagon_device_create_channel( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity, + iree_hal_channel_params_t params, iree_hal_channel_t** out_channel) { + *out_channel = NULL; + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon channels not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_create_command_buffer( + iree_hal_device_t* base_device, iree_hal_command_buffer_mode_t mode, + iree_hal_command_category_t command_categories, + iree_hal_queue_affinity_t queue_affinity, iree_host_size_t binding_capacity, + iree_hal_command_buffer_t** out_command_buffer) { + *out_command_buffer = NULL; + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon command buffers not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_create_event( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity, + iree_hal_event_flags_t flags, iree_hal_event_t** out_event) { + *out_event = NULL; + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon events not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_create_executable_cache( + iree_hal_device_t* base_device, iree_string_view_t identifier, + iree_hal_executable_cache_t** out_executable_cache) { + *out_executable_cache = NULL; + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon executables not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_import_file( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity, + iree_hal_memory_access_t access, iree_io_file_handle_t* handle, + iree_hal_external_file_flags_t flags, iree_hal_file_t** out_file) { + *out_file = NULL; + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon files not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_create_semaphore( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity, + uint64_t initial_value, iree_hal_semaphore_flags_t flags, + iree_hal_semaphore_t** out_semaphore) { + *out_semaphore = NULL; + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon semaphores not implemented"); +} + +static iree_hal_semaphore_compatibility_t +iree_hal_hexagon_device_query_semaphore_compatibility( + iree_hal_device_t* base_device, iree_hal_semaphore_t* semaphore) { + return IREE_HAL_SEMAPHORE_COMPATIBILITY_NONE; +} + +static iree_status_t iree_hal_hexagon_device_query_queue_pool_backend( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity, + iree_hal_queue_pool_backend_t* out_backend) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon queue pools not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_queue_alloca( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity, + const iree_hal_semaphore_list_t wait_semaphore_list, + const iree_hal_semaphore_list_t signal_semaphore_list, + iree_hal_pool_t* pool, iree_hal_buffer_params_t params, + iree_device_size_t allocation_size, iree_hal_alloca_flags_t flags, + iree_hal_buffer_t** IREE_RESTRICT out_buffer) { + *out_buffer = NULL; + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon queue alloca not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_queue_dealloca( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity, + const iree_hal_semaphore_list_t wait_semaphore_list, + const iree_hal_semaphore_list_t signal_semaphore_list, + iree_hal_buffer_t* buffer, iree_hal_dealloca_flags_t flags) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon queue dealloca not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_queue_fill( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity, + const iree_hal_semaphore_list_t wait_semaphore_list, + const iree_hal_semaphore_list_t signal_semaphore_list, + iree_hal_buffer_t* target_buffer, iree_device_size_t target_offset, + iree_device_size_t length, const void* pattern, + iree_host_size_t pattern_length, iree_hal_fill_flags_t flags) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon queue fill not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_queue_update( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity, + const iree_hal_semaphore_list_t wait_semaphore_list, + const iree_hal_semaphore_list_t signal_semaphore_list, + const void* source_buffer, iree_host_size_t source_offset, + iree_hal_buffer_t* target_buffer, iree_device_size_t target_offset, + iree_device_size_t length, iree_hal_update_flags_t flags) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon queue update not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_queue_copy( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity, + const iree_hal_semaphore_list_t wait_semaphore_list, + const iree_hal_semaphore_list_t signal_semaphore_list, + iree_hal_buffer_t* source_buffer, iree_device_size_t source_offset, + iree_hal_buffer_t* target_buffer, iree_device_size_t target_offset, + iree_device_size_t length, iree_hal_copy_flags_t flags) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon queue copy not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_queue_read( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity, + const iree_hal_semaphore_list_t wait_semaphore_list, + const iree_hal_semaphore_list_t signal_semaphore_list, + iree_hal_file_t* source_file, uint64_t source_offset, + iree_hal_buffer_t* target_buffer, iree_device_size_t target_offset, + iree_device_size_t length, iree_hal_read_flags_t flags) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon queue read not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_queue_write( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity, + const iree_hal_semaphore_list_t wait_semaphore_list, + const iree_hal_semaphore_list_t signal_semaphore_list, + iree_hal_buffer_t* source_buffer, iree_device_size_t source_offset, + iree_hal_file_t* target_file, uint64_t target_offset, + iree_device_size_t length, iree_hal_write_flags_t flags) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon queue write not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_queue_host_call( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity, + const iree_hal_semaphore_list_t wait_semaphore_list, + const iree_hal_semaphore_list_t signal_semaphore_list, + iree_hal_host_call_t call, const uint64_t args[4], + iree_hal_host_call_flags_t flags) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon queue host call not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_queue_dispatch( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity, + const iree_hal_semaphore_list_t wait_semaphore_list, + const iree_hal_semaphore_list_t signal_semaphore_list, + iree_hal_executable_t* executable, + iree_hal_executable_function_t export_ordinal, + const iree_hal_dispatch_config_t config, iree_const_byte_span_t constants, + const iree_hal_buffer_ref_list_t bindings, + iree_hal_dispatch_flags_t flags) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon queue dispatch not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_queue_execute( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity, + const iree_hal_semaphore_list_t wait_semaphore_list, + const iree_hal_semaphore_list_t signal_semaphore_list, + iree_hal_command_buffer_t* command_buffer, + iree_hal_buffer_binding_table_t binding_table, + iree_hal_execute_flags_t flags) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon queue execute not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_queue_flush( + iree_hal_device_t* base_device, iree_hal_queue_affinity_t queue_affinity) { + // Nothing is ever queued. + return iree_ok_status(); +} + +static iree_status_t iree_hal_hexagon_device_profiling_begin( + iree_hal_device_t* base_device, + const iree_hal_device_profiling_options_t* options) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon device profiling not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_profiling_flush( + iree_hal_device_t* base_device) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon device profiling not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_profiling_end( + iree_hal_device_t* base_device) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon device profiling not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_external_capture_begin( + iree_hal_device_t* base_device, + const iree_hal_device_external_capture_options_t* options) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon external capture not implemented"); +} + +static iree_status_t iree_hal_hexagon_device_external_capture_end( + iree_hal_device_t* base_device) { + return iree_make_status(IREE_STATUS_UNIMPLEMENTED, + "hexagon external capture not implemented"); +} + +static const iree_hal_device_vtable_t iree_hal_hexagon_device_vtable = { + .destroy = iree_hal_hexagon_device_destroy, + .id = iree_hal_hexagon_device_id, + .host_allocator = iree_hal_hexagon_device_host_allocator, + .device_allocator = iree_hal_hexagon_device_allocator, + .replace_device_allocator = iree_hal_hexagon_replace_device_allocator, + .replace_channel_provider = iree_hal_hexagon_replace_channel_provider, + .trim = iree_hal_hexagon_device_trim, + .query_i64 = iree_hal_hexagon_device_query_i64, + .query_capabilities = iree_hal_hexagon_device_query_capabilities, + .topology_info = iree_hal_hexagon_device_topology_info, + .refine_topology_edge = iree_hal_hexagon_device_refine_topology_edge, + .assign_topology_info = iree_hal_hexagon_device_assign_topology_info, + .create_channel = iree_hal_hexagon_device_create_channel, + .create_command_buffer = iree_hal_hexagon_device_create_command_buffer, + .create_event = iree_hal_hexagon_device_create_event, + .create_executable_cache = iree_hal_hexagon_device_create_executable_cache, + .import_file = iree_hal_hexagon_device_import_file, + .create_semaphore = iree_hal_hexagon_device_create_semaphore, + .query_semaphore_compatibility = + iree_hal_hexagon_device_query_semaphore_compatibility, + .query_queue_pool_backend = + iree_hal_hexagon_device_query_queue_pool_backend, + .queue_alloca = iree_hal_hexagon_device_queue_alloca, + .queue_dealloca = iree_hal_hexagon_device_queue_dealloca, + .queue_fill = iree_hal_hexagon_device_queue_fill, + .queue_update = iree_hal_hexagon_device_queue_update, + .queue_copy = iree_hal_hexagon_device_queue_copy, + .queue_read = iree_hal_hexagon_device_queue_read, + .queue_write = iree_hal_hexagon_device_queue_write, + .queue_host_call = iree_hal_hexagon_device_queue_host_call, + .queue_dispatch = iree_hal_hexagon_device_queue_dispatch, + .queue_execute = iree_hal_hexagon_device_queue_execute, + .queue_flush = iree_hal_hexagon_device_queue_flush, + .profiling_begin = iree_hal_hexagon_device_profiling_begin, + .profiling_flush = iree_hal_hexagon_device_profiling_flush, + .profiling_end = iree_hal_hexagon_device_profiling_end, + .external_capture_begin = iree_hal_hexagon_device_external_capture_begin, + .external_capture_end = iree_hal_hexagon_device_external_capture_end, +};
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/device.h b/experimental/runtime/src/iree/hal/drivers/hexagon/device.h new file mode 100644 index 0000000..3e413b0 --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/device.h
@@ -0,0 +1,46 @@ +// Copyright 2026 The IREE Authors +// +// Licensed 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 IREE_HAL_DRIVERS_HEXAGON_DEVICE_H_ +#define IREE_HAL_DRIVERS_HEXAGON_DEVICE_H_ + +#include "iree/base/api.h" +#include "iree/hal/api.h" +#include "iree/hal/drivers/hexagon/api.h" + +//===----------------------------------------------------------------------===// +// Hexagon DSP domains +//===----------------------------------------------------------------------===// + +// Returns the name of the DSP domain with |domain_id| in |out_name| (e.g. +// "CDSP"). The name is a string literal and does not need to be freed. +// Returns false if the domain is unknown. +bool iree_hal_hexagon_get_domain_name(iree_hal_hexagon_domain_id_t domain_id, + const char** out_name); + +// Returns the ID of the DSP domain with the given |name| (e.g. "CDSP") in +// |out_domain_id|. Returns false if the domain is unknown. +bool iree_hal_hexagon_get_domain_id( + iree_string_view_t name, iree_hal_hexagon_domain_id_t* out_domain_id); + +// Converts between DSP domain IDs and HAL device IDs. The device ID is offset +// by one as domain ID 0 (ADSP) would otherwise be IREE_HAL_DEVICE_ID_DEFAULT. +static inline iree_hal_device_id_t iree_hal_hexagon_device_id_from_domain_id( + iree_hal_hexagon_domain_id_t domain_id) { + return (iree_hal_device_id_t)domain_id + 1; +} +static inline iree_hal_hexagon_domain_id_t +iree_hal_hexagon_domain_id_from_device_id(iree_hal_device_id_t device_id) { + return (iree_hal_hexagon_domain_id_t)(device_id - 1); +} + +// Fills |out_device_info| for the DSP domain with |domain_id|. The name and +// path are the domain name. The strings referenced by the device info are +// literals and do not need to be freed. +void iree_hal_hexagon_fill_device_info(iree_hal_hexagon_domain_id_t domain_id, + iree_hal_device_info_t* out_device_info); + +#endif // IREE_HAL_DRIVERS_HEXAGON_DEVICE_H_
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/driver.c b/experimental/runtime/src/iree/hal/drivers/hexagon/driver.c new file mode 100644 index 0000000..1ddd5c2 --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/driver.c
@@ -0,0 +1,239 @@ +// Copyright 2026 The IREE Authors +// +// Licensed 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 "iree/hal/drivers/hexagon/driver.h" + +#include <string.h> + +#include "iree/hal/drivers/hexagon/api.h" +#include "iree/hal/drivers/hexagon/device.h" +#include "iree/hal/drivers/hexagon/utils.h" + +// Hexagon SDK headers. +#include "AEEStdErr.h" +#include "remote.h" + +// Domain of the device created when no device is specified. +#define IREE_HAL_HEXAGON_DEFAULT_DOMAIN_ID \ + ((iree_hal_hexagon_domain_id_t)CDSP_DOMAIN_ID) + +//===----------------------------------------------------------------------===// +// iree_hal_hexagon_driver_options_t +//===----------------------------------------------------------------------===// + +IREE_API_EXPORT void iree_hal_hexagon_driver_options_initialize( + iree_hal_hexagon_driver_options_t* out_options) { + memset(out_options, 0, sizeof(*out_options)); + iree_hal_hexagon_device_options_initialize( + &out_options->default_device_options); +} + +static iree_status_t iree_hal_hexagon_driver_options_verify( + const iree_hal_hexagon_driver_options_t* options) { + return iree_ok_status(); +} + +//===----------------------------------------------------------------------===// +// iree_hal_hexagon_driver_t +//===----------------------------------------------------------------------===// + +typedef struct iree_hal_hexagon_driver_t { + iree_hal_resource_t resource; + iree_allocator_t host_allocator; + + iree_string_view_t identifier; + iree_hal_hexagon_driver_options_t options; + + // + trailing identifier string storage +} iree_hal_hexagon_driver_t; + +static const iree_hal_driver_vtable_t iree_hal_hexagon_driver_vtable; + +static iree_hal_hexagon_driver_t* iree_hal_hexagon_driver_cast( + iree_hal_driver_t* base_value) { + IREE_HAL_ASSERT_TYPE(base_value, &iree_hal_hexagon_driver_vtable); + return (iree_hal_hexagon_driver_t*)base_value; +} + +IREE_API_EXPORT iree_status_t iree_hal_hexagon_driver_create( + iree_string_view_t identifier, + const iree_hal_hexagon_driver_options_t* options, + iree_allocator_t host_allocator, iree_hal_driver_t** out_driver) { + IREE_ASSERT_ARGUMENT(options); + IREE_ASSERT_ARGUMENT(out_driver); + IREE_TRACE_ZONE_BEGIN(z0); + *out_driver = NULL; + + IREE_RETURN_AND_END_ZONE_IF_ERROR( + z0, iree_hal_hexagon_driver_options_verify(options)); + + iree_hal_hexagon_driver_t* driver = NULL; + iree_host_size_t total_size = sizeof(*driver) + identifier.size; + IREE_RETURN_AND_END_ZONE_IF_ERROR( + z0, iree_allocator_malloc(host_allocator, total_size, (void**)&driver)); + iree_hal_resource_initialize(&iree_hal_hexagon_driver_vtable, + &driver->resource); + driver->host_allocator = host_allocator; + iree_string_view_append_to_buffer( + identifier, &driver->identifier, + (char*)driver + total_size - identifier.size); + memcpy(&driver->options, options, sizeof(*options)); + + *out_driver = (iree_hal_driver_t*)driver; + IREE_TRACE_ZONE_END(z0); + return iree_ok_status(); +} + +static void iree_hal_hexagon_driver_destroy(iree_hal_driver_t* base_driver) { + iree_hal_hexagon_driver_t* driver = iree_hal_hexagon_driver_cast(base_driver); + iree_allocator_t host_allocator = driver->host_allocator; + IREE_TRACE_ZONE_BEGIN(z0); + + iree_allocator_free(host_allocator, driver); + + IREE_TRACE_ZONE_END(z0); +} + +static iree_status_t iree_hal_hexagon_driver_query_available_devices( + iree_hal_driver_t* base_driver, iree_allocator_t host_allocator, + iree_host_size_t* out_device_info_count, + iree_hal_device_info_t** out_device_infos) { + *out_device_info_count = 0; + *out_device_infos = NULL; + + // Report a device for each DSP domain that can run unsigned modules. The + // device library is not signed, so domains supporting only signed modules + // are not usable. Querying is not cached so that domains coming and going + // during the lifetime of the process are reported correctly. + static const iree_hal_hexagon_domain_id_t all_domain_ids[] = { + ADSP_DOMAIN_ID, MDSP_DOMAIN_ID, SDSP_DOMAIN_ID, + CDSP_DOMAIN_ID, CDSP1_DOMAIN_ID, + }; + iree_hal_hexagon_domain_id_t domain_ids[IREE_ARRAYSIZE(all_domain_ids)]; + iree_host_size_t domain_count = 0; + for (iree_host_size_t i = 0; i < IREE_ARRAYSIZE(all_domain_ids); ++i) { + struct remote_dsp_capability capability = { + .domain = (uint32_t)all_domain_ids[i], + .attribute_ID = UNSIGNED_PD_SUPPORT, + .capability = 0, + }; + int dsp_err = remote_handle_control(DSPRPC_GET_DSP_INFO, &capability, + sizeof(capability)); + if (dsp_err == AEE_SUCCESS && capability.capability != 0) { + domain_ids[domain_count++] = all_domain_ids[i]; + } + } + if (domain_count == 0) return iree_ok_status(); + + iree_hal_device_info_t* device_infos = NULL; + IREE_RETURN_IF_ERROR(iree_allocator_malloc( + host_allocator, domain_count * sizeof(*device_infos), + (void**)&device_infos)); + for (iree_host_size_t i = 0; i < domain_count; ++i) { + iree_hal_hexagon_fill_device_info(domain_ids[i], &device_infos[i]); + } + *out_device_info_count = domain_count; + *out_device_infos = device_infos; + return iree_ok_status(); +} + +static iree_status_t iree_hal_hexagon_driver_dump_device_info( + iree_hal_driver_t* base_driver, iree_hal_device_id_t device_id, + iree_string_builder_t* builder) { + iree_hal_hexagon_domain_id_t domain_id = + iree_hal_hexagon_domain_id_from_device_id(device_id); + const char* domain_name = "unknown"; + iree_hal_hexagon_get_domain_name(domain_id, &domain_name); + return iree_string_builder_append_format( + builder, "\n- DSP domain: %s (ID %d)", domain_name, domain_id); +} + +// Parses the device parameters from the device URI into |options|. +// See README.md for the supported parameters. +static iree_status_t iree_hal_hexagon_device_options_parse( + iree_host_size_t param_count, const iree_string_pair_t* params, + iree_hal_hexagon_device_options_t* options) { + for (iree_host_size_t i = 0; i < param_count; ++i) { + const iree_string_pair_t* param = ¶ms[i]; + if (iree_string_view_equal_case(param->key, IREE_SV("verbose"))) { + IREE_RETURN_IF_ERROR(iree_hal_hexagon_parse_bool_from_string( + param->value, &options->verbose)); + } else if (iree_string_view_equal_case(param->key, + IREE_SV("dsp_status_notify"))) { + IREE_RETURN_IF_ERROR(iree_hal_hexagon_parse_bool_from_string( + param->value, &options->dsp_status_notify)); + } else { + return iree_make_status(IREE_STATUS_INVALID_ARGUMENT, + "unknown hexagon device parameter '%.*s'", + (int)param->key.size, param->key.data); + } + } + return iree_ok_status(); +} + +// Creates a device on the DSP domain with |domain_id|. +static iree_status_t iree_hal_hexagon_driver_create_device( + iree_hal_hexagon_driver_t* driver, iree_hal_hexagon_domain_id_t domain_id, + iree_host_size_t param_count, const iree_string_pair_t* params, + const iree_hal_device_create_params_t* create_params, + iree_allocator_t host_allocator, iree_hal_device_t** out_device) { + iree_hal_hexagon_device_options_t options = + driver->options.default_device_options; + IREE_RETURN_IF_ERROR( + iree_hal_hexagon_device_options_parse(param_count, params, &options)); + return iree_hal_hexagon_device_create(driver->identifier, domain_id, &options, + create_params, host_allocator, + out_device); +} + +static iree_status_t iree_hal_hexagon_driver_create_device_by_id( + iree_hal_driver_t* base_driver, iree_hal_device_id_t device_id, + iree_host_size_t param_count, const iree_string_pair_t* params, + const iree_hal_device_create_params_t* create_params, + iree_allocator_t host_allocator, iree_hal_device_t** out_device) { + iree_hal_hexagon_driver_t* driver = iree_hal_hexagon_driver_cast(base_driver); + iree_hal_hexagon_domain_id_t domain_id = + device_id == IREE_HAL_DEVICE_ID_DEFAULT + ? IREE_HAL_HEXAGON_DEFAULT_DOMAIN_ID + : iree_hal_hexagon_domain_id_from_device_id(device_id); + return iree_hal_hexagon_driver_create_device(driver, domain_id, param_count, + params, create_params, + host_allocator, out_device); +} + +static iree_status_t iree_hal_hexagon_driver_create_device_by_path( + iree_hal_driver_t* base_driver, iree_string_view_t driver_name, + iree_string_view_t device_path, iree_host_size_t param_count, + const iree_string_pair_t* params, + const iree_hal_device_create_params_t* create_params, + iree_allocator_t host_allocator, iree_hal_device_t** out_device) { + iree_hal_hexagon_driver_t* driver = iree_hal_hexagon_driver_cast(base_driver); + + // The device path is empty (default domain), a domain name, or a domain ID. + iree_hal_hexagon_domain_id_t domain_id = IREE_HAL_HEXAGON_DEFAULT_DOMAIN_ID; + uint32_t parsed_domain_id = 0; + if (iree_string_view_is_empty(device_path)) { + domain_id = IREE_HAL_HEXAGON_DEFAULT_DOMAIN_ID; + } else if (iree_string_view_atoi_uint32(device_path, &parsed_domain_id)) { + domain_id = (iree_hal_hexagon_domain_id_t)parsed_domain_id; + } else if (!iree_hal_hexagon_get_domain_id(device_path, &domain_id)) { + return iree_make_status(IREE_STATUS_NOT_FOUND, + "unknown hexagon device path '%.*s'; expected a " + "DSP domain name or ID", + (int)device_path.size, device_path.data); + } + return iree_hal_hexagon_driver_create_device(driver, domain_id, param_count, + params, create_params, + host_allocator, out_device); +} + +static const iree_hal_driver_vtable_t iree_hal_hexagon_driver_vtable = { + .destroy = iree_hal_hexagon_driver_destroy, + .query_available_devices = iree_hal_hexagon_driver_query_available_devices, + .dump_device_info = iree_hal_hexagon_driver_dump_device_info, + .create_device_by_id = iree_hal_hexagon_driver_create_device_by_id, + .create_device_by_path = iree_hal_hexagon_driver_create_device_by_path, +};
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/driver.h b/experimental/runtime/src/iree/hal/drivers/hexagon/driver.h new file mode 100644 index 0000000..3deef6b --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/driver.h
@@ -0,0 +1,20 @@ +// Copyright 2026 The IREE Authors +// +// Licensed 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 IREE_HAL_DRIVERS_HEXAGON_DRIVER_H_ +#define IREE_HAL_DRIVERS_HEXAGON_DRIVER_H_ + +#include "iree/base/api.h" +#include "iree/hal/api.h" + +//===----------------------------------------------------------------------===// +// iree_hal_hexagon_driver_t +//===----------------------------------------------------------------------===// + +// NOTE: driver creation is part of the public API header (api.h). This header +// can contain internal types and functions. + +#endif // IREE_HAL_DRIVERS_HEXAGON_DRIVER_H_
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/dsp/BUILD.bazel b/experimental/runtime/src/iree/hal/drivers/hexagon/dsp/BUILD.bazel new file mode 100644 index 0000000..b1fb5f2 --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/dsp/BUILD.bazel
@@ -0,0 +1,22 @@ +# Copyright 2026 The IREE Authors +# +# Licensed 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 + +load("//build_tools/bazel:iree_hexagon_dsp_library.bzl", "iree_hexagon_dsp_library") + +package( + default_visibility = ["//visibility:public"], + features = ["layering_check"], + licenses = ["notice"], # Apache 2.0 +) + +# Device library loaded on the DSP when a Hexagon device is created. Deploy as +# <bin>/../lib/hexagon/libhexagon_dsp_skel.so next to the tools. +iree_hexagon_dsp_library( + name = "hexagon_dsp_skel", + srcs = ["device.c"], + arch = "v79", + interface = "//experimental/runtime/src/iree/hal/drivers/hexagon/interface:hexagon_dsp", +)
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/dsp/CMakeLists.txt b/experimental/runtime/src/iree/hal/drivers/hexagon/dsp/CMakeLists.txt new file mode 100644 index 0000000..40fd4f2 --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/dsp/CMakeLists.txt
@@ -0,0 +1,24 @@ +################################################################################ +# Autogenerated by build_tools/bazel_to_cmake/bazel_to_cmake.py from # +# experimental/runtime/src/iree/hal/drivers/hexagon/dsp/BUILD.bazel # +# # +# Use iree_cmake_extra_content from iree/build_defs.oss.bzl to add arbitrary # +# CMake-only content. # +# # +# To disable autogeneration for this file entirely, delete this header. # +################################################################################ + +iree_add_all_subdirs() + +iree_hexagon_dsp_library( + NAME + hexagon_dsp_skel + INTERFACE + iree_hal_drivers_hexagon_interface_hexagon_dsp + ARCH + v79 + SRCS + "device.c" +) + +### BAZEL_TO_CMAKE_PRESERVES_ALL_CONTENT_BELOW_THIS_LINE ###
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/dsp/device.c b/experimental/runtime/src/iree/hal/drivers/hexagon/dsp/device.c new file mode 100644 index 0000000..bd4f6bb --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/dsp/device.c
@@ -0,0 +1,34 @@ +// Copyright 2026 The IREE Authors +// +// Licensed 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 + +// DSP side of the FastRPC session opened by the Hexagon HAL device. + +#include <stdlib.h> + +#include "AEEStdErr.h" +#include "hexagon_dsp.h" + +// State of a FastRPC session on the DSP. +typedef struct hexagon_dsp_session_t { + // TODO(hexagon): add state (e.g. loaded executables) once there are RPCs. + int reserved; +} hexagon_dsp_session_t; + +// Opens a FastRPC session. |uri| contains the name of the library and the DSP +// domain. The returned |handle| is passed to all other functions. +int hexagon_dsp_open(const char* uri, remote_handle64* handle) { + hexagon_dsp_session_t* session = + (hexagon_dsp_session_t*)calloc(1, sizeof(*session)); + if (!session) return AEE_ENOMEMORY; + *handle = (remote_handle64)session; + return AEE_SUCCESS; +} + +// Closes the FastRPC session with |handle| as returned by hexagon_dsp_open. +int hexagon_dsp_close(remote_handle64 handle) { + free((hexagon_dsp_session_t*)handle); + return AEE_SUCCESS; +}
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/interface/BUILD.bazel b/experimental/runtime/src/iree/hal/drivers/hexagon/interface/BUILD.bazel new file mode 100644 index 0000000..8a312a2 --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/interface/BUILD.bazel
@@ -0,0 +1,19 @@ +# Copyright 2026 The IREE Authors +# +# Licensed 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 + +load("//build_tools/bazel:iree_hexagon_interface.bzl", "iree_hexagon_interface") + +package( + default_visibility = ["//visibility:public"], + features = ["layering_check"], + licenses = ["notice"], # Apache 2.0 +) + +# FastRPC interface between the host (stub) and the DSP (skel). +iree_hexagon_interface( + name = "hexagon_dsp", + idl = "hexagon_dsp.idl", +)
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/interface/CMakeLists.txt b/experimental/runtime/src/iree/hal/drivers/hexagon/interface/CMakeLists.txt new file mode 100644 index 0000000..caa9e0e --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/interface/CMakeLists.txt
@@ -0,0 +1,20 @@ +################################################################################ +# Autogenerated by build_tools/bazel_to_cmake/bazel_to_cmake.py from # +# experimental/runtime/src/iree/hal/drivers/hexagon/interface/BUILD.bazel # +# # +# Use iree_cmake_extra_content from iree/build_defs.oss.bzl to add arbitrary # +# CMake-only content. # +# # +# To disable autogeneration for this file entirely, delete this header. # +################################################################################ + +iree_add_all_subdirs() + +iree_hexagon_interface( + NAME + hexagon_dsp + IDL + "hexagon_dsp.idl" +) + +### BAZEL_TO_CMAKE_PRESERVES_ALL_CONTENT_BELOW_THIS_LINE ###
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/interface/hexagon_dsp.idl b/experimental/runtime/src/iree/hal/drivers/hexagon/interface/hexagon_dsp.idl new file mode 100644 index 0000000..2826a79 --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/interface/hexagon_dsp.idl
@@ -0,0 +1,17 @@ +// Copyright 2026 The IREE Authors +// +// Licensed 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 + +// FastRPC interface between the Hexagon HAL driver on the host (stub) and the +// device library running on the DSP (skel). qaic generates hexagon_dsp_open() +// and hexagon_dsp_close() for the remote_handle64 session; the DSP side +// implements them in dsp/device.c. + +#include "AEEStdDef.idl" +#include "remote.idl" + +const string IDL_VERSION = "0.1.0"; + +interface hexagon_dsp : remote_handle64 {};
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/registration/BUILD.bazel b/experimental/runtime/src/iree/hal/drivers/hexagon/registration/BUILD.bazel new file mode 100644 index 0000000..31cec17 --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/registration/BUILD.bazel
@@ -0,0 +1,44 @@ +# Copyright 2026 The IREE Authors +# +# Licensed 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 + +load("@bazel_skylib//rules:common_settings.bzl", "bool_flag") +load("//build_tools/bazel:build_defs.oss.bzl", "iree_runtime_cc_library") + +package( + default_visibility = ["//visibility:public"], + features = ["layering_check"], + licenses = ["notice"], # Apache 2.0 +) + +iree_runtime_cc_library( + name = "registration", + srcs = ["driver_module.c"], + hdrs = ["driver_module.h"], + target_compatible_with = [ + "@platforms//cpu:aarch64", + "@platforms//os:android", + ], + deps = [ + "//experimental/runtime/src:runtime_defines", + "//experimental/runtime/src/iree/hal/drivers/hexagon", + "//runtime/src/iree/base", + "//runtime/src/iree/hal", + ], +) + +# Enables the driver in the tools with +# --//experimental/runtime/src/iree/hal/drivers/hexagon/registration:enable +# (see --config=hexagon). The external_hal_driver tag in the root MODULE.bazel +# registers the driver with Bazel, the root CMakeLists.txt with CMake. +bool_flag( + name = "enable", + build_setting_default = False, +) + +config_setting( + name = "enabled", + flag_values = {":enable": "True"}, +)
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/registration/CMakeLists.txt b/experimental/runtime/src/iree/hal/drivers/hexagon/registration/CMakeLists.txt new file mode 100644 index 0000000..d6fb6be --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/registration/CMakeLists.txt
@@ -0,0 +1,29 @@ +################################################################################ +# Autogenerated by build_tools/bazel_to_cmake/bazel_to_cmake.py from # +# experimental/runtime/src/iree/hal/drivers/hexagon/registration/BUILD.bazel # +# # +# Use iree_cmake_extra_content from iree/build_defs.oss.bzl to add arbitrary # +# CMake-only content. # +# # +# To disable autogeneration for this file entirely, delete this header. # +################################################################################ + +iree_add_all_subdirs() + +if(IREE_ARCH STREQUAL "arm_64" AND CMAKE_SYSTEM_NAME STREQUAL "Android") +iree_cc_library( + NAME + registration + HDRS + "driver_module.h" + SRCS + "driver_module.c" + DEPS + iree::base + iree::hal + iree::hal::drivers::hexagon + PUBLIC +) +endif() + +### BAZEL_TO_CMAKE_PRESERVES_ALL_CONTENT_BELOW_THIS_LINE ###
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/registration/driver_module.c b/experimental/runtime/src/iree/hal/drivers/hexagon/registration/driver_module.c new file mode 100644 index 0000000..3b3af2d --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/registration/driver_module.c
@@ -0,0 +1,47 @@ +// Copyright 2026 The IREE Authors +// +// Licensed 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 "iree/hal/drivers/hexagon/registration/driver_module.h" + +#include "iree/base/api.h" +#include "iree/hal/drivers/hexagon/api.h" + +static iree_status_t iree_hal_hexagon_driver_factory_enumerate( + void* self, iree_host_size_t* out_driver_info_count, + const iree_hal_driver_info_t** out_driver_infos) { + static const iree_hal_driver_info_t default_driver_info = { + .driver_name = IREE_SVL("hexagon"), + .full_name = IREE_SVL("Qualcomm Hexagon DSP (experimental)"), + }; + *out_driver_info_count = 1; + *out_driver_infos = &default_driver_info; + return iree_ok_status(); +} + +static iree_status_t iree_hal_hexagon_driver_factory_try_create( + void* self, iree_string_view_t driver_name, iree_allocator_t host_allocator, + iree_hal_driver_t** out_driver) { + if (!iree_string_view_equal(driver_name, IREE_SV("hexagon"))) { + return iree_make_status(IREE_STATUS_UNAVAILABLE, + "no driver '%.*s' is provided by this factory", + (int)driver_name.size, driver_name.data); + } + + iree_hal_hexagon_driver_options_t options; + iree_hal_hexagon_driver_options_initialize(&options); + return iree_hal_hexagon_driver_create(driver_name, &options, host_allocator, + out_driver); +} + +IREE_API_EXPORT iree_status_t +iree_hal_hexagon_driver_module_register(iree_hal_driver_registry_t* registry) { + static const iree_hal_driver_factory_t factory = { + .self = NULL, + .enumerate = iree_hal_hexagon_driver_factory_enumerate, + .try_create = iree_hal_hexagon_driver_factory_try_create, + }; + return iree_hal_driver_registry_register_factory(registry, &factory); +}
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/registration/driver_module.h b/experimental/runtime/src/iree/hal/drivers/hexagon/registration/driver_module.h new file mode 100644 index 0000000..a875fc7 --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/registration/driver_module.h
@@ -0,0 +1,25 @@ +// Copyright 2026 The IREE Authors +// +// Licensed 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 IREE_HAL_DRIVERS_HEXAGON_REGISTRATION_DRIVER_MODULE_H_ +#define IREE_HAL_DRIVERS_HEXAGON_REGISTRATION_DRIVER_MODULE_H_ + +#include "iree/base/api.h" +#include "iree/hal/api.h" + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +// Registers the Hexagon HAL driver ("hexagon") with |registry|. +IREE_API_EXPORT iree_status_t +iree_hal_hexagon_driver_module_register(iree_hal_driver_registry_t* registry); + +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + +#endif // IREE_HAL_DRIVERS_HEXAGON_REGISTRATION_DRIVER_MODULE_H_
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/rpc_types.c b/experimental/runtime/src/iree/hal/drivers/hexagon/rpc_types.c new file mode 100644 index 0000000..14b4315 --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/rpc_types.c
@@ -0,0 +1,18 @@ +// Copyright 2026 The IREE Authors +// +// Licensed 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 + +// Checks statically that the type aliases defined in rpc_types.h match the +// types in the hexagon_dsp.h header generated from the RPC interface. + +#include "iree/hal/drivers/hexagon/rpc_types.h" + +#include "hexagon_dsp.h" + +#define IREE_HAL_HEXAGON_ASSERT_TYPES_EQ(a, b) \ + _Static_assert(__builtin_types_compatible_p(a, b), \ + "FastRPC type mismatch, fix type in rpc_types.h") + +IREE_HAL_HEXAGON_ASSERT_TYPES_EQ(remote_handle64, rpc_session_handle_t);
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/rpc_types.h b/experimental/runtime/src/iree/hal/drivers/hexagon/rpc_types.h new file mode 100644 index 0000000..b72c6bb --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/rpc_types.h
@@ -0,0 +1,18 @@ +// Copyright 2026 The IREE Authors +// +// Licensed 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 + +// Aliases for the FastRPC types used by the generated hexagon_dsp.h, based only +// on built-in C types. This decouples headers of the driver from the generated +// interface header. rpc_types.c statically checks that the aliases match the +// generated types. + +#ifndef IREE_HAL_DRIVERS_HEXAGON_RPC_TYPES_H_ +#define IREE_HAL_DRIVERS_HEXAGON_RPC_TYPES_H_ + +// Handle of a FastRPC session with the DSP (remote_handle64). +typedef unsigned long rpc_session_handle_t; + +#endif // IREE_HAL_DRIVERS_HEXAGON_RPC_TYPES_H_
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/utils.c b/experimental/runtime/src/iree/hal/drivers/hexagon/utils.c new file mode 100644 index 0000000..d82dffb --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/utils.c
@@ -0,0 +1,288 @@ +// Copyright 2026 The IREE Authors +// +// Licensed 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 "iree/hal/drivers/hexagon/utils.h" + +#include <errno.h> +#include <string.h> + +// Hexagon SDK headers. +#include "AEEStdErr.h" + +// from AEEStdErr.h +#define DSP_ERR_LIST \ + /* Basic error codes */ \ + DSP_ERR_ENTRY(AEE_SUCCESS, IREE_STATUS_OK) \ + DSP_ERR_ENTRY(AEE_EUNKNOWN, IREE_STATUS_UNKNOWN) \ + DSP_ERR_ENTRY(AEE_EFAILED, IREE_STATUS_UNKNOWN) \ + DSP_ERR_ENTRY(AEE_ENOMEMORY, IREE_STATUS_RESOURCE_EXHAUSTED) \ + DSP_ERR_ENTRY(AEE_ECLASSNOTSUPPORT, IREE_STATUS_INCOMPATIBLE) \ + DSP_ERR_ENTRY(AEE_EVERSIONNOTSUPPORT, IREE_STATUS_INCOMPATIBLE) \ + DSP_ERR_ENTRY(AEE_EALREADYLOADED, IREE_STATUS_ALREADY_EXISTS) \ + DSP_ERR_ENTRY(AEE_EUNABLETOLOAD, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EUNABLETOUNLOAD, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EALARMPENDING, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EINVALIDTIME, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EBADCLASS, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EBADMETRIC, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EEXPIRED, IREE_STATUS_DEADLINE_EXCEEDED) \ + DSP_ERR_ENTRY(AEE_EBADSTATE, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EBADPARM, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_ESCHEMENOTSUPPORTED, IREE_STATUS_INCOMPATIBLE) \ + DSP_ERR_ENTRY(AEE_EBADITEM, IREE_STATUS_OUT_OF_RANGE) \ + DSP_ERR_ENTRY(AEE_EINVALIDFORMAT, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EINCOMPLETEITEM, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_ENOPERSISTMEMORY, IREE_STATUS_RESOURCE_EXHAUSTED) \ + DSP_ERR_ENTRY(AEE_EUNSUPPORTED, IREE_STATUS_INCOMPATIBLE) \ + DSP_ERR_ENTRY(AEE_EPRIVLEVEL, IREE_STATUS_PERMISSION_DENIED) \ + DSP_ERR_ENTRY(AEE_ERESOURCENOTFOUND, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_EREENTERED, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EBADTASK, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EALLOCATED, IREE_STATUS_ALREADY_EXISTS) \ + DSP_ERR_ENTRY(AEE_EALREADY, IREE_STATUS_ALREADY_EXISTS) \ + DSP_ERR_ENTRY(AEE_EADSAUTHBAD, IREE_STATUS_UNAUTHENTICATED) \ + DSP_ERR_ENTRY(AEE_ENEEDSERVICEPROG, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EMEMPTR, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EHEAP, IREE_STATUS_RESOURCE_EXHAUSTED) \ + DSP_ERR_ENTRY(AEE_EIDLE, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EITEMBUSY, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EBADSID, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_ENOTYPE, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_ENEEDMORE, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EADSCAPS, IREE_STATUS_INCOMPATIBLE) \ + DSP_ERR_ENTRY(AEE_EBADSHUTDOWN, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EBUFFERTOOSMALL, IREE_STATUS_RESOURCE_EXHAUSTED) \ + DSP_ERR_ENTRY(AEE_EACKPENDING, IREE_STATUS_DEFERRED) \ + DSP_ERR_ENTRY(AEE_ENOTOWNER, IREE_STATUS_PERMISSION_DENIED) \ + DSP_ERR_ENTRY(AEE_EINVALIDITEM, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_ENOTALLOWED, IREE_STATUS_PERMISSION_DENIED) \ + /* AEE_EINVHANDLE has same value as AEE_EBADHANDLE */ \ + DSP_ERR_ENTRY(AEE_EOUTOFHANDLES, IREE_STATUS_RESOURCE_EXHAUSTED) \ + DSP_ERR_ENTRY(AEE_ENOMORE, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_ECPUEXCEPTION, IREE_STATUS_INTERNAL) \ + DSP_ERR_ENTRY(AEE_EREADONLY, IREE_STATUS_PERMISSION_DENIED) \ + DSP_ERR_ENTRY(AEE_ERPC, IREE_STATUS_INTERNAL) \ + DSP_ERR_ENTRY(AEE_EFILE, IREE_STATUS_INTERNAL) \ + DSP_ERR_ENTRY(AEE_ENOSUCH, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_EINTERRUPTED, IREE_STATUS_ABORTED) \ + /* AEE_ECONNRESET has same value as AEE_ENORPCMEMORY */ \ + DSP_ERR_ENTRY(AEE_EWOULDBLOCK, IREE_STATUS_DEFERRED) \ + /* Sigverify / loader errors */ \ + DSP_ERR_ENTRY(AEE_EINVALIDMSG, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EINVALIDTHREAD, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EINVALIDPROCESS, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EINVALIDFILENAME, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EINVALIDDIGESTSIZE, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EINVALIDSEGS, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EINVALIDSIGNATURE, IREE_STATUS_UNAUTHENTICATED) \ + DSP_ERR_ENTRY(AEE_EINVALIDDOMAIN, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EINVALIDFD, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EINVALIDDEVICE, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_EINVALIDMODE, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EINVALIDPROCNAME, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_ENOSUCHMOD, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_ENOSUCHINSTANCE, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_ENOSUCHTHREAD, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_ENOSUCHPROCESS, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_ENOSUCHSYMBOL, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_ENOSUCHDEVICE, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_ENOSUCHPROP, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_ENOSUCHFILE, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_ENOSUCHHANDLE, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_ENOSUCHSTREAM, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_ENOSUCHMAP, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_ENOSUCHREGISTER, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_ENOSUCHCLIENT, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_EBADDOMAIN, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EBADSIZE, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EBADPERMS, IREE_STATUS_PERMISSION_DENIED) \ + DSP_ERR_ENTRY(AEE_EBADFD, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EBADPID, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EBADTID, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EBADELF, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EBADASID, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EBADCONTEXT, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EBADMEMALIGN, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EIOCTL, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EFOPEN, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_EFGETS, IREE_STATUS_INTERNAL) \ + DSP_ERR_ENTRY(AEE_EFFLUSH, IREE_STATUS_INTERNAL) \ + DSP_ERR_ENTRY(AEE_EFCLOSE, IREE_STATUS_INTERNAL) \ + DSP_ERR_ENTRY(AEE_EEOF, IREE_STATUS_OUT_OF_RANGE) \ + DSP_ERR_ENTRY(AEE_EFREAD, IREE_STATUS_INTERNAL) \ + DSP_ERR_ENTRY(AEE_EFWRITE, IREE_STATUS_INTERNAL) \ + DSP_ERR_ENTRY(AEE_EFGETPOS, IREE_STATUS_INTERNAL) \ + DSP_ERR_ENTRY(AEE_EFSETPOS, IREE_STATUS_INTERNAL) \ + DSP_ERR_ENTRY(AEE_EFTELL, IREE_STATUS_INTERNAL) \ + DSP_ERR_ENTRY(AEE_EFSEEK, IREE_STATUS_INTERNAL) \ + DSP_ERR_ENTRY(AEE_EFLEN, IREE_STATUS_OUT_OF_RANGE) \ + DSP_ERR_ENTRY(AEE_EGETENV, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_ESETENV, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EMMAP, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EIONMAP, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EIONALLOC, IREE_STATUS_RESOURCE_EXHAUSTED) \ + DSP_ERR_ENTRY(AEE_ENORPCMEMORY, IREE_STATUS_RESOURCE_EXHAUSTED) \ + DSP_ERR_ENTRY(AEE_ENOROOTOFTRUST, IREE_STATUS_UNAUTHENTICATED) \ + DSP_ERR_ENTRY(AEE_ENOTLOCKED, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_ENOTINITIALIZED, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EUNSUPPORTEDAPI, IREE_STATUS_INCOMPATIBLE) \ + DSP_ERR_ENTRY(AEE_EUNPACK, IREE_STATUS_INTERNAL) \ + DSP_ERR_ENTRY(AEE_EPOLL, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EEVENTREAD, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EMAXBUFS, IREE_STATUS_RESOURCE_EXHAUSTED) \ + DSP_ERR_ENTRY(AEE_EINVARGS, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_ECONNREFUSED, IREE_STATUS_UNAVAILABLE) \ + DSP_ERR_ENTRY(AEE_ENOSESSION, IREE_STATUS_UNAVAILABLE) \ + DSP_ERR_ENTRY(AEE_EUNSIGNEDMOD, IREE_STATUS_PERMISSION_DENIED) \ + DSP_ERR_ENTRY(AEE_EINVALIDHASH, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EBADVA, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_ENOSUCHJOB, IREE_STATUS_NOT_FOUND) \ + /* AEE_ENOSUCHGROUP has same value as AEE_ENOSUCHJOB */ \ + DSP_ERR_ENTRY(AEE_EBADMAPREFCNT, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EBADPAGECNT, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EMAPALREADYPRESENT, IREE_STATUS_ALREADY_EXISTS) \ + DSP_ERR_ENTRY(AEE_ENOFREESECTION, IREE_STATUS_RESOURCE_EXHAUSTED) \ + DSP_ERR_ENTRY(AEE_U2GCLIENT_OPEN, IREE_STATUS_FAILED_PRECONDITION) \ + /* DAL and subsystems */ \ + DSP_ERR_ENTRY(AEE_EDALDEVATTACH, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EDALINTREGISTER, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EDALINTUNREGISTER, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EDALGETPROP, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_EDALGETVAL, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EDCVSREQUEST, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTREGIONCREATE, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTCACHECLEAN, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTREGIONGETATTR, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTBADREGIONPERMS, IREE_STATUS_PERMISSION_DENIED) \ + DSP_ERR_ENTRY(AEE_EQURTMEMPOOLADD, IREE_STATUS_RESOURCE_EXHAUSTED) \ + DSP_ERR_ENTRY(AEE_EQURTREGISTERDEV, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTMEMPOOLCREATE, IREE_STATUS_RESOURCE_EXHAUSTED) \ + DSP_ERR_ENTRY(AEE_EQURTGETVA, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTREGIONDELETE, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTMEMPOOLATTACH, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTTHREADCREATE, IREE_STATUS_RESOURCE_EXHAUSTED) \ + DSP_ERR_ENTRY(AEE_EQURTCOPYTOUSER, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTMEMMAPCREATE, IREE_STATUS_RESOURCE_EXHAUSTED) \ + DSP_ERR_ENTRY(AEE_EQURTINVHANDLE, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EQURTBADASID, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EQURTOPENFAILED, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTCOPYFROMUSER, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTLINELOCK, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTQDIDEFMETHOD, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTCREATEHANDLE, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTWRITABLEMEM, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTTHREADCREATEDEF, IREE_STATUS_RESOURCE_EXHAUSTED) \ + DSP_ERR_ENTRY(AEE_EQURTLOOKUPVA, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_EQURTLOOKUPPA, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_EQURTMIGRATESECURE, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTQDIOPEN, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTMAPREMOVE, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTQDICLOSE, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EQURTWAIT, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EMMPMREQUEST, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EMMPMRELEASE, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EMMPMSETPARAM, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EMMPMREGISTER, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_EMMPMGETINFO, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_EMAX_MMPM_CLIENTS, IREE_STATUS_RESOURCE_EXHAUSTED) \ + DSP_ERR_ENTRY(AEE_EDCVSREGISTER, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_PDRREGFAIL, IREE_STATUS_FAILED_PRECONDITION) \ + /* Miscellaneous */ \ + DSP_ERR_ENTRY(AEE_DEFAULT_PROCESS, IREE_STATUS_NOT_FOUND) \ + DSP_ERR_ENTRY(AEE_ENULLCONTEXT, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EINVALIDJOB, IREE_STATUS_INVALID_ARGUMENT) \ + DSP_ERR_ENTRY(AEE_EBUSY, IREE_STATUS_FAILED_PRECONDITION) \ + DSP_ERR_ENTRY(AEE_ESTUBSKELVERMISMATCH, IREE_STATUS_INCOMPATIBLE) \ + DSP_ERR_ENTRY(AEE_EBADHANDLE, IREE_STATUS_INVALID_ARGUMENT) + +// For some unknown reason, the error codes on the Hexagon side have an offset +// added to them. This offset is not effective when including the header with +// the error definitions on the ARM host side, fix this by accepting also the +// offset error code... +#define DSP_ERR_ENTRY(dsp_err_, status_code_) \ + case dsp_err_: \ + case dsp_err_ + 0x80000400: \ + status_code = status_code_; \ + dsp_err_str = #dsp_err_; \ + break; + +iree_status_t iree_hal_hexagon_make_status_from_dsp_err(const char* file, + int line, int dsp_err, + const char* msg) { + iree_status_code_t status_code = IREE_STATUS_UNKNOWN; + const char* dsp_err_str = NULL; + switch (dsp_err) { DSP_ERR_LIST } + if (dsp_err_str) { + return iree_make_status_with_location(file, line, status_code, "%s (%s)", + msg, dsp_err_str); + } else { + return iree_make_status_with_location(file, line, status_code, + "%s (code %d)", msg, dsp_err); + } +} + +// from errno.h and sub-includes +#define ERR_NO_LIST \ + ERR_NO_ENTRY(ECANCELED, IREE_STATUS_CANCELLED) \ + ERR_NO_ENTRY(EBADF, IREE_STATUS_INVALID_ARGUMENT) \ + ERR_NO_ENTRY(EFAULT, IREE_STATUS_INVALID_ARGUMENT) \ + ERR_NO_ENTRY(EINVAL, IREE_STATUS_INVALID_ARGUMENT) \ + ERR_NO_ENTRY(ENODEV, IREE_STATUS_NOT_FOUND) \ + ERR_NO_ENTRY(ENOTDIR, IREE_STATUS_NOT_FOUND) \ + ERR_NO_ENTRY(ENOENT, IREE_STATUS_NOT_FOUND) \ + ERR_NO_ENTRY(ENXIO, IREE_STATUS_NOT_FOUND) \ + ERR_NO_ENTRY(EEXIST, IREE_STATUS_ALREADY_EXISTS) \ + ERR_NO_ENTRY(EACCES, IREE_STATUS_PERMISSION_DENIED) \ + ERR_NO_ENTRY(EPERM, IREE_STATUS_PERMISSION_DENIED) \ + ERR_NO_ENTRY(EROFS, IREE_STATUS_PERMISSION_DENIED) \ + ERR_NO_ENTRY(ENOMEM, IREE_STATUS_RESOURCE_EXHAUSTED) \ + ERR_NO_ENTRY(EIO, IREE_STATUS_RESOURCE_EXHAUSTED) \ + ERR_NO_ENTRY(EMFILE, IREE_STATUS_RESOURCE_EXHAUSTED) \ + ERR_NO_ENTRY(ENOSPC, IREE_STATUS_RESOURCE_EXHAUSTED) \ + ERR_NO_ENTRY(E2BIG, IREE_STATUS_OUT_OF_RANGE) \ + ERR_NO_ENTRY(EFBIG, IREE_STATUS_OUT_OF_RANGE) \ + ERR_NO_ENTRY(EAGAIN, IREE_STATUS_DEFERRED) \ + ERR_NO_ENTRY(EBUSY, IREE_STATUS_DEFERRED) \ + ERR_NO_ENTRY(ENOEXEC, IREE_STATUS_INCOMPATIBLE) + +#define ERR_NO_ENTRY(err_no_, status_code_) \ + case err_no_: \ + status_code = status_code_; \ + break; + +iree_status_t iree_hal_hexagon_make_status_from_errno(const char* file, + int line, + const char* msg) { + int err_no = errno; // read global errno variable once at beginning, + // any syscall might change it + iree_status_code_t status_code = IREE_STATUS_UNKNOWN; + const char* err_str = strerror(err_no); + switch (err_no) { ERR_NO_LIST } + return iree_make_status_with_location(file, line, status_code, "%s (%s)", msg, + err_str); +} + +iree_status_t iree_hal_hexagon_parse_bool_from_string(iree_string_view_t str, + int* parsed) { + static const struct str_parsed_s { + const char* str; + int parsed; + } accepted[] = { + {.str = "true", .parsed = 1}, {.str = "false", .parsed = 0}, + {.str = "yes", .parsed = 1}, {.str = "no", .parsed = 0}, + {.str = "y", .parsed = 1}, {.str = "n", .parsed = 0}, + {.str = "1", .parsed = 1}, {.str = "0", .parsed = 0}, + }; + for (size_t i = 0; i < sizeof(accepted) / sizeof(accepted[0]); ++i) { + if (iree_string_view_equal_case(str, + iree_make_cstring_view(accepted[i].str))) { + *parsed = accepted[i].parsed; + return iree_ok_status(); + } + } + return iree_make_status(IREE_STATUS_INVALID_ARGUMENT, + "cannot parse boolean argument"); +}
diff --git a/experimental/runtime/src/iree/hal/drivers/hexagon/utils.h b/experimental/runtime/src/iree/hal/drivers/hexagon/utils.h new file mode 100644 index 0000000..28417c9 --- /dev/null +++ b/experimental/runtime/src/iree/hal/drivers/hexagon/utils.h
@@ -0,0 +1,34 @@ +// Copyright 2026 The IREE Authors +// +// Licensed 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 IREE_HAL_DRIVERS_HEXAGON_UTILS_H_ +#define IREE_HAL_DRIVERS_HEXAGON_UTILS_H_ + +#include "iree/base/api.h" + +/// make an IREE status from a DSP error code +iree_status_t iree_hal_hexagon_make_status_from_dsp_err(const char* file, + int line, int dsp_err, + const char* msg); + +// make an IREE status from a DSP error code and include current file/line +#define IREE_HAL_HEXAGON_MAKE_STATUS_FROM_DSP_ERR(dsp_err, msg) \ + iree_hal_hexagon_make_status_from_dsp_err(__FILE__, __LINE__, dsp_err, msg) + +/// make an IREE status from the errno variable +iree_status_t iree_hal_hexagon_make_status_from_errno(const char* file, + int line, + const char* msg); + +// make an IREE status from the errno variable and include current file/line +#define IREE_HAL_HEXAGON_MAKE_STATUS_FROM_ERRNO(msg) \ + iree_hal_hexagon_make_status_from_errno(__FILE__, __LINE__, msg) + +/// parse a boolean from a string +iree_status_t iree_hal_hexagon_parse_bool_from_string(iree_string_view_t str, + int* parsed); + +#endif // IREE_HAL_DRIVERS_HEXAGON_UTILS_H_