[LLVMCPU] Write embedded executable object data before linking (#25117)

The LLVMCPU pipeline did not serialize inline executable object data
into the temporary file passed to the linker, which then crashed on this
empty file.

Adds a lit test that exercises this path, by attaching a linker script
referencing `iree_hal_executable_library_query` as the inline data (to
avoid binary data).

```mlir
#hal.executable.object<{
    path = "object.o",
    data = "HIDDEN(object_fn = iree_hal_executable_library_query);"
}>
```

Adds a missing null check and drops a redundant file `flush` followed by
a `close` in the same source file.

Assisted-by: Claude Code

---------

Signed-off-by: Romain Paquet <rpaquet@kalrayinc.com>
diff --git a/compiler/plugins/target/LLVMCPU/LLVMCPUTarget.cpp b/compiler/plugins/target/LLVMCPU/LLVMCPUTarget.cpp
index 11ec7df..ae7a1ce 100644
--- a/compiler/plugins/target/LLVMCPU/LLVMCPUTarget.cpp
+++ b/compiler/plugins/target/LLVMCPU/LLVMCPUTarget.cpp
@@ -699,9 +699,12 @@
                        variantOp.getName(), ".o", objectData);
       }
       auto objectFile = Artifact::createTemporary(libraryName, "o");
+      if (!objectFile.outputFile) {
+        return variantOp.emitError()
+               << "failed to create temporary file for the generated object";
+      }
       auto &os = objectFile.outputFile->os();
       os << objectData;
-      os.flush();
       os.close();
       objectFiles.push_back(std::move(objectFile));
     }
@@ -730,9 +733,24 @@
     for (auto [index, attr] : llvm::enumerate(linkerObjectAttrs)) {
       auto objectAttr = cast<IREE::HAL::ExecutableObjectAttr>(attr);
       if (auto dataAttr = objectAttr.getData()) {
-        objectFiles.push_back(Artifact::createTemporary(
+        auto objectFile = Artifact::createTemporary(
             objectFiles.front().path + "_object_" + std::to_string(index),
-            llvm::sys::path::extension(objectAttr.getPath())));
+            llvm::sys::path::extension(objectAttr.getPath()));
+        if (!objectFile.outputFile) {
+          return variantOp.emitError()
+                 << "failed to create temporary file for object "
+                 << objectAttr.getPath();
+        }
+        auto &os = objectFile.outputFile->os();
+        if (failed(dataAttr.serializeToStream(variantOp.getLoc(),
+                                              llvm::endianness::native, os))) {
+          return variantOp.emitError()
+                 << "failed to serialize object " << objectAttr.getPath();
+        }
+        // The stream is buffered and the linker process reads the file from
+        // disk, so flush and close it before linking.
+        objectFile.close();
+        objectFiles.push_back(std::move(objectFile));
       } else {
         auto absolutePath = objectAttr.getAbsolutePath();
         if (failed(absolutePath)) {
diff --git a/compiler/plugins/target/LLVMCPU/test/BUILD.bazel b/compiler/plugins/target/LLVMCPU/test/BUILD.bazel
index 7746d4d..b1a0db4 100644
--- a/compiler/plugins/target/LLVMCPU/test/BUILD.bazel
+++ b/compiler/plugins/target/LLVMCPU/test/BUILD.bazel
@@ -17,6 +17,7 @@
     srcs = enforce_glob(
         # keep sorted
         [
+            "executable_object_data.mlir",
             "hal_target_device_attributes.mlir",
             "materialize_homogeneous_encodings.mlir",
             "smoketest_embedded.mlir",
diff --git a/compiler/plugins/target/LLVMCPU/test/CMakeLists.txt b/compiler/plugins/target/LLVMCPU/test/CMakeLists.txt
index 4c9e39a..9a84159 100644
--- a/compiler/plugins/target/LLVMCPU/test/CMakeLists.txt
+++ b/compiler/plugins/target/LLVMCPU/test/CMakeLists.txt
@@ -14,6 +14,7 @@
   NAME
     lit
   SRCS
+    "executable_object_data.mlir"
     "hal_target_device_attributes.mlir"
     "materialize_homogeneous_encodings.mlir"
     "smoketest_embedded.mlir"
diff --git a/compiler/plugins/target/LLVMCPU/test/executable_object_data.mlir b/compiler/plugins/target/LLVMCPU/test/executable_object_data.mlir
new file mode 100644
index 0000000..73f8e8e
--- /dev/null
+++ b/compiler/plugins/target/LLVMCPU/test/executable_object_data.mlir
@@ -0,0 +1,37 @@
+// RUN: iree-opt \
+// RUN:   --pass-pipeline='builtin.module(hal.executable(iree-hal-serialize-target-executables{target=llvm-cpu}))' \
+// RUN:   %s | FileCheck %s
+
+// Tests that the inline data of an executable object is written to the object
+// file passed to the linker. Only the object defines @object_fn and the
+// embedded linker runs with --no-undefined, so linking fails if that file is
+// empty or its contents have not been flushed.
+
+// The object data is a linker script rather than a relocatable object, so the
+// test needs no binary data. It defines @object_fn as an alias of the library
+// query function, which the generated object always defines.
+
+#executable_target = #hal.executable.target<"llvm-cpu", "embedded-elf-x86_64", {cpu = "generic", target_triple = "x86_64-unknown-unknown-eabi-elf"}>
+#pipeline_layout = #hal.pipeline.layout<bindings = [#hal.pipeline.binding<storage_buffer>]>
+builtin.module {
+  hal.executable public @executable {
+    // CHECK: hal.executable.binary public @embedded_elf_x86_64
+    // CHECK-SAME: format = "embedded-elf-x86_64"
+    hal.executable.variant public @embedded_elf_x86_64 target(#executable_target) objects([
+      #hal.executable.object<{path = "object.o", data = "HIDDEN(object_fn = iree_hal_executable_library_query);"}>
+    ]) {
+      hal.executable.export public @fn ordinal(0) layout(#pipeline_layout) count(%arg0: !hal.device) -> (index, index, index) {
+        %c1 = arith.constant 1 : index
+        hal.return %c1, %c1, %c1 : index, index, index
+      }
+      builtin.module {
+        llvm.func @object_fn() attributes {sym_visibility = "private"}
+        llvm.func @fn(%arg0: !llvm.ptr, %arg1: !llvm.ptr, %arg2: !llvm.ptr) -> i32 {
+          llvm.call @object_fn() : () -> ()
+          %0 = llvm.mlir.constant(0 : i32) : i32
+          llvm.return %0 : i32
+        }
+      }
+    }
+  }
+}