https://github.com/RiverDave created 
https://github.com/llvm/llvm-project/pull/240322

Add `cir-offload-merge`, a standalone tool that nests a host CIR module and its 
device CIR modules in an offload container (the `cir.offload.container` module 
added in #206576). This is the first piece of the Host-Device CIR Combine 
Pipeline: passes that need both sides of an offload compilation in one module 
will run on this container, and a split mode will write the modules back out 
per target.

```mlir
cir-offload-merge -combine \
  -input=host.cir -input=gfx90a-xnack-on.cir -input=gfx90a-xnack-off.cir \
  
-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa--gfx90a:xnack+,hip-amdgcn-amd-amdhsa--gfx90a:xnack-
 \
  -output=combined.cir
module attributes {cir.offload.container} {
  module @host attributes {
      cir.offload.bundle_id = "host-x86_64-unknown-linux-gnu",
      cir.offload.kind = #cir.offload<host>, ...} {...}
  module @device_0 attributes {
      cir.offload.bundle_id = "hip-amdgcn-amd-amdhsa--gfx90a:xnack+",
      cir.offload.kind = #cir.offload<device>, ...} {...}
  module @device_1 attributes {
      cir.offload.bundle_id = "hip-amdgcn-amd-amdhsa--gfx90a:xnack-",
      cir.offload.kind = #cir.offload<device>, ...} {...}
}
```
For this patch The tool concretely does:

* pairs each input with an offload bundle ID, `<offload kind>-<target 
triple>[-<target ID>]`, checked with `clang-offload-bundler`'s parser. Exactly 
one host and at least one device target are required, and duplicate targets are 
rejected;
* tags each nested module with `cir.offload.kind` and `cir.offload.bundle_id`, 
and names it `@host` or `@device_<N>`, numbered in -targets order;
* puts the host module first, as the container verifier requires, and verifies 
the container before writing it;
* runs no passes.

To record which compilation each nested module came from, this patch also adds 
`cir.offload.bundle_id`, a string attribute holding the module's bundle ID. 
`cir.offload.kind` only says host or device, and the target triple is not 
enough either: a multi-arch HIP build produces device modules that share a 
triple and only differ in their target ID, as above. Something that will be 
coming in a later PR in the split mode will use the bundle ID to route each 
module to its output. The verifier checks that the attribute is a non-empty 
string on a `builtin.module` and that bundle IDs are unique within a container. 
It is optional, so existing containers stay valid.

Not in this patch: the split mode and the passes that run on the container.

This is part of the Host-Device CIR Combine Pipeline work discussed on 
Discourse: 
https://discourse.llvm.org/t/gsoc-2026-host-device-cir-combine-pipeline-project-idea-discussion/89623

>From e041ce98d0c5487cbdc40a47586142ce4eb4316e Mon Sep 17 00:00:00 2001
From: David Rivera <[email protected]>
Date: Wed, 4 Nov 2026 05:25:01 -0500
Subject: [PATCH 1/3] [CIR] Add cir-offload-merge tool with a combine mode

Nest a host CIR module and its device modules in an offload container.
Add cir.offload.bundle_id to record each module's offload bundle ID, since
modules can share a triple and differ only in target ID.
---
 .../include/clang/CIR/Dialect/IR/CIRAttrs.td  |  30 ++-
 .../clang/CIR/Dialect/IR/CIRDialect.td        |   1 +
 clang/lib/CIR/Dialect/IR/CIRDialect.cpp       |  23 ++
 .../test/CIR/IR/invalid-offload-container.cir |  41 +++
 clang/test/CIR/IR/offload-container.cir       |  16 ++
 clang/test/CIR/Tools/cir-offload-merge.cir    | 101 ++++++++
 clang/test/CMakeLists.txt                     |   2 +
 clang/test/lit.cfg.py                         |   1 +
 clang/tools/CMakeLists.txt                    |   1 +
 clang/tools/cir-offload-merge/CMakeLists.txt  |  23 ++
 .../cir-offload-merge/cir-offload-merge.cpp   | 234 ++++++++++++++++++
 11 files changed, 470 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/CIR/Tools/cir-offload-merge.cir
 create mode 100644 clang/tools/cir-offload-merge/CMakeLists.txt
 create mode 100644 clang/tools/cir-offload-merge/cir-offload-merge.cpp

diff --git a/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td 
b/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td
index 2fb7102b0ccf2c..997cfcb75bbea7 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td
@@ -153,9 +153,33 @@ def CIR_OffloadKindAttr : CIR_EnumAttr<CIR_OffloadKind, 
"offload"> {
     unchanged; the layout above is enforced by the CIR dialect attribute
     verifier, following the `gpu.container_module` precedent.
 
-    The attribute names `cir.offload.container` and `cir.offload.kind` are
-    defined by the `getOffloadContainerAttrName` and `getOffloadKindAttrName`
-    methods in the CIRDialect class.
+    A nested module may also carry `cir.offload.bundle_id`, a string holding
+    the offload bundle ID (`<offload kind>-<target triple>[-<target ID>]`, as
+    used by clang-offload-bundler) of the compilation the module came from,
+    e.g. `"hip-amdgcn-amd-amdhsa--gfx90a:xnack+"`. It identifies a module
+    when splitting the container back into per-target modules; the target
+    triple alone does not, since several device modules may share a triple
+    and only differ in their target ID. Bundle IDs are unique within a
+    container.
+
+    ```mlir
+    module attributes {cir.offload.container} {
+      module @host attributes {
+          cir.offload.kind = #cir.offload<host>,
+          cir.offload.bundle_id = "host-x86_64-unknown-linux-gnu"} {}
+      module @device1 attributes {
+          cir.offload.kind = #cir.offload<device>,
+          cir.offload.bundle_id = "hip-amdgcn-amd-amdhsa--gfx90a:xnack+"} {}
+      module @device2 attributes {
+          cir.offload.kind = #cir.offload<device>,
+          cir.offload.bundle_id = "hip-amdgcn-amd-amdhsa--gfx90a:xnack-"} {}
+    }
+    ```
+
+    The attribute names `cir.offload.container`, `cir.offload.kind` and
+    `cir.offload.bundle_id` are defined by the `getOffloadContainerAttrName`,
+    `getOffloadKindAttrName` and `getOffloadBundleIDAttrName` methods in the
+    CIRDialect class.
   }];
 }
 
