[clang] [CIR] Add a split mode to cir-offload-merge (PR #245157)
via cfe-commits
cfe-commits at lists.llvm.org
Mon Nov 23 00:37:57 PST 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang
Author: David Rivera (RiverDave)
<details>
<summary>Changes</summary>
Add a -split mode to cir-offload-merge, the inverse of -combine (#<!-- -->240322). It takes an offload container and writes each nested module to its own file, so the modules can go back through the regular per-target pipeline after the (future) container passes run.
invocation:
```bash
cir-offload-merge -combine host.cir sm80.cir -o combined.cir
cir-offload-merge -split combined.cir
```
IR:
```mlir
// combined.cir
module attributes {cir.offload.container} {
module @<!-- -->host attributes {
cir.lowering_options = #cir.lowering_options<..., cuda_is_device = false, ...>,
cir.offload.kind = #cir.offload<host>,
cir.offload.source_name = "/src/k.cu",
cir.triple = "x86_64-unknown-linux-gnu", ...} {...}
module @<!-- -->device_0 attributes {
cir.lowering_options = #cir.lowering_options<..., cuda_is_device = true, ...>,
cir.offload.kind = #cir.offload<device>,
cir.offload.source_name = "/src/k.cu",
cir.triple = "nvptx64-nvidia-cuda", ...} {...}
}
```
split files:
```mlir
// k-host-x86_64-unknown-linux-gnu.cir
module @"/src/k.cu" attributes {cir.lowering_options = ..., cir.triple = "x86_64-unknown-linux-gnu", ...} {...}
```
```mlir
// k-cuda-nvptx64-nvidia-cuda.cir
module @"/src/k.cu" attributes {cir.lowering_options = ..., cir.triple = "nvptx64-nvidia-cuda", ...} {...}
```
Few things:
- combine now keeps the module name CIRGen gave each input in cir.offload.source_name. LoweringPrepare names global initializers after the module, so the name has to survive the round trip;
- split restores that name and drops cir.offload.kind and cir.offload.source_name, so each output is the same as the input given to combine;
- output files follow the driver's offload file naming, <stem>-<kind>-<triple>.cir, with the stem taken from the source file and the kind (host, cuda, hip) from position and cir.lowering_options. Devices that end up with the same name, e.g. two archs of one triple, get their index appended. -o sets the prefix instead of the stem;
- split takes exactly one input, and it must be an offload container.
---
Full diff: https://github.com/llvm/llvm-project/pull/245157.diff
3 Files Affected:
- (modified) clang/include/clang/CIR/Dialect/IR/CIRDialect.td (+1)
- (modified) clang/test/CIR/Tools/cir-offload-merge.cir (+83-7)
- (modified) clang/tools/cir-offload-merge/cir-offload-merge.cpp (+123-6)
``````````diff
diff --git a/clang/include/clang/CIR/Dialect/IR/CIRDialect.td b/clang/include/clang/CIR/Dialect/IR/CIRDialect.td
index 28b5663c23c49a..9741ae021afa3f 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRDialect.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIRDialect.td
@@ -78,6 +78,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 getOffloadSourceNameAttrName() { return "cir.offload.source_name"; }
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/test/CIR/Tools/cir-offload-merge.cir b/clang/test/CIR/Tools/cir-offload-merge.cir
index 75679b8f7f4247..8b0d93830ce122 100644
--- a/clang/test/CIR/Tools/cir-offload-merge.cir
+++ b/clang/test/CIR/Tools/cir-offload-merge.cir
@@ -8,11 +8,25 @@
// RUN: cir-opt %t/combined.cir --verify-roundtrip -o /dev/null
// COMBINE: module attributes {cir.offload.container} {
-// COMBINE-NEXT: module @host attributes {cir.lowering_options = #cir.lowering_options<{{.*}}cuda_is_device = false{{.*}}>, cir.offload.kind = #cir.offload<host>, cir.triple = "x86_64-unknown-linux-gnu"} {
+// COMBINE-NEXT: module @host attributes {cir.lowering_options = #cir.lowering_options<{{.*}}cuda_is_device = false{{.*}}>, cir.offload.kind = #cir.offload<host>, cir.offload.source_name = "/src/k.cu", cir.triple = "x86_64-unknown-linux-gnu"} {
// COMBINE-NEXT: cir.func{{.*}} @host_fn
-// COMBINE: module @device_0 attributes {cir.lowering_options = #cir.lowering_options<{{.*}}cuda_is_device = true{{.*}}>, cir.offload.kind = #cir.offload<device>, cir.triple = "nvptx64-nvidia-cuda"} {
+// COMBINE: module @device_0 attributes {cir.lowering_options = #cir.lowering_options<{{.*}}cuda_is_device = true{{.*}}>, cir.offload.kind = #cir.offload<device>, cir.offload.source_name = "/src/k.cu", cir.triple = "nvptx64-nvidia-cuda"} {
// COMBINE-NEXT: cir.func{{.*}} @device_fn
+// Split names each output <stem>-<kind>-<triple>.cir, like the driver names
+// offload files, with the stem taken from the source file. Each module gets
+// its original name back.
+// RUN: cir-offload-merge -split %t/combined.cir
+// RUN: FileCheck %s --check-prefix=SPLIT-HOST --implicit-check-not=cir.offload --implicit-check-not=device_fn --input-file=%t/k-host-x86_64-unknown-linux-gnu.cir
+// RUN: FileCheck %s --check-prefix=SPLIT-SM80 --implicit-check-not=cir.offload --implicit-check-not=host_fn --input-file=%t/k-cuda-nvptx64-nvidia-cuda.cir
+// RUN: cir-opt %t/k-host-x86_64-unknown-linux-gnu.cir --verify-roundtrip -o /dev/null
+// RUN: cir-opt %t/k-cuda-nvptx64-nvidia-cuda.cir --verify-roundtrip -o /dev/null
+
+// SPLIT-HOST: module @"/src/k.cu" attributes {cir.lowering_options = #cir.lowering_options<{{.*}}cuda_is_device = false{{.*}}>, cir.triple = "x86_64-unknown-linux-gnu"} {
+// SPLIT-HOST-NEXT: cir.func{{.*}} @host_fn
+// SPLIT-SM80: module @"/src/k.cu" attributes {cir.lowering_options = #cir.lowering_options<{{.*}}cuda_is_device = true{{.*}}>, cir.triple = "nvptx64-nvidia-cuda"} {
+// SPLIT-SM80-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 \
@@ -26,20 +40,51 @@
// REORDER-NEXT: module @host
// REORDER: module @device_0 attributes {{{.*}}cir.offload.kind = #cir.offload<device>, cir.triple = "nvptx64-nvidia-cuda"} {
// REORDER-NEXT: }
-// REORDER-NEXT: module @device_1 attributes {{{.*}}cir.offload.kind = #cir.offload<device>, cir.triple = "nvptx64-nvidia-cuda"} {
+// REORDER-NEXT: module @device_1 attributes {{{.*}}cir.offload.kind = #cir.offload<device>, cir.offload.source_name = "/src/k.cu", cir.triple = "nvptx64-nvidia-cuda"} {
// REORDER-NEXT: cir.func{{.*}} @device_fn
+// -o replaces the directory and stem. Devices that would get the same name
+// get their index among them appended, and a module that had no name gets
+// none back.
+// RUN: mkdir -p %t/out
+// RUN: cir-offload-merge -split %t/reordered.cir -o %t/out/split
+// RUN: FileCheck %s --check-prefix=SPLIT-SM90 --implicit-check-not=cir.offload --input-file=%t/out/split-cuda-nvptx64-nvidia-cuda-0.cir
+// RUN: FileCheck %s --check-prefix=SPLIT-SM80-REORDER --input-file=%t/out/split-cuda-nvptx64-nvidia-cuda-1.cir
+// RUN: test -f %t/out/split-host-x86_64-unknown-linux-gnu.cir
+
+// SPLIT-SM90: module attributes {cir.lowering_options = #cir.lowering_options<{{.*}}>, cir.triple = "nvptx64-nvidia-cuda"} {
+// SPLIT-SM80-REORDER: module @"/src/k.cu"
+// SPLIT-SM80-REORDER-NEXT: cir.func{{.*}} @device_fn
+
+// A split module is printed as a top-level module, so it defines its type
+// aliases instead of spelling every type out at each use.
+// RUN: cir-offload-merge -split %t/aliases.cir
+// Without a source name or triple, the stem is the input's and only the kind
+// is added.
+// RUN: FileCheck %s --check-prefix=SPLIT-ALIASES --input-file=%t/aliases-host.cir
+// RUN: test -f %t/aliases-device.cir
+
+// SPLIT-ALIASES: !s32i = !cir.int<s, 32>
+// SPLIT-ALIASES: module {
+// SPLIT-ALIASES-NEXT: cir.global external @g = #cir.int<0> : !s32i
+
// RUN: cir-offload-merge -combine \
// RUN: %t/host-hip.cir \
-// RUN: %t/device-gfx90a.cir | FileCheck %s --check-prefix=HIP
+// RUN: %t/device-gfx90a.cir -o %t/hip.cir
+// RUN: FileCheck %s --check-prefix=HIP --input-file=%t/hip.cir
+// RUN: cir-offload-merge -split %t/hip.cir
+// RUN: test -f %t/hip-host.cir
+// RUN: test -f %t/hip-hip.cir
// HIP: module @host attributes {cir.lowering_options = #cir.lowering_options<{{.*}}cuda_is_device = false, hip = true{{.*}}>, cir.offload.kind = #cir.offload<host>
// HIP: module @device_0 attributes {{{.*}}cir.lowering_options = #cir.lowering_options<{{.*}}cuda_is_device = true, hip = true{{.*}}>, cir.offload.kind = #cir.offload<device>
// RUN: not cir-offload-merge %t/host.cir -o %t/out.cir 2>&1 | FileCheck %s --check-prefix=ERR-NO-MODE
-// ERR-NO-MODE: error: expected -combine
+// RUN: not cir-offload-merge -combine -split %t/host.cir -o %t/out.cir 2>&1 | FileCheck %s --check-prefix=ERR-NO-MODE
+// ERR-NO-MODE: error: expected exactly one of -combine or -split
// RUN: not cir-offload-merge -combine -o %t/out.cir 2>&1 | FileCheck %s --check-prefix=ERR-NO-INPUT
+// RUN: not cir-offload-merge -split -o %t/out.cir 2>&1 | FileCheck %s --check-prefix=ERR-NO-INPUT
// ERR-NO-INPUT: error: no input files
// RUN: not cir-offload-merge -combine %t/device-sm80.cir -o %t/out.cir 2>&1 | FileCheck %s --check-prefix=ERR-HOSTS
@@ -62,17 +107,29 @@
// ERR-SYCL: device-sycl.cir{{.*}}: error: SYCL compilations are not supported yet
// RUN: not cir-offload-merge -combine %t/invalid.cir %t/device-sm80.cir -o %t/out.cir 2>&1 | FileCheck %s --check-prefix=ERR-PARSE
+// RUN: not cir-offload-merge -split %t/invalid.cir 2>&1 | FileCheck %s --check-prefix=ERR-PARSE
// ERR-PARSE: error: failed to parse input file '{{.*}}invalid.cir'
+// RUN: not cir-offload-merge -split %t/combined.cir %t/combined.cir 2>&1 | FileCheck %s --check-prefix=ERR-SPLIT-INPUTS
+// ERR-SPLIT-INPUTS: error: split mode expects exactly one input
+
+// RUN: not cir-offload-merge -split %t/host.cir 2>&1 | FileCheck %s --check-prefix=ERR-SPLIT-NOT-CONTAINER
+// ERR-SPLIT-NOT-CONTAINER: host.cir{{.*}}: error: expected input to be an offload container
+
+// The container verifier runs when the input is parsed.
+// RUN: not cir-offload-merge -split %t/missing-kind.cir 2>&1 | FileCheck %s --check-prefix=ERR-SPLIT-VERIFY
+// ERR-SPLIT-VERIFY: error: 'builtin.module' op expects 'cir.offload.kind'
+// ERR-SPLIT-VERIFY: error: failed to parse input file '{{.*}}missing-kind.cir'
+
//--- host.cir
-module attributes {cir.lowering_options = #cir.lowering_options<exceptions = false, threadsafe_statics = true, cuda = true, cuda_is_device = false, hip = false, hlsl = false, sycl_is_device = false, gpu_rdc = false, openmp = false, openmp_is_target_device = false, clang_abi_compat = 17, long_double_size = 0, enable_noundef_attrs = false, no_trapping_math = true, ssp_buffer_size = 8>, cir.triple = "x86_64-unknown-linux-gnu"} {
+module @"/src/k.cu" attributes {cir.lowering_options = #cir.lowering_options<exceptions = false, threadsafe_statics = true, cuda = true, cuda_is_device = false, hip = false, hlsl = false, sycl_is_device = false, gpu_rdc = false, openmp = false, openmp_is_target_device = false, clang_abi_compat = 17, long_double_size = 0, enable_noundef_attrs = false, no_trapping_math = true, ssp_buffer_size = 8>, cir.triple = "x86_64-unknown-linux-gnu"} {
cir.func @host_fn() {
cir.return
}
}
//--- device-sm80.cir
-module attributes {cir.lowering_options = #cir.lowering_options<exceptions = false, threadsafe_statics = true, cuda = true, cuda_is_device = true, hip = false, hlsl = false, sycl_is_device = false, gpu_rdc = false, openmp = false, openmp_is_target_device = false, clang_abi_compat = 17, long_double_size = 0, enable_noundef_attrs = false, no_trapping_math = true, ssp_buffer_size = 8>, cir.triple = "nvptx64-nvidia-cuda"} {
+module @"/src/k.cu" attributes {cir.lowering_options = #cir.lowering_options<exceptions = false, threadsafe_statics = true, cuda = true, cuda_is_device = true, hip = false, hlsl = false, sycl_is_device = false, gpu_rdc = false, openmp = false, openmp_is_target_device = false, clang_abi_compat = 17, long_double_size = 0, enable_noundef_attrs = false, no_trapping_math = true, ssp_buffer_size = 8>, cir.triple = "nvptx64-nvidia-cuda"} {
cir.func @device_fn() {
cir.return
}
@@ -104,3 +161,22 @@ module attributes {cir.lowering_options = #cir.lowering_options<exceptions = fal
//--- invalid.cir
module {
+
+//--- aliases.cir
+!s32i = !cir.int<s, 32>
+module attributes {cir.offload.container} {
+ module @host attributes {cir.offload.kind = #cir.offload<host>} {
+ cir.global external @g = #cir.int<0> : !s32i
+ }
+ module @device_0 attributes {cir.offload.kind = #cir.offload<device>} {
+ }
+}
+
+//--- missing-kind.cir
+module attributes {cir.offload.container} {
+ module @host attributes {cir.offload.kind = #cir.offload<host>} {
+ }
+ module @device_0 {
+ }
+}
+
diff --git a/clang/tools/cir-offload-merge/cir-offload-merge.cpp b/clang/tools/cir-offload-merge/cir-offload-merge.cpp
index cde2cd28345fe9..3425d8bf14b307 100644
--- a/clang/tools/cir-offload-merge/cir-offload-merge.cpp
+++ b/clang/tools/cir-offload-merge/cir-offload-merge.cpp
@@ -9,7 +9,8 @@
// \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).
+// `cir.offload.container` unit attribute), and splits such a module back into
+// its nested modules.
//
//===----------------------------------------------------------------------===//
@@ -22,9 +23,12 @@
#include "mlir/Support/FileUtilities.h"
#include "clang/CIR/Dialect/IR/CIRDialect.h"
#include "clang/CIR/InitAllDialects.h"
+#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringMap.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/InitLLVM.h"
+#include "llvm/Support/Path.h"
#include "llvm/Support/ToolOutputFile.h"
#include <optional>
@@ -37,13 +41,19 @@ static llvm::cl::opt<bool> Combine("combine",
llvm::cl::desc("Combine CIR inputs"),
llvm::cl::cat(CIROffloadMergeCategory));
+static llvm::cl::opt<bool> Split("split",
+ llvm::cl::desc("Split a combined CIR input"),
+ llvm::cl::cat(CIROffloadMergeCategory));
+
static llvm::cl::list<std::string>
InputFileNames(llvm::cl::Positional, llvm::cl::desc("<input files>"),
llvm::cl::cat(CIROffloadMergeCategory));
static llvm::cl::opt<std::string>
- OutputFileName("o", llvm::cl::desc("Output CIR file"),
- llvm::cl::value_desc("filename"), llvm::cl::init("-"),
+ OutputFileName("o",
+ llvm::cl::desc("Output CIR file. In split mode, the prefix "
+ "of the per-module output files"),
+ llvm::cl::value_desc("filename"),
llvm::cl::cat(CIROffloadMergeCategory));
// The host/device role and language of a module come from the LangOptions
@@ -72,6 +82,12 @@ getLoweringOptions(mlir::ModuleOp moduleOp) {
static void setOffloadAttrs(mlir::ModuleOp moduleOp, llvm::StringRef name,
cir::OffloadKind offloadKind) {
+ // LoweringPrepare names global initializers after the module, so keep the
+ // name CIRGen gave it for split to restore.
+ if (std::optional<llvm::StringRef> sourceName = moduleOp.getSymName())
+ moduleOp->setAttr(
+ cir::CIRDialect::getOffloadSourceNameAttrName(),
+ mlir::StringAttr::get(moduleOp.getContext(), *sourceName));
moduleOp.setSymName(name);
moduleOp->setAttr(
cir::CIRDialect::getOffloadKindAttrName(),
@@ -164,6 +180,97 @@ static int writeModuleToOutput(mlir::ModuleOp moduleOp,
return 0;
}
+// Undoes setOffloadAttrs.
+static void restoreModule(mlir::ModuleOp moduleOp) {
+ moduleOp->removeAttr(cir::CIRDialect::getOffloadKindAttrName());
+ auto sourceName = moduleOp->getAttrOfType<mlir::StringAttr>(
+ cir::CIRDialect::getOffloadSourceNameAttrName());
+ if (!sourceName) {
+ moduleOp.removeSymNameAttr();
+ return;
+ }
+ moduleOp.setSymNameAttr(sourceName);
+ moduleOp->removeAttr(cir::CIRDialect::getOffloadSourceNameAttrName());
+}
+
+// Follows the driver's naming of offload files: <stem>-<kind>-<triple>. The
+// stem comes from the source file the module was compiled from.
+static std::string getOutputBaseName(mlir::ModuleOp moduleOp, bool isHost,
+ llvm::StringRef inputFileName,
+ llvm::StringRef outputPrefix) {
+ llvm::SmallString<128> baseName(outputPrefix);
+ if (baseName.empty()) {
+ auto sourceName = moduleOp->getAttrOfType<mlir::StringAttr>(
+ cir::CIRDialect::getOffloadSourceNameAttrName());
+ baseName = llvm::sys::path::parent_path(inputFileName);
+ llvm::sys::path::append(
+ baseName, llvm::sys::path::stem(sourceName ? sourceName.getValue()
+ : inputFileName));
+ }
+
+ auto loweringOpts = moduleOp->getAttrOfType<cir::LoweringOptionsAttr>(
+ cir::CIRDialect::getLoweringOptionsAttrName());
+ if (isHost)
+ baseName += "-host";
+ else if (!loweringOpts)
+ baseName += "-device";
+ else
+ baseName += loweringOpts.getHip() ? "-hip" : "-cuda";
+
+ if (auto triple = moduleOp->getAttrOfType<mlir::StringAttr>(
+ cir::CIRDialect::getTripleAttrName())) {
+ baseName += "-";
+ baseName += triple.getValue();
+ }
+ return baseName.str().str();
+}
+
+// Writes each nested module of the container to its own file. Modules that
+// would get the same name, e.g. devices that only differ in their arch, get
+// their index among those modules appended.
+static int splitInput(llvm::StringRef inputFileName,
+ llvm::StringRef outputPrefix,
+ mlir::MLIRContext &context) {
+ mlir::OwningOpRef<mlir::ModuleOp> container =
+ mlir::parseSourceFile<mlir::ModuleOp>(inputFileName,
+ mlir::ParserConfig(&context));
+ if (!container) {
+ mlir::emitError(mlir::UnknownLoc::get(&context))
+ << "failed to parse input file '" << inputFileName << "'";
+ return 1;
+ }
+ if (!(*container)->hasAttr(cir::CIRDialect::getOffloadContainerAttrName())) {
+ mlir::emitError(container->getLoc(),
+ "expected input to be an offload container");
+ return 1;
+ }
+
+ // The container verifier guarantees the host module comes first.
+ llvm::SmallVector<std::pair<mlir::ModuleOp, std::string>> outputs;
+ llvm::StringMap<unsigned> numUses;
+ for (mlir::ModuleOp nestedModule : container->getOps<mlir::ModuleOp>()) {
+ std::string baseName = getOutputBaseName(nestedModule, outputs.empty(),
+ inputFileName, outputPrefix);
+ ++numUses[baseName];
+ outputs.emplace_back(nestedModule, std::move(baseName));
+ }
+
+ llvm::StringMap<unsigned> nextIndex;
+ for (auto &[nestedModule, baseName] : outputs) {
+ std::string outputFileName = baseName;
+ if (numUses[baseName] > 1)
+ outputFileName += "-" + std::to_string(nextIndex[baseName]++);
+ outputFileName += ".cir";
+
+ nestedModule->remove();
+ mlir::OwningOpRef<mlir::ModuleOp> detachedModule(nestedModule);
+ restoreModule(*detachedModule);
+ if (int errorCode = writeModuleToOutput(*detachedModule, outputFileName))
+ return errorCode;
+ }
+ return 0;
+}
+
int main(int argc, char **argv) {
llvm::InitLLVM y(argc, argv);
llvm::cl::HideUnrelatedOptions(CIROffloadMergeCategory);
@@ -176,8 +283,8 @@ int main(int argc, char **argv) {
context.loadDialect<cir::CIRDialect>();
mlir::Location unknownLoc = mlir::UnknownLoc::get(&context);
- if (!Combine) {
- mlir::emitError(unknownLoc, "expected -combine");
+ if (Combine == Split) {
+ mlir::emitError(unknownLoc, "expected exactly one of -combine or -split");
return 1;
}
if (InputFileNames.empty()) {
@@ -185,6 +292,14 @@ int main(int argc, char **argv) {
return 1;
}
+ if (Split) {
+ if (InputFileNames.size() != 1) {
+ mlir::emitError(unknownLoc, "split mode expects exactly one input");
+ return 1;
+ }
+ return splitInput(InputFileNames.front(), OutputFileName, context);
+ }
+
mlir::OwningOpRef<mlir::ModuleOp> container = combineInputs(context);
if (!container)
return 1;
@@ -193,5 +308,7 @@ int main(int argc, char **argv) {
return 1;
}
- return writeModuleToOutput(*container, OutputFileName);
+ llvm::StringRef outputFileName = OutputFileName;
+ return writeModuleToOutput(*container,
+ outputFileName.empty() ? "-" : outputFileName);
}
``````````
</details>
https://github.com/llvm/llvm-project/pull/245157
More information about the cfe-commits
mailing list