[lld] [RFC][lld][SPIRV] Add support for SPIR-V LTO (PR #178749)
Nick Sarnie via llvm-commits
llvm-commits at lists.llvm.org
Thu Jan 29 12:55:01 PST 2026
https://github.com/sarnex updated https://github.com/llvm/llvm-project/pull/178749
>From d9de594713cb77a7fe89ef697daacda856450ba4 Mon Sep 17 00:00:00 2001
From: Nick Sarnie <nick.sarnie at intel.com>
Date: Thu, 29 Jan 2026 12:03:23 -0800
Subject: [PATCH] [RFC][lld][SPIRV] Add support for SPIR-V LTO
Signed-off-by: Nick Sarnie <nick.sarnie at intel.com>
---
lld/CMakeLists.txt | 1 +
lld/Common/DriverDispatcher.cpp | 1 +
lld/SPIRV/CMakeLists.txt | 23 ++++
lld/SPIRV/Config.h | 23 ++++
lld/SPIRV/Driver.cpp | 122 +++++++++++++++++++
lld/SPIRV/LTO.cpp | 163 ++++++++++++++++++++++++++
lld/SPIRV/LTO.h | 39 ++++++
lld/SPIRV/Options.td | 5 +
lld/include/lld/Common/Driver.h | 6 +-
lld/test/SPIRV/basic.ll | 13 ++
lld/test/lit.cfg.py | 1 +
lld/tools/lld/CMakeLists.txt | 3 +-
lld/tools/lld/lld.cpp | 1 +
lld/unittests/AsLibAll/AllDrivers.cpp | 2 +
lld/unittests/AsLibAll/CMakeLists.txt | 1 +
15 files changed, 401 insertions(+), 3 deletions(-)
create mode 100644 lld/SPIRV/CMakeLists.txt
create mode 100644 lld/SPIRV/Config.h
create mode 100644 lld/SPIRV/Driver.cpp
create mode 100644 lld/SPIRV/LTO.cpp
create mode 100644 lld/SPIRV/LTO.h
create mode 100644 lld/SPIRV/Options.td
create mode 100644 lld/test/SPIRV/basic.ll
diff --git a/lld/CMakeLists.txt b/lld/CMakeLists.txt
index 80e25204a65ee..9333fefbda3e2 100644
--- a/lld/CMakeLists.txt
+++ b/lld/CMakeLists.txt
@@ -205,6 +205,7 @@ add_subdirectory(ELF)
add_subdirectory(MachO)
add_subdirectory(MinGW)
add_subdirectory(wasm)
+add_subdirectory(SPIRV)
add_custom_target(lld-headers)
set_target_properties(lld-headers PROPERTIES FOLDER "Misc")
diff --git a/lld/Common/DriverDispatcher.cpp b/lld/Common/DriverDispatcher.cpp
index 0b71c08094863..e538797415af8 100644
--- a/lld/Common/DriverDispatcher.cpp
+++ b/lld/Common/DriverDispatcher.cpp
@@ -34,6 +34,7 @@ static Flavor getFlavor(StringRef s) {
.CasesLower({"wasm", "ld-wasm"}, Wasm)
.CaseLower("link", WinLink)
.CasesLower({"ld64", "ld64.lld", "darwin"}, Darwin)
+ .CasesLower({"spirv", "spirv-lld"}, Spirv)
.Default(Invalid);
}
diff --git a/lld/SPIRV/CMakeLists.txt b/lld/SPIRV/CMakeLists.txt
new file mode 100644
index 0000000000000..00b7ce89cff87
--- /dev/null
+++ b/lld/SPIRV/CMakeLists.txt
@@ -0,0 +1,23 @@
+set(LLVM_TARGET_DEFINITIONS Options.td)
+tablegen(LLVM Options.inc -gen-opt-parser-defs)
+add_public_tablegen_target(SpirvOptionsTableGen)
+
+add_lld_library(lldSPIRV
+ Driver.cpp
+ LTO.cpp
+
+ LINK_COMPONENTS
+ ${LLVM_TARGETS_TO_BUILD}
+ BinaryFormat
+ LTO
+ MC
+ Passes
+ Support
+
+ LINK_LIBS
+ lldCommon
+
+ DEPENDS
+ SpirvOptionsTableGen
+ intrinsics_gen
+ )
diff --git a/lld/SPIRV/Config.h b/lld/SPIRV/Config.h
new file mode 100644
index 0000000000000..f31f16fcd67c7
--- /dev/null
+++ b/lld/SPIRV/Config.h
@@ -0,0 +1,23 @@
+//===- Config.h -------------------------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLD_SPIRV_CONFIG_H
+#define LLD_SPIRV_CONFIG_H
+
+#include <string>
+
+namespace lld::spirv {
+
+struct Config {
+ std::string targetTriple = "spirv64";
+ unsigned ltoOptLevel = 2;
+};
+
+} // namespace lld::spirv
+
+#endif
diff --git a/lld/SPIRV/Driver.cpp b/lld/SPIRV/Driver.cpp
new file mode 100644
index 0000000000000..1f23dfd3fc264
--- /dev/null
+++ b/lld/SPIRV/Driver.cpp
@@ -0,0 +1,122 @@
+//===- Driver.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
+//
+//===----------------------------------------------------------------------===//
+//
+// Driver for SPIR-V linking
+//
+//===----------------------------------------------------------------------===//
+
+#include "lld/Common/Driver.h"
+#include "Config.h"
+#include "LTO.h"
+#include "lld/Common/CommonLinkerContext.h"
+#include "lld/Common/ErrorHandler.h"
+#include "lld/Common/Memory.h"
+#include "lld/Common/Version.h"
+#include "llvm/BinaryFormat/Magic.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/raw_ostream.h"
+
+using namespace llvm;
+
+namespace lld::spirv {
+
+Config config;
+
+static void initLLVM() {
+ InitializeAllTargets();
+ InitializeAllTargetMCs();
+ InitializeAllAsmPrinters();
+ InitializeAllAsmParsers();
+}
+
+static void printVersion(llvm::raw_ostream &os) {
+ os << getLLDVersion() << "\n";
+}
+
+static void printHelp() {
+ llvm::outs() << "USAGE: spirv-lld [options] file...\n\n"
+ << "OPTIONS:\n"
+ << " -o <path> Output file path\n"
+ << " --version Print version information\n"
+ << " --help Print this help\n";
+}
+
+bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
+ llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
+ auto *context = new CommonLinkerContext;
+ context->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
+ context->e.cleanupCallback = []() { config = Config(); };
+
+ initLLVM();
+
+ // Handle --version and --help
+ for (size_t i = 1; i < args.size(); ++i) {
+ StringRef arg = args[i];
+ if (arg == "--version") {
+ printVersion(stdoutOS);
+ return true;
+ }
+ if (arg == "--help") {
+ printHelp();
+ return true;
+ }
+ }
+
+ // Parse args: -o output, rest are inputs
+ std::string outputFile = "a.out.spv";
+ std::vector<MemoryBufferRef> inputs;
+
+ for (size_t i = 1; i < args.size(); ++i) {
+ StringRef arg = args[i];
+ if (arg == "-o" && i + 1 < args.size()) {
+ outputFile = args[++i];
+ } else {
+ ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr =
+ MemoryBuffer::getFile(arg);
+ if (auto ec = mbOrErr.getError()) {
+ error("cannot open " + arg + ": " + ec.message());
+ continue;
+ }
+ // Only support LTO for now
+ std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
+ if (llvm::identify_magic(mb->getBuffer()) != llvm::file_magic::bitcode) {
+ error(arg + ": not a bitcode file");
+ continue;
+ }
+ inputs.push_back(mb->getMemBufferRef());
+ make<std::unique_ptr<MemoryBuffer>>(std::move(mb));
+ }
+ }
+
+ if (inputs.empty()) {
+ error("no input files");
+ return false;
+ }
+
+ BitcodeCompiler compiler(config);
+ for (MemoryBufferRef mb : inputs)
+ compiler.add(mb);
+
+ std::vector<char> spirvBinary = compiler.compile();
+ if (errorCount())
+ return false;
+
+ std::error_code ec;
+ raw_fd_ostream os(outputFile, ec, sys::fs::OF_None);
+ if (ec) {
+ error("cannot open output file " + outputFile + ": " + ec.message());
+ return false;
+ }
+ os.write(spirvBinary.data(), spirvBinary.size());
+
+ return errorCount() == 0;
+}
+
+} // namespace lld::spirv
diff --git a/lld/SPIRV/LTO.cpp b/lld/SPIRV/LTO.cpp
new file mode 100644
index 0000000000000..5231d49b2d785
--- /dev/null
+++ b/lld/SPIRV/LTO.cpp
@@ -0,0 +1,163 @@
+//===- LTO.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
+//
+//===----------------------------------------------------------------------===//
+
+#include "LTO.h"
+#include "Config.h"
+#include "lld/Common/ErrorHandler.h"
+#include "lld/Common/TargetOptionsCommandFlags.h"
+#include "llvm/IR/DiagnosticPrinter.h"
+#include "llvm/LTO/Config.h"
+#include "llvm/LTO/LTO.h"
+#include "llvm/Support/Caching.h"
+#include "llvm/Support/CodeGen.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Program.h"
+#include "llvm/Support/Threading.h"
+#include "llvm/Support/raw_ostream.h"
+
+using namespace llvm;
+using namespace lld;
+using namespace lld::spirv;
+
+static lto::Config createConfig(Config &config) {
+ lto::Config c;
+ c.OptLevel = config.ltoOptLevel;
+ c.DisableVerify = false;
+ c.DiagHandler = diagnosticHandler;
+ c.DefaultTriple = config.targetTriple;
+ c.Options = lld::initTargetOptionsFromCodeGenFlags();
+ c.RelocModel = Reloc::Static;
+ c.CodeModel = getCodeModelFromCMModel();
+ c.HasWholeProgramVisibility = true;
+ c.CGFileType = CodeGenFileType::ObjectFile;
+ c.OverrideTriple = config.targetTriple;
+ return c;
+}
+
+BitcodeCompiler::BitcodeCompiler(Config &Config) : config(Config) {
+ lto::ThinBackend backend = lto::createInProcessThinBackend(
+ llvm::heavyweight_hardware_concurrency(1));
+ ltoObj = std::make_unique<lto::LTO>(createConfig(config), backend, 1);
+}
+
+void BitcodeCompiler::add(MemoryBufferRef mb) {
+ Expected<std::unique_ptr<lto::InputFile>> objOrErr =
+ lto::InputFile::create(mb);
+ if (!objOrErr) {
+ error("failed to parse bitcode: " + toString(objOrErr.takeError()));
+ return;
+ }
+ std::unique_ptr<lto::InputFile> &obj = *objOrErr;
+
+ std::vector<lto::SymbolResolution> resolutions;
+ resolutions.reserve(obj->symbols().size());
+ for (const lto::InputFile::Symbol &sym : obj->symbols()) {
+ lto::SymbolResolution res;
+ res.Prevailing = !sym.isUndefined();
+ res.FinalDefinitionInLinkageUnit = !sym.isUndefined();
+ res.VisibleToRegularObj = true;
+ res.ExportDynamic = false;
+ res.LinkerRedefined = false;
+ resolutions.push_back(res);
+ }
+
+ if (Error err = ltoObj->add(std::move(obj), std::move(resolutions)))
+ error("failed to add bitcode: " + toString(std::move(err)));
+}
+
+std::vector<char> BitcodeCompiler::compile() {
+ unsigned maxTasks = ltoObj->getMaxTasks();
+ buf.resize(maxTasks);
+ tempFiles.resize(maxTasks);
+
+ // Run LTO to generate SPIR-V modules
+ if (Error err = ltoObj->run([&](size_t task, const Twine &moduleName) {
+ return std::make_unique<CachedFileStream>(
+ std::make_unique<raw_svector_ostream>(buf[task]));
+ })) {
+ error("LTO failed: " + toString(std::move(err)));
+ return {};
+ }
+
+ // Save SPIR-V modules to temp files for spirv-link
+ std::vector<std::string> spirvFiles;
+ for (unsigned i = 0; i < maxTasks; ++i) {
+ if (buf[i].empty())
+ continue;
+
+ SmallString<128> tempPath;
+ std::error_code ec = sys::fs::createTemporaryFile("lto", "spv", tempPath);
+ if (ec) {
+ error("failed to create temp file: " + ec.message());
+ return {};
+ }
+
+ raw_fd_ostream os(tempPath, ec, sys::fs::OF_None);
+ if (ec) {
+ error("failed to open temp file: " + ec.message());
+ return {};
+ }
+ os.write(buf[i].data(), buf[i].size());
+ os.close();
+
+ tempFiles[i] = tempPath.str().str();
+ spirvFiles.push_back(tempFiles[i]);
+ }
+
+ if (spirvFiles.empty()) {
+ error("LTO produced no output");
+ return {};
+ }
+
+ // Use spirv-link to do the actual linking
+ SmallString<128> outputPath;
+ std::error_code ec =
+ sys::fs::createTemporaryFile("linked", "spv", outputPath);
+ if (ec) {
+ error("failed to create output temp file: " + ec.message());
+ return {};
+ }
+ ErrorOr<std::string> spirvLinkPath = sys::findProgramByName("spirv-link");
+ if (!spirvLinkPath) {
+ error("couldn't find path to spirv-link");
+ return {};
+ }
+
+ std::vector<StringRef> linkArgs = {*spirvLinkPath};
+ for (const std::string &f : spirvFiles)
+ linkArgs.push_back(f);
+ linkArgs.push_back("-o");
+ linkArgs.push_back(outputPath);
+
+ std::string errMsg;
+ int result = sys::ExecuteAndWait(linkArgs[0], linkArgs, std::nullopt, {}, 0,
+ 0, &errMsg);
+ if (result != 0) {
+ error("spirv-link failed: " + errMsg);
+ return {};
+ }
+
+ // Read linked output
+ ErrorOr<std::unique_ptr<MemoryBuffer>> bufOrErr =
+ MemoryBuffer::getFile(outputPath);
+ if (auto ec = bufOrErr.getError()) {
+ error("failed to read spirv-link output: " + ec.message());
+ return {};
+ }
+
+ std::vector<char> linkedResult((*bufOrErr)->getBufferStart(),
+ (*bufOrErr)->getBufferEnd());
+
+ // Clean up all temp files
+ sys::fs::remove(outputPath);
+ for (const std::string &f : tempFiles)
+ if (!f.empty())
+ sys::fs::remove(f);
+
+ return linkedResult;
+}
diff --git a/lld/SPIRV/LTO.h b/lld/SPIRV/LTO.h
new file mode 100644
index 0000000000000..44bb72c620bc5
--- /dev/null
+++ b/lld/SPIRV/LTO.h
@@ -0,0 +1,39 @@
+//===- LTO.h ----------------------------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLD_SPIRV_LTO_H
+#define LLD_SPIRV_LTO_H
+
+#include "lld/Common/LLVM.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/LTO/LTO.h"
+#include <memory>
+#include <string>
+#include <vector>
+
+namespace lld::spirv {
+
+struct Config;
+
+class BitcodeCompiler {
+public:
+ BitcodeCompiler(Config &config);
+
+ void add(MemoryBufferRef mb);
+ std::vector<char> compile();
+
+private:
+ Config &config;
+ std::unique_ptr<llvm::lto::LTO> ltoObj;
+ std::vector<SmallString<0>> buf;
+ std::vector<std::string> tempFiles;
+};
+
+} // namespace lld::spirv
+
+#endif
diff --git a/lld/SPIRV/Options.td b/lld/SPIRV/Options.td
new file mode 100644
index 0000000000000..937939f8fc386
--- /dev/null
+++ b/lld/SPIRV/Options.td
@@ -0,0 +1,5 @@
+include "llvm/Option/OptParser.td"
+
+def o : JoinedOrSeparate<["-"], "o">,
+ MetaVarName<"<path>">,
+ HelpText<"Path to output SPIR-V binary">;
diff --git a/lld/include/lld/Common/Driver.h b/lld/include/lld/Common/Driver.h
index 8520e6e7e257c..431e4b08ace42 100644
--- a/lld/include/lld/Common/Driver.h
+++ b/lld/include/lld/Common/Driver.h
@@ -20,6 +20,7 @@ enum Flavor {
WinLink, // -flavor link
Darwin, // -flavor darwin
Wasm, // -flavor wasm
+ Spirv, // -flavor spirv
};
using Driver = bool (*)(llvm::ArrayRef<const char *>, llvm::raw_ostream &,
@@ -61,8 +62,9 @@ Result lldMain(llvm::ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
#define LLD_ALL_DRIVERS \
{ \
{lld::WinLink, &lld::coff::link}, {lld::Gnu, &lld::elf::link}, \
- {lld::MinGW, &lld::mingw::link}, {lld::Darwin, &lld::macho::link}, { \
- lld::Wasm, &lld::wasm::link \
+ {lld::MinGW, &lld::mingw::link}, {lld::Darwin, &lld::macho::link}, \
+ {lld::Wasm, &lld::wasm::link}, { \
+ lld::Spirv, &lld::spirv::link \
} \
}
diff --git a/lld/test/SPIRV/basic.ll b/lld/test/SPIRV/basic.ll
new file mode 100644
index 0000000000000..5613b6b222d10
--- /dev/null
+++ b/lld/test/SPIRV/basic.ll
@@ -0,0 +1,13 @@
+; REQUIRES: spirv, spirv-tools
+; RUN: llvm-as %s -o %t_input.bc
+; RUN: ld.lld -flavor spirv %t_input.bc -o %t_output.spv
+
+; RUN: spirv-lld %t_input.bc -o %t_output2.spv
+
+target datalayout = "e-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-n8:16:32:64"
+target triple = "spirv64-unknown-unknown"
+
+define spir_kernel void @test(i32 addrspace(1)* %ptr) {
+ store i32 42, i32 addrspace(1)* %ptr
+ ret void
+}
diff --git a/lld/test/lit.cfg.py b/lld/test/lit.cfg.py
index 39c3d0aa36bfb..417dd9eb0d57f 100644
--- a/lld/test/lit.cfg.py
+++ b/lld/test/lit.cfg.py
@@ -95,6 +95,7 @@
"MSP430": "msp430",
"PowerPC": "ppc",
"RISCV": "riscv",
+ "SPIRV": "spirv",
"Sparc": "sparc",
"SystemZ": "systemz",
"WebAssembly": "wasm",
diff --git a/lld/tools/lld/CMakeLists.txt b/lld/tools/lld/CMakeLists.txt
index 8498a91597a93..c22d7c6136018 100644
--- a/lld/tools/lld/CMakeLists.txt
+++ b/lld/tools/lld/CMakeLists.txt
@@ -32,11 +32,12 @@ lld_target_link_libraries(lld
lldMachO
lldMinGW
lldWasm
+ lldSPIRV
)
if(NOT LLD_SYMLINKS_TO_CREATE)
set(LLD_SYMLINKS_TO_CREATE
- lld-link ld.lld ld64.lld wasm-ld)
+ lld-link ld.lld ld64.lld wasm-ld spirv-lld)
endif()
foreach(link ${LLD_SYMLINKS_TO_CREATE})
diff --git a/lld/tools/lld/lld.cpp b/lld/tools/lld/lld.cpp
index d6800fa1eea4b..680e6668d6cf8 100644
--- a/lld/tools/lld/lld.cpp
+++ b/lld/tools/lld/lld.cpp
@@ -71,6 +71,7 @@ LLD_HAS_DRIVER(elf)
LLD_HAS_DRIVER(mingw)
LLD_HAS_DRIVER(macho)
LLD_HAS_DRIVER(wasm)
+LLD_HAS_DRIVER(spirv)
int lld_main(int argc, char **argv, const llvm::ToolContext &) {
sys::Process::UseANSIEscapeCodes(true);
diff --git a/lld/unittests/AsLibAll/AllDrivers.cpp b/lld/unittests/AsLibAll/AllDrivers.cpp
index fef3d8ca6f016..9d036d4c80a1e 100644
--- a/lld/unittests/AsLibAll/AllDrivers.cpp
+++ b/lld/unittests/AsLibAll/AllDrivers.cpp
@@ -18,6 +18,7 @@ LLD_HAS_DRIVER(elf)
LLD_HAS_DRIVER(mingw)
LLD_HAS_DRIVER(macho)
LLD_HAS_DRIVER(wasm)
+LLD_HAS_DRIVER(spirv)
static bool lldInvoke(std::vector<const char *> args) {
args.push_back("--version");
@@ -32,4 +33,5 @@ TEST(AsLib, AllDrivers) {
EXPECT_TRUE(lldInvoke({"ld", "-m", "i386pe"})); // MinGW
EXPECT_TRUE(lldInvoke({"lld-link"}));
EXPECT_TRUE(lldInvoke({"wasm-ld"}));
+ EXPECT_TRUE(lldInvoke({"spirv-lld"}));
}
diff --git a/lld/unittests/AsLibAll/CMakeLists.txt b/lld/unittests/AsLibAll/CMakeLists.txt
index a88dc3eb854d4..01057bb72fd6f 100644
--- a/lld/unittests/AsLibAll/CMakeLists.txt
+++ b/lld/unittests/AsLibAll/CMakeLists.txt
@@ -14,4 +14,5 @@ target_link_libraries(LLDAsLibAllTests
lldMachO
lldMinGW
lldWasm
+ lldSPIRV
)
More information about the llvm-commits
mailing list