diff --git a/clang/include/clang/CIR/Dialect/IR/CIRDialect.td 
b/clang/include/clang/CIR/Dialect/IR/CIRDialect.td
index 31283c32f0e44e..4987788ce3d5b4 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRDialect.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIRDialect.td
@@ -75,6 +75,7 @@ def CIR_Dialect : Dialect {
     static llvm::StringRef getGlobalDtorsAttrName() { return 
"cir.global_dtors"; }
     static llvm::StringRef getOffloadContainerAttrName() { return 
"cir.offload.container"; }
     static llvm::StringRef getOffloadKindAttrName() { return 
"cir.offload.kind"; }
+    static llvm::StringRef getOffloadBundleIDAttrName() { return 
"cir.offload.bundle_id"; }
     static llvm::StringRef getOperandSegmentSizesAttrName() { return 
"operandSegmentSizes"; }
     static llvm::StringRef getNoCallerSavedRegsAttrName() { return 
"no_caller_saved_registers"; }
     static llvm::StringRef getNoCallbackAttrName() { return "nocallback"; }
diff --git a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp 
b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
index 31f8c142acb3c3..c1f65e889faeb9 100644
--- a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
+++ b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
@@ -33,6 +33,7 @@
 #include "clang/CIR/MissingFeatures.h"
 #include "llvm/ADT/SetOperations.h"
 #include "llvm/ADT/SmallSet.h"
+#include "llvm/ADT/StringSet.h"
 #include "llvm/ADT/TypeSwitch.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/LogicalResult.h"
@@ -254,6 +255,16 @@ static LogicalResult 
verifyOffloadContainer(mlir::Operation *op) {
     if (failed(verifyOffloadKind(module, cir::OffloadKind::Device)))
       return failure();
   }
+
+  llvm::StringSet<> bundleIDs;
+  for (auto module : container.getOps<mlir::ModuleOp>()) {
+    auto bundleID = module->getAttrOfType<mlir::StringAttr>(
+        cir::CIRDialect::getOffloadBundleIDAttrName());
+    if (bundleID && !bundleIDs.insert(bundleID.getValue()).second)
+      return module.emitOpError()
+             << "duplicate '" << cir::CIRDialect::getOffloadBundleIDAttrName()
+             << "' value '" << bundleID.getValue() << "'";
+  }
   return success();
 }
 
@@ -304,6 +315,18 @@ cir::CIRDialect::verifyOperationAttribute(mlir::Operation 
*op,
                              << "' attribute to be attached to '"
                              << mlir::ModuleOp::getOperationName() << "'";
 
+  if (attrName == getOffloadBundleIDAttrName()) {
+    if (!mlir::isa<mlir::ModuleOp>(op))
+      return op->emitOpError() << "expects '" << getOffloadBundleIDAttrName()
+                               << "' attribute to be attached to '"
+                               << mlir::ModuleOp::getOperationName() << "'";
+    auto bundleID = mlir::dyn_cast<mlir::StringAttr>(attr.getValue());
+    if (!bundleID || bundleID.getValue().empty())
+      return op->emitOpError() << "expects '" << getOffloadBundleIDAttrName()
+                               << "' to be a non-empty string";
+    return success();
+  }
+
   if (attrName == getModuleFramePointerAttrName()) {
     if (!mlir::isa<mlir::ModuleOp>(op))
       return op->emitOpError() << "expects '" << 
getModuleFramePointerAttrName()
diff --git a/clang/test/CIR/IR/invalid-offload-container.cir 
b/clang/test/CIR/IR/invalid-offload-container.cir
index 95a8c77363efad..3cc8d446633ca4 100644
--- a/clang/test/CIR/IR/invalid-offload-container.cir
+++ b/clang/test/CIR/IR/invalid-offload-container.cir
@@ -78,3 +78,44 @@ module attributes {cir.offload.container = 0 : i32} {
   module @device_0 attributes {cir.offload.kind = #cir.offload<device>} {
   }
 }
+
+// -----
+
+module attributes {cir.offload.container} {
+  module @host attributes {cir.offload.bundle_id = 
"host-x86_64-unknown-linux-gnu", cir.offload.kind = #cir.offload<host>} {
+  }
+  module @device_0 attributes {cir.offload.bundle_id = 
"cuda-nvptx64-nvidia-cuda--sm_80", cir.offload.kind = #cir.offload<device>} {
+  }
+  module @device_1 attributes {cir.offload.bundle_id = 
"cuda-nvptx64-nvidia-cuda--sm_80", cir.offload.kind = #cir.offload<device>} { 
// expected-error {{duplicate 'cir.offload.bundle_id' value 
'cuda-nvptx64-nvidia-cuda--sm_80'}}
+  }
+}
+
+// -----
+
+module {
+  cir.func @f() {
+    cir.return {cir.offload.bundle_id = "host-x86_64-unknown-linux-gnu"} // 
expected-error {{expects 'cir.offload.bundle_id' attribute to be attached to 
'builtin.module'}}
+  }
+}
+
+// -----
+
+module {
+  cir.func @f() {
+    cir.return
+  }
+  // expected-error@+1 {{expects 'cir.offload.bundle_id' to be a non-empty 
string}}
+  module @m attributes {cir.offload.bundle_id = 0 : i32} {
+  }
+}
+
+// -----
+
+module {
+  cir.func @f() {
+    cir.return
+  }
+  // expected-error@+1 {{expects 'cir.offload.bundle_id' to be a non-empty 
string}}
+  module @m attributes {cir.offload.bundle_id = ""} {
+  }
+}
diff --git a/clang/test/CIR/IR/offload-container.cir 
b/clang/test/CIR/IR/offload-container.cir
index 20a5b24cf7465a..ca61f3ad903967 100644
--- a/clang/test/CIR/IR/offload-container.cir
+++ b/clang/test/CIR/IR/offload-container.cir
@@ -26,3 +26,19 @@ module attributes {cir.offload.container} {
 // CHECK-LABEL:   module @host attributes {cir.offload.kind = 
#cir.offload<host>} {
 // CHECK-LABEL:   module @device_0 attributes {cir.offload.kind = 
#cir.offload<device>} {
 // CHECK-LABEL:   module @device_1 attributes {cir.offload.kind = 
#cir.offload<device>} {
+
+// -----
+
+module attributes {cir.offload.container} {
+  module @host attributes {cir.offload.bundle_id = 
"host-x86_64-unknown-linux-gnu", cir.offload.kind = #cir.offload<host>} {
+  }
+  module @device_0 attributes {cir.offload.bundle_id = 
"hip-amdgcn-amd-amdhsa--gfx90a:xnack+", cir.offload.kind = 
#cir.offload<device>} {
+  }
+  module @device_1 attributes {cir.offload.bundle_id = 
"hip-amdgcn-amd-amdhsa--gfx90a:xnack-", cir.offload.kind = 
#cir.offload<device>} {
+  }
+}
+
+// CHECK-LABEL: module attributes {cir.offload.container} {
+// CHECK-LABEL:   module @host attributes {cir.offload.bundle_id = 
"host-x86_64-unknown-linux-gnu", cir.offload.kind = #cir.offload<host>} {
+// CHECK-LABEL:   module @device_0 attributes {cir.offload.bundle_id = 
"hip-amdgcn-amd-amdhsa--gfx90a:xnack+", cir.offload.kind = 
#cir.offload<device>} {
+// CHECK-LABEL:   module @device_1 attributes {cir.offload.bundle_id = 
"hip-amdgcn-amd-amdhsa--gfx90a:xnack-", cir.offload.kind = 
#cir.offload<device>} {
diff --git a/clang/test/CIR/Tools/cir-offload-merge.cir 
b/clang/test/CIR/Tools/cir-offload-merge.cir
new file mode 100644
index 00000000000000..4ccd8c34059ad4
--- /dev/null
+++ b/clang/test/CIR/Tools/cir-offload-merge.cir
@@ -0,0 +1,101 @@
+// RUN: rm -rf %t && split-file %s %t
+
+// RUN: cir-offload-merge -combine \
+// RUN:   -input=%t/host.cir \
+// RUN:   -input=%t/device-sm80.cir \
+// RUN:   
-targets=host-x86_64-unknown-linux-gnu,cuda-nvptx64-nvidia-cuda--sm_80 \
+// RUN:   -output=%t/combined.cir
+// RUN: FileCheck %s --check-prefix=COMBINE --input-file=%t/combined.cir
+// RUN: cir-opt %t/combined.cir --verify-roundtrip -o /dev/null
+
+// COMBINE:      module attributes {cir.offload.container} {
+// COMBINE-NEXT:   module @host attributes {cir.offload.bundle_id = 
"host-x86_64-unknown-linux-gnu", cir.offload.kind = #cir.offload<host>, 
cir.triple = "x86_64-unknown-linux-gnu"} {
+// COMBINE-NEXT:     cir.func{{.*}} @host_fn
+// COMBINE:        module @device_cuda_nvptx64_nvidia_cuda__sm_80 attributes 
{cir.offload.bundle_id = "cuda-nvptx64-nvidia-cuda--sm_80", cir.offload.kind = 
#cir.offload<device>, cir.triple = "nvptx64-nvidia-cuda"} {
+// COMBINE-NEXT:     cir.func{{.*}} @device_fn
+
+// The host module goes first whatever the input order; device modules keep
+// their relative order.
+// RUN: cir-offload-merge -combine \
+// RUN:   -input=%t/device-sm90.cir \
+// RUN:   -input=%t/host.cir \
+// RUN:   -input=%t/device-sm80.cir \
+// RUN:   
-targets=cuda-nvptx64-nvidia-cuda--sm_90,host-x86_64-unknown-linux-gnu,cuda-nvptx64-nvidia-cuda--sm_80
 \
+// RUN:   -output=%t/reordered.cir
+// RUN: FileCheck %s --check-prefix=REORDER --input-file=%t/reordered.cir
+
+// REORDER:      module attributes {cir.offload.container} {
+// REORDER-NEXT:   module @host
+// REORDER:        module @device_cuda_nvptx64_nvidia_cuda__sm_90
+// REORDER:        module @device_cuda_nvptx64_nvidia_cuda__sm_80
+
+// Device modules sharing a triple are told apart by their target ID.
+// RUN: cir-offload-merge -combine \
+// RUN:   -input=%t/host.cir \
+// RUN:   -input=%t/device-gfx90a.cir \
+// RUN:   -input=%t/device-gfx90a.cir \
+// RUN:   
-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa--gfx90a:xnack+,hip-amdgcn-amd-amdhsa--gfx90a:xnack-
 \
+// RUN:   -output=%t/multi-arch.cir
+// RUN: FileCheck %s --check-prefix=MULTI-ARCH --input-file=%t/multi-arch.cir
+
+// MULTI-ARCH: module @device_hip_amdgcn_amd_amdhsa__gfx90a_xnack_ attributes 
{cir.offload.bundle_id = "hip-amdgcn-amd-amdhsa--gfx90a:xnack+"
+// MULTI-ARCH: module @device_hip_amdgcn_amd_amdhsa__gfx90a_xnack__1 
attributes {cir.offload.bundle_id = "hip-amdgcn-amd-amdhsa--gfx90a:xnack-"
+
+// RUN: not cir-offload-merge -input=%t/host.cir 
-targets=host-x86_64-unknown-linux-gnu -output=%t/out.cir 2>&1 | FileCheck %s 
--check-prefix=ERR-NO-MODE
+// ERR-NO-MODE: error: expected -combine
+
+// RUN: not cir-offload-merge -combine -targets=host-x86_64-unknown-linux-gnu 
-output=%t/out.cir 2>&1 | FileCheck %s --check-prefix=ERR-NO-INPUT
+// ERR-NO-INPUT: error: missing required -input
+
+// RUN: not cir-offload-merge -combine -input=%t/host.cir -output=%t/out.cir 
2>&1 | FileCheck %s --check-prefix=ERR-NO-TARGETS
+// ERR-NO-TARGETS: error: missing required -targets
+
+// RUN: not cir-offload-merge -combine -input=%t/host.cir 
-targets=host-x86_64-unknown-linux-gnu 2>&1 | FileCheck %s 
--check-prefix=ERR-NO-OUTPUT
+// ERR-NO-OUTPUT: error: missing required -output
+
+// RUN: not cir-offload-merge -combine -input=%t/host.cir 
-input=%t/device-sm80.cir 
-targets=host-x86_64-unknown-linux-gnu,cuda-nvptx64-nvidia-cuda--sm_80 
-output=%t/a.cir -output=%t/b.cir 2>&1 | FileCheck %s 
--check-prefix=ERR-MULTI-OUTPUT
+// ERR-MULTI-OUTPUT: error: combine mode expects exactly one output
+
+// RUN: not cir-offload-merge -combine -input=%t/host.cir 
-input=%t/device-sm80.cir -targets=host-x86_64-unknown-linux-gnu 
-output=%t/out.cir 2>&1 | FileCheck %s --check-prefix=ERR-COUNT
+// ERR-COUNT: error: number of input files and targets should match in combine 
mode
+
+// RUN: not cir-offload-merge -combine -input=%t/host.cir 
-targets=not-a-target -output=%t/out.cir 2>&1 | FileCheck %s 
--check-prefix=ERR-BAD-TARGET
+// ERR-BAD-TARGET: error: invalid target 'not-a-target'
+
+// RUN: not cir-offload-merge -combine -input=%t/host.cir 
-input=%t/device-sm80.cir 
-targets=cuda-nvptx64-nvidia-cuda--sm_80,cuda-nvptx64-nvidia-cuda--sm_80 
-output=%t/out.cir 2>&1 | FileCheck %s --check-prefix=ERR-DUP-TARGET
+// ERR-DUP-TARGET: error: duplicate target 'cuda-nvptx64-nvidia-cuda--sm_80'
+
+// RUN: not cir-offload-merge -combine -input=%t/device-sm80.cir 
-targets=cuda-nvptx64-nvidia-cuda--sm_80 -output=%t/out.cir 2>&1 | FileCheck %s 
--check-prefix=ERR-NO-HOST
+// RUN: not cir-offload-merge -combine -input=%t/host.cir -input=%t/host.cir 
-targets=host-x86_64-unknown-linux-gnu,host-aarch64-unknown-linux-gnu 
-output=%t/out.cir 2>&1 | FileCheck %s --check-prefix=ERR-NO-HOST
+// ERR-NO-HOST: error: expected exactly one host target
+
+// RUN: not cir-offload-merge -combine -input=%t/host.cir 
-targets=host-x86_64-unknown-linux-gnu -output=%t/out.cir 2>&1 | FileCheck %s 
--check-prefix=ERR-NO-DEVICE
+// ERR-NO-DEVICE: error: expected at least one device target
+
+// RUN: not cir-offload-merge -combine -input=%t/invalid.cir 
-input=%t/device-sm80.cir 
-targets=host-x86_64-unknown-linux-gnu,cuda-nvptx64-nvidia-cuda--sm_80 
-output=%t/out.cir 2>&1 | FileCheck %s --check-prefix=ERR-PARSE
+// ERR-PARSE: error: failed to parse input file
+
+//--- host.cir
+module attributes {cir.triple = "x86_64-unknown-linux-gnu"} {
+  cir.func @host_fn() {
+    cir.return
+  }
+}
+
+//--- device-sm80.cir
+module attributes {cir.triple = "nvptx64-nvidia-cuda"} {
+  cir.func @device_fn() {
+    cir.return
+  }
+}
+
+//--- device-sm90.cir
+module {
+}
+
+//--- device-gfx90a.cir
+module {
+}
+
+//--- invalid.cir
+module {
diff --git a/clang/test/CMakeLists.txt b/clang/test/CMakeLists.txt
index 3cbc8354900fa6..5859a264cf1fd7 100644
--- a/clang/test/CMakeLists.txt
+++ b/clang/test/CMakeLists.txt
@@ -115,6 +115,7 @@ list(APPEND CLANG_TEST_DEPS
 
 if(CLANG_ENABLE_CIR)
   list(APPEND CLANG_TEST_DEPS
+    cir-offload-merge
     cir-opt
     cir-translate
     llvm-strings
@@ -257,6 +258,7 @@ if(CLANG_ENABLE_CIR)
   # directly by tests under clang/test/CIR.
   set(CLANG_CIR_TEST_DEPS
     clang
+    cir-offload-merge
     cir-opt
     cir-translate
     )
diff --git a/clang/test/lit.cfg.py b/clang/test/lit.cfg.py
index bd1dac8044f73b..73b6264ab3d3a8 100644
--- a/clang/test/lit.cfg.py
+++ b/clang/test/lit.cfg.py
@@ -138,6 +138,7 @@
 ]
 
 if config.clang_enable_cir:
+    tools.append("cir-offload-merge")
     tools.append("cir-opt")
 
 if config.clang_examples:
diff --git a/clang/tools/CMakeLists.txt b/clang/tools/CMakeLists.txt
index 855af780d4e02a..81a1e5ced7cf4d 100644
--- a/clang/tools/CMakeLists.txt
+++ b/clang/tools/CMakeLists.txt
@@ -3,6 +3,7 @@ create_subdirectory_options(CLANG TOOL)
 add_clang_subdirectory(diagtool)
 add_clang_subdirectory(driver)
 if(CLANG_ENABLE_CIR)
+  add_clang_subdirectory(cir-offload-merge)
   add_clang_subdirectory(cir-opt)
   add_clang_subdirectory(cir-translate)
   add_clang_subdirectory(cir-lsp-server)
diff --git a/clang/tools/cir-offload-merge/CMakeLists.txt 
b/clang/tools/cir-offload-merge/CMakeLists.txt
new file mode 100644
index 00000000000000..8a7af9e4e51550
--- /dev/null
+++ b/clang/tools/cir-offload-merge/CMakeLists.txt
@@ -0,0 +1,23 @@
+include_directories(${LLVM_MAIN_SRC_DIR}/../mlir/include)
+include_directories(${LLVM_BINARY_DIR}/tools/mlir/include)
+
+add_clang_tool(cir-offload-merge
+  cir-offload-merge.cpp
+)
+
+clang_target_link_libraries(cir-offload-merge
+  PRIVATE
+  clangBasic
+  clangDriver
+)
+
+target_link_libraries(cir-offload-merge
+  PRIVATE
+  CIRRegisterAllDialects
+  MLIRCIR
+  MLIRIR
+  MLIRLLVMDialect
+  MLIRMemRefDialect
+  MLIRParser
+  MLIRSupport
+)
diff --git a/clang/tools/cir-offload-merge/cir-offload-merge.cpp 
b/clang/tools/cir-offload-merge/cir-offload-merge.cpp
new file mode 100644
index 00000000000000..86411316de6592
--- /dev/null
+++ b/clang/tools/cir-offload-merge/cir-offload-merge.cpp
@@ -0,0 +1,234 @@
+//===-- cir-offload-merge/cir-offload-merge.cpp 
---------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// \file
+// This tool combines a host CIR module and its device CIR modules into a
+// single module marked as an offload container (carrying the
+// `cir.offload.container` unit attribute).
+//
+//===----------------------------------------------------------------------===//
+
+#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
+#include "mlir/Dialect/MemRef/IR/MemRef.h"
+#include "mlir/IR/BuiltinAttributes.h"
+#include "mlir/IR/BuiltinOps.h"
+#include "mlir/IR/MLIRContext.h"
+#include "mlir/IR/OwningOpRef.h"
+#include "mlir/IR/Verifier.h"
+#include "mlir/Parser/Parser.h"
+#include "mlir/Support/FileUtilities.h"
+#include "clang/CIR/Dialect/IR/CIRDialect.h"
+#include "clang/CIR/InitAllDialects.h"
+#include "clang/Driver/OffloadBundler.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/ADT/StringSet.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/InitLLVM.h"
+#include "llvm/Support/ToolOutputFile.h"
+#include "llvm/Support/raw_ostream.h"
+
+#include <cctype>
+#include <string>
+
+namespace {
+
+llvm::cl::OptionCategory CIROffloadMergeCategory("cir-offload-merge options");
+
+llvm::cl::opt<bool> Combine("combine", llvm::cl::desc("Combine CIR inputs"),
+                            llvm::cl::cat(CIROffloadMergeCategory));
+
+llvm::cl::list<std::string>
+    InputFileNames("input",
+                   llvm::cl::desc("Input CIR file. Can be specified multiple "
+                                  "times."),
+                   llvm::cl::cat(CIROffloadMergeCategory));
+
+llvm::cl::list<std::string>
+    TargetNames("targets", llvm::cl::CommaSeparated,
+                llvm::cl::desc("[<offload kind>-<target triple>,...]"),
+                llvm::cl::cat(CIROffloadMergeCategory));
+
+llvm::cl::list<std::string>
+    OutputFileNames("output", llvm::cl::desc("Output CIR file."),
+                    llvm::cl::cat(CIROffloadMergeCategory));
+
+struct InputTarget {
+  std::string Input;
+  std::string Target;
+  bool IsHost = false;
+};
+
+int reportError(const llvm::Twine &message) {
+  llvm::errs() << "error: " << message << '\n';
+  return 1;
+}
+
+std::string sanitizeModuleName(llvm::StringRef target) {
+  std::string name = "device_";
+  for (char c : target) {
+    if (std::isalnum(static_cast<unsigned char>(c)))
+      name.push_back(c);
+    else
+      name.push_back('_');
+  }
+  return name;
+}
+
+std::string makeUnique(llvm::StringRef name,
+                       llvm::StringMap<unsigned> &seenNames) {
+  unsigned &count = seenNames[name];
+  if (count++ == 0)
+    return name.str();
+  return (name + "_" + llvm::Twine(count - 1)).str();
+}
+
+bool isValidTarget(llvm::StringRef target,
+                   const clang::OffloadBundlerConfig &bundlerConfig) {
+  if (!clang::checkOffloadBundleID(target))
+    return false;
+
+  clang::OffloadTargetInfo offloadInfo(target, bundlerConfig);
+  // The bundler has no "cuda" offload kind, but CUDA modules are combined 
here.
+  return (offloadInfo.isOffloadKindValid() ||
+          offloadInfo.OffloadKind == "cuda") &&
+         offloadInfo.isTripleValid();
+}
+
+int validateCombineCommandLine(
+    llvm::SmallVectorImpl<InputTarget> &inputTargets) {
+  if (InputFileNames.empty())
+    return reportError("missing required -input");
+  if (TargetNames.empty())
+    return reportError("missing required -targets");
+  if (OutputFileNames.empty())
+    return reportError("missing required -output");
+  if (OutputFileNames.size() != 1)
+    return reportError("combine mode expects exactly one output");
+  if (InputFileNames.size() != TargetNames.size())
+    return reportError("number of input files and targets should match in "
+                       "combine mode");
+
+  clang::OffloadBundlerConfig bundlerConfig;
+  llvm::StringSet<> seenTargets;
+  unsigned numHostTargets = 0;
+
+  for (auto [input, target] : llvm::zip_equal(InputFileNames, TargetNames)) {
+    if (!seenTargets.insert(target).second)
+      return reportError("duplicate target '" + target + "'");
+    if (!isValidTarget(target, bundlerConfig))
+      return reportError("invalid target '" + target + "'");
+
+    bool isHost = clang::OffloadTargetInfo(target, 
bundlerConfig).hasHostKind();
+    numHostTargets += isHost;
+    inputTargets.push_back({input, target, isHost});
+  }
+
+  if (numHostTargets != 1)
+    return reportError("expected exactly one host target");
+  if (inputTargets.size() == 1)
+    return reportError("expected at least one device target");
+  return 0;
+}
+
+void setOffloadAttrs(mlir::ModuleOp module, llvm::StringRef name,
+                     cir::OffloadKind offloadKind, llvm::StringRef bundleID) {
+  module.setSymName(name);
+  module->setAttr(cir::CIRDialect::getOffloadKindAttrName(),
+                  cir::OffloadKindAttr::get(module.getContext(), offloadKind));
+  module->setAttr(cir::CIRDialect::getOffloadBundleIDAttrName(),
+                  mlir::StringAttr::get(module.getContext(), bundleID));
+}
+
+mlir::OwningOpRef<mlir::ModuleOp>
+combineInputs(llvm::ArrayRef<InputTarget> inputTargets,
+              mlir::MLIRContext &context) {
+  mlir::OwningOpRef<mlir::ModuleOp> hostModule;
+  llvm::SmallVector<mlir::OwningOpRef<mlir::ModuleOp>> deviceModules;
+  llvm::StringMap<unsigned> deviceNames;
+
+  for (const InputTarget &inputTarget : inputTargets) {
+    mlir::OwningOpRef<mlir::ModuleOp> module =
+        mlir::parseSourceFile<mlir::ModuleOp>(inputTarget.Input,
+                                              mlir::ParserConfig(&context));
+    if (!module)
+      return {};
+
+    if (inputTarget.IsHost) {
+      setOffloadAttrs(*module, "host", cir::OffloadKind::Host,
+                      inputTarget.Target);
+      hostModule = std::move(module);
+      continue;
+    }
+
+    std::string deviceName =
+        makeUnique(sanitizeModuleName(inputTarget.Target), deviceNames);
+    setOffloadAttrs(*module, deviceName, cir::OffloadKind::Device,
+                    inputTarget.Target);
+    deviceModules.push_back(std::move(module));
+  }
+
+  // The container verifier expects the host module first, followed by the
+  // device modules.
+  mlir::ModuleOp container =
+      mlir::ModuleOp::create(mlir::UnknownLoc::get(&context));
+  container->setAttr(cir::CIRDialect::getOffloadContainerAttrName(),
+                     mlir::UnitAttr::get(&context));
+  container.getBody()->push_back(hostModule.release());
+  for (mlir::OwningOpRef<mlir::ModuleOp> &deviceModule : deviceModules)
+    container.getBody()->push_back(deviceModule.release());
+  return container;
+}
+
+int writeModuleToOutput(mlir::ModuleOp module, llvm::StringRef outputFileName) 
{
+  // Type aliases are only printed for an operation without a parent.
+  assert(!module->getParentOp() && "expected a top-level module");
+  std::string errorMessage;
+  std::unique_ptr<llvm::ToolOutputFile> outputFile =
+      mlir::openOutputFile(outputFileName, &errorMessage);
+  if (!outputFile)
+    return reportError(errorMessage);
+
+  // TODO: Support bytecode output.
+  module->print(outputFile->os());
+  outputFile->os() << '\n';
+  outputFile->keep();
+  return 0;
+}
+
+} // namespace
+
+int main(int argc, char **argv) {
+  llvm::InitLLVM y(argc, argv);
+  llvm::cl::HideUnrelatedOptions(CIROffloadMergeCategory);
+  llvm::cl::ParseCommandLineOptions(argc, argv,
+                                    "CIR host-device offload merge\n");
+
+  if (!Combine)
+    return reportError("expected -combine");
+
+  mlir::DialectRegistry registry;
+  cir::registerAllDialects(registry);
+  registry.insert<mlir::memref::MemRefDialect, mlir::LLVM::LLVMDialect>();
+  mlir::MLIRContext context(registry);
+  context.loadDialect<cir::CIRDialect>();
+
+  llvm::SmallVector<InputTarget> inputTargets;
+  if (int errorCode = validateCombineCommandLine(inputTargets))
+    return errorCode;
+
+  mlir::OwningOpRef<mlir::ModuleOp> container =
+      combineInputs(inputTargets, context);
+  if (!container)
+    return reportError("failed to parse input file");
+  if (mlir::failed(mlir::verify(*container)))
+    return reportError("failed to verify combined module");
+
+  return writeModuleToOutput(*container, OutputFileNames.front());
+}

>From 0c19254766ada182557aaa0ceb074f7dc78415db Mon Sep 17 00:00:00 2001
From: David Rivera <[email protected]>
Date: Mon, 9 Nov 2026 04:32:45 -0500
Subject: [PATCH 2/3] [CIR] Use static functions in cir-offload-merge

Keep the anonymous namespace for the struct only, and comment why the
bundler is used to check targets.
---
 .../cir-offload-merge/cir-offload-merge.cpp   | 54 +++++++++++--------
 1 file changed, 31 insertions(+), 23 deletions(-)

diff --git a/clang/tools/cir-offload-merge/cir-offload-merge.cpp 
b/clang/tools/cir-offload-merge/cir-offload-merge.cpp
index 86411316de6592..664be79c5346cf 100644
--- a/clang/tools/cir-offload-merge/cir-offload-merge.cpp
+++ b/clang/tools/cir-offload-merge/cir-offload-merge.cpp
@@ -37,40 +37,42 @@
 #include <cctype>
 #include <string>
 
-namespace {
-
-llvm::cl::OptionCategory CIROffloadMergeCategory("cir-offload-merge options");
+static llvm::cl::OptionCategory
+    CIROffloadMergeCategory("cir-offload-merge options");
 
-llvm::cl::opt<bool> Combine("combine", llvm::cl::desc("Combine CIR inputs"),
-                            llvm::cl::cat(CIROffloadMergeCategory));
+static llvm::cl::opt<bool> Combine("combine",
+                                   llvm::cl::desc("Combine CIR inputs"),
+                                   llvm::cl::cat(CIROffloadMergeCategory));
 
-llvm::cl::list<std::string>
+static llvm::cl::list<std::string>
     InputFileNames("input",
                    llvm::cl::desc("Input CIR file. Can be specified multiple "
                                   "times."),
                    llvm::cl::cat(CIROffloadMergeCategory));
 
-llvm::cl::list<std::string>
+static llvm::cl::list<std::string>
     TargetNames("targets", llvm::cl::CommaSeparated,
                 llvm::cl::desc("[<offload kind>-<target triple>,...]"),
                 llvm::cl::cat(CIROffloadMergeCategory));
 
-llvm::cl::list<std::string>
+static llvm::cl::list<std::string>
     OutputFileNames("output", llvm::cl::desc("Output CIR file."),
                     llvm::cl::cat(CIROffloadMergeCategory));
 
+namespace {
 struct InputTarget {
   std::string Input;
   std::string Target;
   bool IsHost = false;
 };
+} // namespace
 
-int reportError(const llvm::Twine &message) {
+static int reportError(const llvm::Twine &message) {
   llvm::errs() << "error: " << message << '\n';
   return 1;
 }
 
-std::string sanitizeModuleName(llvm::StringRef target) {
+static std::string sanitizeModuleName(llvm::StringRef target) {
   std::string name = "device_";
   for (char c : target) {
     if (std::isalnum(static_cast<unsigned char>(c)))
@@ -81,16 +83,20 @@ std::string sanitizeModuleName(llvm::StringRef target) {
   return name;
 }
 
-std::string makeUnique(llvm::StringRef name,
-                       llvm::StringMap<unsigned> &seenNames) {
+static std::string makeUnique(llvm::StringRef name,
+                              llvm::StringMap<unsigned> &seenNames) {
   unsigned &count = seenNames[name];
   if (count++ == 0)
     return name.str();
   return (name + "_" + llvm::Twine(count - 1)).str();
 }
 
-bool isValidTarget(llvm::StringRef target,
-                   const clang::OffloadBundlerConfig &bundlerConfig) {
+// Targets are offload bundle IDs, so they are checked with
+// clang-offload-bundler's parser (thus, legalized). checkOffloadBundleID must
+// run first, since OffloadTargetInfo asserts on a malformed ID.
+static bool
+isValidCombineTarget(llvm::StringRef target,
+                     const clang::OffloadBundlerConfig &bundlerConfig) {
   if (!clang::checkOffloadBundleID(target))
     return false;
 
@@ -101,8 +107,8 @@ bool isValidTarget(llvm::StringRef target,
          offloadInfo.isTripleValid();
 }
 
-int validateCombineCommandLine(
-    llvm::SmallVectorImpl<InputTarget> &inputTargets) {
+static int
+validateCombineCommandLine(llvm::SmallVectorImpl<InputTarget> &inputTargets) {
   if (InputFileNames.empty())
     return reportError("missing required -input");
   if (TargetNames.empty())
@@ -115,6 +121,8 @@ int validateCombineCommandLine(
     return reportError("number of input files and targets should match in "
                        "combine mode");
 
+  // OffloadTargetInfo requires a bundler config; the defaults are enough to
+  // parse a target.
   clang::OffloadBundlerConfig bundlerConfig;
   llvm::StringSet<> seenTargets;
   unsigned numHostTargets = 0;
@@ -122,7 +130,7 @@ int validateCombineCommandLine(
   for (auto [input, target] : llvm::zip_equal(InputFileNames, TargetNames)) {
     if (!seenTargets.insert(target).second)
       return reportError("duplicate target '" + target + "'");
-    if (!isValidTarget(target, bundlerConfig))
+    if (!isValidCombineTarget(target, bundlerConfig))
       return reportError("invalid target '" + target + "'");
 
     bool isHost = clang::OffloadTargetInfo(target, 
bundlerConfig).hasHostKind();
@@ -137,8 +145,9 @@ int validateCombineCommandLine(
   return 0;
 }
 
-void setOffloadAttrs(mlir::ModuleOp module, llvm::StringRef name,
-                     cir::OffloadKind offloadKind, llvm::StringRef bundleID) {
+static void setOffloadAttrs(mlir::ModuleOp module, llvm::StringRef name,
+                            cir::OffloadKind offloadKind,
+                            llvm::StringRef bundleID) {
   module.setSymName(name);
   module->setAttr(cir::CIRDialect::getOffloadKindAttrName(),
                   cir::OffloadKindAttr::get(module.getContext(), offloadKind));
@@ -146,7 +155,7 @@ void setOffloadAttrs(mlir::ModuleOp module, llvm::StringRef 
name,
                   mlir::StringAttr::get(module.getContext(), bundleID));
 }
 
-mlir::OwningOpRef<mlir::ModuleOp>
+static mlir::OwningOpRef<mlir::ModuleOp>
 combineInputs(llvm::ArrayRef<InputTarget> inputTargets,
               mlir::MLIRContext &context) {
   mlir::OwningOpRef<mlir::ModuleOp> hostModule;
@@ -186,7 +195,8 @@ combineInputs(llvm::ArrayRef<InputTarget> inputTargets,
   return container;
 }
 
-int writeModuleToOutput(mlir::ModuleOp module, llvm::StringRef outputFileName) 
{
+static int writeModuleToOutput(mlir::ModuleOp module,
+                               llvm::StringRef outputFileName) {
   // Type aliases are only printed for an operation without a parent.
   assert(!module->getParentOp() && "expected a top-level module");
   std::string errorMessage;
@@ -202,8 +212,6 @@ int writeModuleToOutput(mlir::ModuleOp module, 
llvm::StringRef outputFileName) {
   return 0;
 }
 
-} // namespace
-
 int main(int argc, char **argv) {
   llvm::InitLLVM y(argc, argv);
   llvm::cl::HideUnrelatedOptions(CIROffloadMergeCategory);

>From 08e17a00fe832788df7aee2ed62342ebfc9ca42f Mon Sep 17 00:00:00 2001
From: David Rivera <[email protected]>
Date: Mon, 9 Nov 2026 05:22:06 -0500
Subject: [PATCH 3/3] [CIR] Name cir-offload-merge device modules by position

Name device modules @device_0, @device_1, ... in -targets order. The bundle
ID attribute already identifies each module.
---
 clang/test/CIR/Tools/cir-offload-merge.cir    | 10 ++++----
 .../cir-offload-merge/cir-offload-merge.cpp   | 24 +------------------
 2 files changed, 6 insertions(+), 28 deletions(-)

diff --git a/clang/test/CIR/Tools/cir-offload-merge.cir 
b/clang/test/CIR/Tools/cir-offload-merge.cir
index 4ccd8c34059ad4..4c025932e91cca 100644
--- a/clang/test/CIR/Tools/cir-offload-merge.cir
+++ b/clang/test/CIR/Tools/cir-offload-merge.cir
@@ -11,7 +11,7 @@
 // COMBINE:      module attributes {cir.offload.container} {
 // COMBINE-NEXT:   module @host attributes {cir.offload.bundle_id = 
"host-x86_64-unknown-linux-gnu", cir.offload.kind = #cir.offload<host>, 
cir.triple = "x86_64-unknown-linux-gnu"} {
 // COMBINE-NEXT:     cir.func{{.*}} @host_fn
-// COMBINE:        module @device_cuda_nvptx64_nvidia_cuda__sm_80 attributes 
{cir.offload.bundle_id = "cuda-nvptx64-nvidia-cuda--sm_80", cir.offload.kind = 
#cir.offload<device>, cir.triple = "nvptx64-nvidia-cuda"} {
+// COMBINE:        module @device_0 attributes {cir.offload.bundle_id = 
"cuda-nvptx64-nvidia-cuda--sm_80", cir.offload.kind = #cir.offload<device>, 
cir.triple = "nvptx64-nvidia-cuda"} {
 // COMBINE-NEXT:     cir.func{{.*}} @device_fn
 
 // The host module goes first whatever the input order; device modules keep
@@ -26,8 +26,8 @@
 
 // REORDER:      module attributes {cir.offload.container} {
 // REORDER-NEXT:   module @host
-// REORDER:        module @device_cuda_nvptx64_nvidia_cuda__sm_90
-// REORDER:        module @device_cuda_nvptx64_nvidia_cuda__sm_80
+// REORDER:        module @device_0 attributes {cir.offload.bundle_id = 
"cuda-nvptx64-nvidia-cuda--sm_90"
+// REORDER:        module @device_1 attributes {cir.offload.bundle_id = 
"cuda-nvptx64-nvidia-cuda--sm_80"
 
 // Device modules sharing a triple are told apart by their target ID.
 // RUN: cir-offload-merge -combine \
@@ -38,8 +38,8 @@
 // RUN:   -output=%t/multi-arch.cir
 // RUN: FileCheck %s --check-prefix=MULTI-ARCH --input-file=%t/multi-arch.cir
 
-// MULTI-ARCH: module @device_hip_amdgcn_amd_amdhsa__gfx90a_xnack_ attributes 
{cir.offload.bundle_id = "hip-amdgcn-amd-amdhsa--gfx90a:xnack+"
-// MULTI-ARCH: module @device_hip_amdgcn_amd_amdhsa__gfx90a_xnack__1 
attributes {cir.offload.bundle_id = "hip-amdgcn-amd-amdhsa--gfx90a:xnack-"
+// MULTI-ARCH: module @device_0 attributes {cir.offload.bundle_id = 
"hip-amdgcn-amd-amdhsa--gfx90a:xnack+"
+// MULTI-ARCH: module @device_1 attributes {cir.offload.bundle_id = 
"hip-amdgcn-amd-amdhsa--gfx90a:xnack-"
 
 // RUN: not cir-offload-merge -input=%t/host.cir 
-targets=host-x86_64-unknown-linux-gnu -output=%t/out.cir 2>&1 | FileCheck %s 
--check-prefix=ERR-NO-MODE
 // ERR-NO-MODE: error: expected -combine
diff --git a/clang/tools/cir-offload-merge/cir-offload-merge.cpp 
b/clang/tools/cir-offload-merge/cir-offload-merge.cpp
index 664be79c5346cf..942606fb5cf611 100644
--- a/clang/tools/cir-offload-merge/cir-offload-merge.cpp
+++ b/clang/tools/cir-offload-merge/cir-offload-merge.cpp
@@ -27,14 +27,12 @@
 #include "clang/Driver/OffloadBundler.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/ToolOutputFile.h"
 #include "llvm/Support/raw_ostream.h"
 
-#include <cctype>
 #include <string>
 
 static llvm::cl::OptionCategory
@@ -72,25 +70,6 @@ static int reportError(const llvm::Twine &message) {
   return 1;
 }
 
-static std::string sanitizeModuleName(llvm::StringRef target) {
-  std::string name = "device_";
-  for (char c : target) {
-    if (std::isalnum(static_cast<unsigned char>(c)))
-      name.push_back(c);
-    else
-      name.push_back('_');
-  }
-  return name;
-}
-
-static std::string makeUnique(llvm::StringRef name,
-                              llvm::StringMap<unsigned> &seenNames) {
-  unsigned &count = seenNames[name];
-  if (count++ == 0)
-    return name.str();
-  return (name + "_" + llvm::Twine(count - 1)).str();
-}
-
 // Targets are offload bundle IDs, so they are checked with
 // clang-offload-bundler's parser (thus, legalized). checkOffloadBundleID must
 // run first, since OffloadTargetInfo asserts on a malformed ID.
@@ -160,7 +139,6 @@ combineInputs(llvm::ArrayRef<InputTarget> inputTargets,
               mlir::MLIRContext &context) {
   mlir::OwningOpRef<mlir::ModuleOp> hostModule;
   llvm::SmallVector<mlir::OwningOpRef<mlir::ModuleOp>> deviceModules;
-  llvm::StringMap<unsigned> deviceNames;
 
   for (const InputTarget &inputTarget : inputTargets) {
     mlir::OwningOpRef<mlir::ModuleOp> module =
@@ -177,7 +155,7 @@ combineInputs(llvm::ArrayRef<InputTarget> inputTargets,
     }
 
     std::string deviceName =
-        makeUnique(sanitizeModuleName(inputTarget.Target), deviceNames);
+        ("device_" + llvm::Twine(deviceModules.size())).str();
     setOffloadAttrs(*module, deviceName, cir::OffloadKind::Device,
                     inputTarget.Target);
     deviceModules.push_back(std::move(module));

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

Reply via email to