https://github.com/srividya-sundaram updated https://github.com/llvm/llvm-project/pull/240674
>From 12e50b10dfa7ecd643c4d57d5b62590b1363442f Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Mon, 9 Nov 2026 18:49:21 -0800 Subject: [PATCH 01/21] [clang-linker-wrapper][SYCL] Add --sycl-device-link With --sycl-device-link, clang-linker-wrapper links and wraps the SYCL device code, then copies the wrapped host object to the output instead of running the host linker. The object can be linked later by any host linker. If there is no device code, an empty host object without SYCL runtime registration is written. This is the wrapper part of -fsycl-link support. --- .../linker-wrapper-sycl-device-link.c | 62 ++++++++++++++++++ .../ClangLinkerWrapper.cpp | 63 ++++++++++++++++++- .../clang-linker-wrapper/LinkerWrapperOpts.td | 6 ++ 3 files changed, 129 insertions(+), 2 deletions(-) create mode 100644 clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c diff --git a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c new file mode 100644 index 00000000000000..2601dbcf39d95c --- /dev/null +++ b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c @@ -0,0 +1,62 @@ +// Test --sycl-device-link: SYCL device code is linked and wrapped into a host +// object, which is copied to the output. The host linker is not run. + +// REQUIRES: x86-registered-target +// REQUIRES: spirv-registered-target + +// RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.elf.o +// RUN: %clang -cc1 %s -triple spirv64-unknown-unknown -emit-llvm-bc -o %t.spirv.bc + +// RUN: llvm-offload-binary -o %t.sycl.out \ +// RUN: --image=file=%t.spirv.bc,kind=sycl,triple=spirv64-unknown-unknown,arch=generic +// RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.sycl.o \ +// RUN: -fembed-offload-object=%t.sycl.out + +// RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ +// RUN: --sycl-device-link --linker-path=/usr/bin/ld %t.sycl.o -o dev.o 2>&1 \ +// RUN: | FileCheck %s --check-prefix=LINK --implicit-check-not=/usr/bin/ld +// LINK: "{{.*}}clang{{(.exe)?}}" {{.*}}--target=spirv64-unknown-unknown {{.*}}.o --sycl-link{{$}} +// LINK-NEXT: "cp" {{.*}}dev.o.sycl.image.wrapper{{.*}}.o dev.o{{$}} + +// Archive members are only extracted for the host link, so use +// --whole-archive to device link a static library. +// RUN: rm -f %t.sycl.a && llvm-ar rcs %t.sycl.a %t.sycl.o +// RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ +// RUN: --sycl-device-link --linker-path=/usr/bin/ld --whole-archive %t.sycl.a \ +// RUN: --no-whole-archive -o dev.o 2>&1 \ +// RUN: | FileCheck %s --check-prefix=LINK --implicit-check-not=/usr/bin/ld + +// The output is the wrapped device object with SYCL runtime registration. +// RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu \ +// RUN: --sycl-device-link --linker-path=/usr/bin/ld %t.sycl.o -o %t.dev.o +// RUN: llvm-nm %t.dev.o | FileCheck %s --check-prefix=WRAPPED +// WRAPPED-DAG: .sycl_offloading.binary +// WRAPPED-DAG: U __sycl_register_lib + +// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \ +// RUN: --sycl-device-link --linker-path=/usr/bin/ld %t.sycl.o -o dev.obj 2>&1 \ +// RUN: | FileCheck %s --check-prefix=WIN --implicit-check-not=/usr/bin/ld +// WIN: "copy" {{.*}}dev.obj.sycl.image.wrapper{{.*}}.o dev.obj{{$}} + +// No device code: an empty host object without SYCL runtime registration is +// written to the output. +// RUN: rm -f %t.empty.o +// RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu \ +// RUN: --sycl-device-link --linker-path=/usr/bin/ld %t.elf.o -o %t.empty.o +// RUN: llvm-readobj --file-header %t.empty.o | FileCheck %s --check-prefix=EMPTY +// RUN: llvm-nm %t.empty.o | count 0 +// EMPTY: Format: elf64-x86-64 + +// RUN: llvm-offload-binary -o %t.openmp.out \ +// RUN: --image=file=%t.elf.o,kind=openmp,triple=nvptx64-nvidia-cuda,arch=sm_70 +// RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.openmp.o \ +// RUN: -fembed-offload-object=%t.openmp.out +// RUN: not clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ +// RUN: --sycl-device-link --linker-path=/usr/bin/ld %t.openmp.o -o dev.o 2>&1 \ +// RUN: | FileCheck %s --check-prefix=NOT-SYCL +// NOT-SYCL: error: --sycl-device-link requires SYCL device code, got 'openmp' + +// RUN: not clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ +// RUN: --sycl-device-link --emit-fatbin-only --linker-path=/usr/bin/ld \ +// RUN: %t.sycl.o -o dev.o 2>&1 | FileCheck %s --check-prefix=FATBIN +// FATBIN: error: --sycl-device-link cannot be used with --emit-fatbin-only diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp index 1024d5e6e1a6c8..c083c694705de5 100644 --- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp +++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp @@ -1092,6 +1092,45 @@ Error handleOverrideImages( return Error::success(); } +/// Writes the result of --sycl-device-link to the output file. The wrapped SYCL +/// device object is the final output, so the host linker is not run. +Error emitSYCLDeviceLinkOutput(const cl::LibraryOptionsContext &LibraryOptions, + ArrayRef<StringRef> WrappedFiles, + const ArgList &Args) { + if (WrappedFiles.size() > 1) + return createStringError("expected a single wrapped SYCL device object, " + "got %zu", + WrappedFiles.size()); + + Triple HostTriple( + Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple())); + StringRef File; + if (WrappedFiles.empty()) { + // No device code was linked. Emit an empty host object with no runtime + // registration, so the output can still be used in the host link. + LLVMContext Context; + Module M("offload.wrapper.module", Context); + M.setTargetTriple(HostTriple); + M.setDataLayout(HostTriple.computeDataLayout()); + auto FileOrErr = compileModule(LibraryOptions, M, OFK_SYCL); + if (!FileOrErr) + return FileOrErr.takeError(); + File = *FileOrErr; + } else { + File = WrappedFiles.front(); + } + + if (Verbose || DryRun) + printCommands( + {HostTriple.isOSWindows() ? "copy" : "cp", File, ExecutableName}); + if (DryRun) + return Error::success(); + + if (std::error_code EC = sys::fs::copy_file(File, ExecutableName)) + return createFileError(ExecutableName, EC); + return Error::success(); +} + /// Transforms all the extracted offloading input files into an image that can /// be registered by the runtime. If NeedsWrapping is false, writes bundled /// output directly without wrapping or host linking. @@ -1612,6 +1651,22 @@ int main(int Argc, char **Argv) { // linking. bool EmitFatbinOnly = Args.hasArg(OPT_emit_fatbin_only); + // With --sycl-device-link, the wrapped device object is the output and the + // host linker is not run. + bool SYCLDeviceLink = Args.hasArg(OPT_sycl_device_link); + if (SYCLDeviceLink) { + if (EmitFatbinOnly) + reportError(createStringError( + "--sycl-device-link cannot be used with --emit-fatbin-only")); + for (const SmallVector<OffloadFile> &Files : *DeviceInputFiles) + for (const OffloadFile &File : Files) + if (OffloadKind Kind = File.getBinary()->getOffloadKind(); + Kind != OFK_SYCL) + reportError(createStringError( + "--sycl-device-link requires SYCL device code, got '%s'", + getOffloadKindName(Kind).str().c_str())); + } + // Link and process the device images. The function may emit a direct fat // binary if --emit-fatbin-only is specified. auto FilesOrErr = linkAndWrapDeviceFiles(LibraryOptions, *DeviceInputFiles, @@ -1619,8 +1674,12 @@ int main(int Argc, char **Argv) { if (!FilesOrErr) reportError(FilesOrErr.takeError()); - // Run the host linking job with the rendered arguments. - if (!EmitFatbinOnly) { + if (SYCLDeviceLink) { + if (Error Err = + emitSYCLDeviceLinkOutput(LibraryOptions, *FilesOrErr, Args)) + reportError(std::move(Err)); + } else if (!EmitFatbinOnly) { + // Run the host linking job with the rendered arguments. if (Error Err = runLinker(*FilesOrErr, Args)) reportError(std::move(Err)); } diff --git a/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td b/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td index fc48eac2637eeb..b54e2b0fd24ec5 100644 --- a/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td +++ b/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td @@ -69,6 +69,12 @@ def emit_fatbin_only Flags<[WrapperOnlyOption]>, HelpText<"Emit fat binary directly without wrapping or host linking">; +def sycl_device_link + : Flag<["--"], "sycl-device-link">, + Flags<[WrapperOnlyOption]>, + HelpText<"Link and wrap SYCL device code into a host object without " + "running the host linker">; + def no_canonical_prefixes : Flag<["--"], "no-canonical-prefixes">, Flags<[WrapperOnlyOption]>, HelpText<"Do not resolve symbolic links, turn relative paths into absolute ones, or do anything else to identify the executable">; >From 430a66f1028ba4816252f82bc3fb3756e887d8d9 Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Mon, 9 Nov 2026 18:51:41 -0800 Subject: [PATCH 02/21] [Clang][SYCL] Add -fsycl-link -fsycl-link links and wraps the SYCL device code of the inputs into a host object through clang-linker-wrapper --sycl-device-link. The host linker is not run; the object is used later in a host link. -fsycl-link requires -fsycl and is not allowed with --offload-device-only or --offload-host-only. The default output name is the same as for a host link. --- clang/docs/SYCLSupport.md | 26 ++++++++++ clang/include/clang/Options/Options.td | 3 ++ clang/lib/Driver/Driver.cpp | 17 +++++++ clang/lib/Driver/ToolChains/Clang.cpp | 5 ++ clang/test/Driver/sycl-link.cpp | 70 ++++++++++++++++++++++++++ 5 files changed, 121 insertions(+) create mode 100644 clang/test/Driver/sycl-link.cpp diff --git a/clang/docs/SYCLSupport.md b/clang/docs/SYCLSupport.md index 9eabfd57e55f1c..7cba27bdafa196 100644 --- a/clang/docs/SYCLSupport.md +++ b/clang/docs/SYCLSupport.md @@ -106,3 +106,29 @@ space attributes for pointers: ```C++ //TODO: add support for __attribute__((opencl_global_host)) and __attribute__((opencl_global_device)). ``` + +## Separate device link + +`-fsycl-link` links the SYCL device code of its inputs and wraps the resulting +device image into a host object. The host linker is not run. The object is +then used in a later host link, which can be done by any host linker. + +```console +clang++ -fsycl -c a.cpp b.cpp +clang++ -fsycl -fsycl-link a.o b.o -o dev.o +clang++ main.o a.o b.o dev.o -L<libsycl dir> -lLLVMSYCL -o app +``` + +The host link does not use `-fsycl`. With `-fsycl`, the device code in `a.o` +and `b.o` would be linked and registered a second time. + +If the inputs contain no device code, the output is an empty object without +SYCL runtime registration. + +Device code in a static library is only extracted when the host link would +use the archive member. To device link a whole library, pass it with +`-Wl,--whole-archive libfoo.a -Wl,--no-whole-archive`. + +The output of `-fsycl-link` is not yet supported in a static library: nothing +in it is referenced by the host code, so the host linker does not pull it out +of the archive and the device images are never registered. diff --git a/clang/include/clang/Options/Options.td b/clang/include/clang/Options/Options.td index 81f26bb4791416..818e48613f1281 100644 --- a/clang/include/clang/Options/Options.td +++ b/clang/include/clang/Options/Options.td @@ -7854,6 +7854,9 @@ def fsycl_device_only : Flag<["-"], "fsycl-device-only">, def fsycl_host_only : Flag<["-"], "fsycl-host-only">, Alias<offload_host_only>, HelpText<"Compile SYCL code for host only. Has no " "effect on non-SYCL compilations">; +def fsycl_link : Flag<["-"], "fsycl-link">, + HelpText<"Link and wrap SYCL device code into a host object without running " + "the host linker">; def sycl_link : Flag<["--"], "sycl-link">, Flags<[HelpHidden]>, HelpText<"Perform link through clang-sycl-linker via the target " "offloading toolchain.">; diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp index c6f0bb0325a440..9dfa41e8619ecd 100644 --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -1132,6 +1132,23 @@ void Driver::CreateOffloadingDeviceToolChains(Compilation &C, if (Active) Kinds.insert(Kind); + // -fsycl-link links SYCL device code into a host object, so it needs both + // the host and the device side of a SYCL compilation. + if (Arg *A = C.getInputArgs().getLastArgNoClaim(options::OPT_fsycl_link)) { + if (!IsSYCL) + Diag(clang::diag::err_drv_argument_only_allowed_with) + << A->getSpelling() << "-fsycl"; + else if (const Arg *OnlyArg = C.getInputArgs().getLastArgNoClaim( + options::OPT_offload_device_only, + options::OPT_offload_host_only)) { + // Report the spelling that was used, e.g. -fsycl-device-only. + if (OnlyArg->getAlias()) + OnlyArg = OnlyArg->getAlias(); + Diag(clang::diag::err_drv_argument_not_allowed_with) + << A->getSpelling() << OnlyArg->getSpelling(); + } + } + // We currently don't support any kind of mixed offloading. if (Kinds.size() > 1) { Diag(clang::diag::err_drv_mix_offload) diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index a33b116eda7105..3c2d9c694a9eac 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -10140,6 +10140,11 @@ void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA, for (auto Input : Inputs) CmdArgs.push_back(Input.getFilename()); } else { + // With -fsycl-link, the wrapper writes the wrapped SYCL device object to + // the output and does not run the host link command. + if (C.isOffloadingHostKind(Action::OFK_SYCL) && + Args.hasArg(options::OPT_fsycl_link)) + CmdArgs.push_back("--sycl-device-link"); for (const char *LinkArg : LinkCommand->getArguments()) CmdArgs.push_back(LinkArg); } diff --git a/clang/test/Driver/sycl-link.cpp b/clang/test/Driver/sycl-link.cpp new file mode 100644 index 00000000000000..8182f8007c7ab2 --- /dev/null +++ b/clang/test/Driver/sycl-link.cpp @@ -0,0 +1,70 @@ +/// Test -fsycl-link: the SYCL device code is linked and wrapped into a host +/// object by clang-linker-wrapper, without running the host linker. + +// RUN: touch %t.a.o %t.b.o + +/// clang-linker-wrapper is the only link job, and it gets --sycl-device-link. +// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl -fsycl-link \ +// RUN: %t.a.o %t.b.o -o dev.o 2>&1 | FileCheck %s --check-prefix=LINK +// LINK: clang-linker-wrapper" +// LINK-SAME: "--sycl-device-link" +// LINK-SAME: "-o" "dev.o" + +// RUN: %clang -ccc-print-bindings --target=x86_64-unknown-linux-gnu -fsycl \ +// RUN: -fsycl-link %t.a.o %t.b.o -o dev.o 2>&1 \ +// RUN: | FileCheck %s --check-prefix=BINDINGS +// BINDINGS: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["{{.*}}a.o", "{{.*}}b.o"], output: "dev.o" +// BINDINGS-NOT: {{.}} + +/// The default output name is the same as for a host link. +// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl -fsycl-link \ +// RUN: %t.a.o 2>&1 | FileCheck %s --check-prefix=DEFAULT-NAME +// DEFAULT-NAME: clang-linker-wrapper"{{.*}} "--sycl-device-link"{{.*}} "-o" "a.out" + +/// Source inputs are compiled, then device linked. +// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl -fsycl-link %s \ +// RUN: -o dev.o 2>&1 | FileCheck %s --check-prefix=SOURCE +// SOURCE: "-cc1"{{.*}} "-fsycl-is-device" +// SOURCE: "-cc1"{{.*}} "-fsycl-is-host" +// SOURCE: clang-linker-wrapper"{{.*}} "--sycl-device-link"{{.*}} "-o" "dev.o" + +// RUN: %clang -### --target=x86_64-pc-windows-msvc -fsycl -fsycl-link \ +// RUN: %t.a.o -o dev.obj 2>&1 | FileCheck %s --check-prefix=WINDOWS +// WINDOWS: clang-linker-wrapper"{{.*}} "--sycl-device-link"{{.*}} "-out:dev.obj" +// RUN: %clang -ccc-print-bindings --target=x86_64-pc-windows-msvc -fsycl \ +// RUN: -fsycl-link %t.a.o -o dev.obj 2>&1 \ +// RUN: | FileCheck %s --check-prefix=WINDOWS-BINDINGS +// WINDOWS-BINDINGS: "x86_64-pc-windows-msvc{{.*}}" - "Offload::Linker", inputs: ["{{.*}}a.o"], output: "dev.obj" +// WINDOWS-BINDINGS-NOT: {{.}} + +/// Without -fsycl-link, the host link is run as usual. +// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl %t.a.o 2>&1 \ +// RUN: | FileCheck %s --check-prefix=NO-SYCL-LINK +// NO-SYCL-LINK: clang-linker-wrapper" +// NO-SYCL-LINK-NOT: "--sycl-device-link" + +/// -fsycl-link requires -fsycl. +// RUN: not %clang -### --target=x86_64-unknown-linux-gnu -fsycl-link %t.a.o \ +// RUN: 2>&1 | FileCheck %s --check-prefix=NO-FSYCL +// NO-FSYCL: error: invalid argument '-fsycl-link' only allowed with '-fsycl' + +/// -fsycl-link needs both the host and the device compilation. +// RUN: not %clang -### --target=x86_64-unknown-linux-gnu -fsycl -fsycl-link \ +// RUN: --offload-device-only %t.a.o 2>&1 \ +// RUN: | FileCheck %s --check-prefix=ONLY -DOPT=--offload-device-only +// RUN: not %clang -### --target=x86_64-unknown-linux-gnu -fsycl -fsycl-link \ +// RUN: -fsycl-device-only %t.a.o 2>&1 \ +// RUN: | FileCheck %s --check-prefix=ONLY -DOPT=-fsycl-device-only +// RUN: not %clang -### --target=x86_64-unknown-linux-gnu -fsycl -fsycl-link \ +// RUN: --offload-host-only %t.a.o 2>&1 \ +// RUN: | FileCheck %s --check-prefix=ONLY -DOPT=--offload-host-only +// RUN: not %clang -### --target=x86_64-unknown-linux-gnu -fsycl -fsycl-link \ +// RUN: -fsycl-host-only %t.a.o 2>&1 \ +// RUN: | FileCheck %s --check-prefix=ONLY -DOPT=-fsycl-host-only +// ONLY: error: invalid argument '-fsycl-link' not allowed with '[[OPT]]' + +/// -fsycl-link is unused when there is no link step. +// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl -fsycl-link -c %s \ +// RUN: 2>&1 | FileCheck %s --check-prefix=UNUSED \ +// RUN: --implicit-check-not=--sycl-device-link +// UNUSED: warning: argument unused during compilation: '-fsycl-link' >From c8407af98a29062f56bee0f8aeccf769be6cefbe Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 07:32:22 -0800 Subject: [PATCH 03/21] [clang-linker-wrapper][SYCL] Address review: embed finalized images, check override kinds and missing inputs With --sycl-device-link the device image is already linked, so it is now embedded in .sycl_fatbin instead of .llvm.offloading. A later wrapped host link no longer extracts it and links it again. Also check the kind of --override-image inputs, and report missing input files, since no host linker runs to report them. --- .../linker-wrapper-sycl-device-link.c | 25 ++++++++++++ .../ClangLinkerWrapper.cpp | 39 ++++++++++++++----- 2 files changed, 54 insertions(+), 10 deletions(-) diff --git a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c index 2601dbcf39d95c..cbedb6021a19c8 100644 --- a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c +++ b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c @@ -30,8 +30,19 @@ // RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu \ // RUN: --sycl-device-link --linker-path=/usr/bin/ld %t.sycl.o -o %t.dev.o // RUN: llvm-nm %t.dev.o | FileCheck %s --check-prefix=WRAPPED +// RUN: llvm-readobj --sections %t.dev.o | FileCheck %s --check-prefix=SECTIONS // WRAPPED-DAG: .sycl_offloading.binary // WRAPPED-DAG: U __sycl_register_lib +// SECTIONS-NOT: Name: .llvm.offloading +// SECTIONS: Name: .sycl_fatbin +// SECTIONS-NOT: Name: .llvm.offloading + +// The device image is already linked, so a later wrapped host link does not +// link it again. +// RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ +// RUN: --linker-path=/usr/bin/ld %t.dev.o -o a.out 2>&1 \ +// RUN: | FileCheck %s --check-prefix=RELINK --implicit-check-not=--sycl-link +// RELINK: "/usr/bin/ld" {{.*}}dev.o -o a.out // RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \ // RUN: --sycl-device-link --linker-path=/usr/bin/ld %t.sycl.o -o dev.obj 2>&1 \ @@ -54,8 +65,22 @@ // RUN: not clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ // RUN: --sycl-device-link --linker-path=/usr/bin/ld %t.openmp.o -o dev.o 2>&1 \ // RUN: | FileCheck %s --check-prefix=NOT-SYCL +// RUN: not clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ +// RUN: --sycl-device-link --override-image=openmp=%t.elf.o \ +// RUN: --linker-path=/usr/bin/ld %t.elf.o -o dev.o 2>&1 \ +// RUN: | FileCheck %s --check-prefix=NOT-SYCL // NOT-SYCL: error: --sycl-device-link requires SYCL device code, got 'openmp' +// Without a host link, a missing input must be diagnosed here. +// RUN: not clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ +// RUN: --sycl-device-link --linker-path=/usr/bin/ld %t.sycl.o %t.missing.o \ +// RUN: -o dev.o 2>&1 | FileCheck %s --check-prefix=MISSING -DFILE=%t.missing.o +// RUN: not clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ +// RUN: --sycl-device-link --linker-path=/usr/bin/ld --whole-archive \ +// RUN: %t.missing.o --no-whole-archive -o dev.o 2>&1 \ +// RUN: | FileCheck %s --check-prefix=MISSING -DFILE=%t.missing.o +// MISSING: error: '[[FILE]]': {{[Nn]}}o such file or directory + // RUN: not clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ // RUN: --sycl-device-link --emit-fatbin-only --linker-path=/usr/bin/ld \ // RUN: %t.sycl.o -o dev.o 2>&1 | FileCheck %s --check-prefix=FATBIN diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp index c083c694705de5..d3e0eec39e723b 100644 --- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp +++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp @@ -787,8 +787,15 @@ wrapDeviceImages(const cl::LibraryOptionsContext &LibraryOptions, const ArgList &Args, OffloadKind Kind) { llvm::TimeTraceScope TimeScope("Wrap bundled images"); + // With --sycl-device-link, the wrapped images are already linked. They must + // not be found and linked again if the output goes through another wrapped + // host link, so they are embedded as finalized images. + bool IsFinalizedImage = Kind == OFK_SYCL && Args.hasArg(OPT_sycl_device_link); + // We use the discrete tools if we are in verbose mode with '--save-temps'. - if (Verbose && SaveTemps && !Args.hasArg(OPT_print_wrapped_module)) + // llvm-offload-wrapper cannot embed finalized images. + if (Verbose && SaveTemps && !Args.hasArg(OPT_print_wrapped_module) && + !IsFinalizedImage) return wrapDeviceImagesVerbose(Buffers, Args, Kind); SmallVector<ArrayRef<char>, 4> BuffersToWrap; @@ -824,8 +831,8 @@ wrapDeviceImages(const cl::LibraryOptionsContext &LibraryOptions, case OFK_SYCL: { // TODO: fill these options once the Driver supports them. offloading::SYCLJITOptions Options; - if (Error Err = - offloading::wrapSYCLBinaries(M, BuffersToWrap.front(), Options)) + if (Error Err = offloading::wrapSYCLBinaries(M, BuffersToWrap.front(), + Options, IsFinalizedImage)) return std::move(Err); break; } @@ -1446,8 +1453,16 @@ getDeviceInput(const ArgList &Args) { if (!Filename && Arg->getOption().matches(OPT_library)) return createStringError("unable to find library -l%s", Arg->getValue()); - if (!Filename || !sys::fs::exists(*Filename) || - sys::fs::is_directory(*Filename)) + if (!Filename || !sys::fs::exists(*Filename)) { + // With --sycl-device-link there is no host link to report missing + // inputs. + if (Args.hasArg(OPT_sycl_device_link)) + return createFileError( + Arg->getValue(), + std::make_error_code(std::errc::no_such_file_or_directory)); + continue; + } + if (sys::fs::is_directory(*Filename)) continue; // Unlike `--whole-archive`, `/wholearchive:` applies to a single library. @@ -1658,13 +1673,17 @@ int main(int Argc, char **Argv) { if (EmitFatbinOnly) reportError(createStringError( "--sycl-device-link cannot be used with --emit-fatbin-only")); + auto CheckKind = [](OffloadKind Kind) { + if (Kind != OFK_SYCL) + reportError(createStringError( + "--sycl-device-link requires SYCL device code, got '%s'", + getOffloadKindName(Kind).str().c_str())); + }; for (const SmallVector<OffloadFile> &Files : *DeviceInputFiles) for (const OffloadFile &File : Files) - if (OffloadKind Kind = File.getBinary()->getOffloadKind(); - Kind != OFK_SYCL) - reportError(createStringError( - "--sycl-device-link requires SYCL device code, got '%s'", - getOffloadKindName(Kind).str().c_str())); + CheckKind(File.getBinary()->getOffloadKind()); + for (StringRef Override : Args.getAllArgValues(OPT_override_image)) + CheckKind(getOffloadKind(Override.split('=').first)); } // Link and process the device images. The function may emit a direct fat >From f25480b438cc7ce481cac69991daab4e7d522962 Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 07:34:46 -0800 Subject: [PATCH 04/21] [Clang][SYCL] Address review: pass only link inputs with -fsycl-link, allow --offload-host-device With -fsycl-link no host link runs, so clang-linker-wrapper now gets the link inputs and library paths instead of the host link command with its startup files and default libraries. This also lets the wrapper report missing inputs without tripping over host linker options. --offload-host-device after --offload-device-only or --offload-host-only selects both sides, so it is no longer rejected. --- clang/lib/Driver/Driver.cpp | 13 ++++++++----- clang/lib/Driver/ToolChains/Clang.cpp | 16 +++++++++++----- clang/test/Driver/sycl-link.cpp | 21 ++++++++++++++++----- 3 files changed, 35 insertions(+), 15 deletions(-) diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp index 9dfa41e8619ecd..b320ef3494a613 100644 --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -1138,14 +1138,17 @@ void Driver::CreateOffloadingDeviceToolChains(Compilation &C, if (!IsSYCL) Diag(clang::diag::err_drv_argument_only_allowed_with) << A->getSpelling() << "-fsycl"; - else if (const Arg *OnlyArg = C.getInputArgs().getLastArgNoClaim( + else if (const Arg *ModeArg = C.getInputArgs().getLastArgNoClaim( options::OPT_offload_device_only, - options::OPT_offload_host_only)) { + options::OPT_offload_host_only, + options::OPT_offload_host_device); + ModeArg && + !ModeArg->getOption().matches(options::OPT_offload_host_device)) { // Report the spelling that was used, e.g. -fsycl-device-only. - if (OnlyArg->getAlias()) - OnlyArg = OnlyArg->getAlias(); + if (ModeArg->getAlias()) + ModeArg = ModeArg->getAlias(); Diag(clang::diag::err_drv_argument_not_allowed_with) - << A->getSpelling() << OnlyArg->getSpelling(); + << A->getSpelling() << ModeArg->getSpelling(); } } diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index 3c2d9c694a9eac..f68ac073e9b19c 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -10139,12 +10139,18 @@ void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA, CmdArgs.append({"-o", Output.getFilename()}); for (auto Input : Inputs) CmdArgs.push_back(Input.getFilename()); - } else { + } else if (C.isOffloadingHostKind(Action::OFK_SYCL) && + Args.hasArg(options::OPT_fsycl_link)) { // With -fsycl-link, the wrapper writes the wrapped SYCL device object to - // the output and does not run the host link command. - if (C.isOffloadingHostKind(Action::OFK_SYCL) && - Args.hasArg(options::OPT_fsycl_link)) - CmdArgs.push_back("--sycl-device-link"); + // the output and no host link runs. Pass only the link inputs and library + // paths, not the host link command with its startup files and default + // libraries. + CmdArgs.push_back("--sycl-device-link"); + CmdArgs.append({"-o", Output.getFilename()}); + Args.AddAllArgs(CmdArgs, options::OPT_L); + getToolChain().AddFilePathLibArgs(Args, CmdArgs); + AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA); + } else { for (const char *LinkArg : LinkCommand->getArguments()) CmdArgs.push_back(LinkArg); } diff --git a/clang/test/Driver/sycl-link.cpp b/clang/test/Driver/sycl-link.cpp index 8182f8007c7ab2..d6c1458ddba73a 100644 --- a/clang/test/Driver/sycl-link.cpp +++ b/clang/test/Driver/sycl-link.cpp @@ -3,12 +3,16 @@ // RUN: touch %t.a.o %t.b.o -/// clang-linker-wrapper is the only link job, and it gets --sycl-device-link. +/// clang-linker-wrapper is the only link job, and it gets --sycl-device-link +/// with the link inputs instead of the host link command. // RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl -fsycl-link \ -// RUN: %t.a.o %t.b.o -o dev.o 2>&1 | FileCheck %s --check-prefix=LINK +// RUN: %t.a.o -L/foo -Wl,--whole-archive -lbar -Wl,--no-whole-archive \ +// RUN: %t.b.o -o dev.o 2>&1 \ +// RUN: | FileCheck %s --check-prefix=LINK --implicit-check-not=crt1.o \ +// RUN: --implicit-check-not='"-lc"' // LINK: clang-linker-wrapper" -// LINK-SAME: "--sycl-device-link" -// LINK-SAME: "-o" "dev.o" +// LINK-SAME: "--sycl-device-link" "-o" "dev.o" "-L/foo" +// LINK-SAME: "{{.*}}a.o" "--whole-archive" "-lbar" "--no-whole-archive" "{{.*}}b.o"{{$}} // RUN: %clang -ccc-print-bindings --target=x86_64-unknown-linux-gnu -fsycl \ // RUN: -fsycl-link %t.a.o %t.b.o -o dev.o 2>&1 \ @@ -30,7 +34,7 @@ // RUN: %clang -### --target=x86_64-pc-windows-msvc -fsycl -fsycl-link \ // RUN: %t.a.o -o dev.obj 2>&1 | FileCheck %s --check-prefix=WINDOWS -// WINDOWS: clang-linker-wrapper"{{.*}} "--sycl-device-link"{{.*}} "-out:dev.obj" +// WINDOWS: clang-linker-wrapper"{{.*}} "--sycl-device-link" "-o" "dev.obj" "{{.*}}a.o"{{$}} // RUN: %clang -ccc-print-bindings --target=x86_64-pc-windows-msvc -fsycl \ // RUN: -fsycl-link %t.a.o -o dev.obj 2>&1 \ // RUN: | FileCheck %s --check-prefix=WINDOWS-BINDINGS @@ -63,6 +67,13 @@ // RUN: | FileCheck %s --check-prefix=ONLY -DOPT=-fsycl-host-only // ONLY: error: invalid argument '-fsycl-link' not allowed with '[[OPT]]' +/// The last of the mode options selects the mode. +// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl -fsycl-link \ +// RUN: --offload-device-only --offload-host-device %t.a.o 2>&1 \ +// RUN: | FileCheck %s --check-prefix=HOST-DEVICE +// HOST-DEVICE-NOT: error: +// HOST-DEVICE: clang-linker-wrapper"{{.*}} "--sycl-device-link" + /// -fsycl-link is unused when there is no link step. // RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl -fsycl-link -c %s \ // RUN: 2>&1 | FileCheck %s --check-prefix=UNUSED \ >From 6ac6264902bbd02317845c9f9eb215a6588c88ef Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 07:39:48 -0800 Subject: [PATCH 05/21] [clang-linker-wrapper][SYCL] Address review: keep host linker option values, drop copy print A missing input is not reported when it follows an option the wrapper does not know, since it may be the value of a host linker option such as '-z now'. Also stop printing a copy command that is not run, assert that there is at most one wrapped object, and test the -v --save-temps path. --- .../linker-wrapper-sycl-device-link.c | 28 +++++++++---- .../ClangLinkerWrapper.cpp | 39 +++++++++++-------- 2 files changed, 42 insertions(+), 25 deletions(-) diff --git a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c index cbedb6021a19c8..56b70fd165d94a 100644 --- a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c +++ b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c @@ -15,8 +15,7 @@ // RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ // RUN: --sycl-device-link --linker-path=/usr/bin/ld %t.sycl.o -o dev.o 2>&1 \ // RUN: | FileCheck %s --check-prefix=LINK --implicit-check-not=/usr/bin/ld -// LINK: "{{.*}}clang{{(.exe)?}}" {{.*}}--target=spirv64-unknown-unknown {{.*}}.o --sycl-link{{$}} -// LINK-NEXT: "cp" {{.*}}dev.o.sycl.image.wrapper{{.*}}.o dev.o{{$}} +// LINK: "{{.*}}clang{{(.exe)?}}" {{.*}}--target=spirv64-unknown-unknown {{.*}}sycl-spirv64-unknown-unknown-generic{{.*}}.o --sycl-link{{$}} // Archive members are only extracted for the host link, so use // --whole-archive to device link a static library. @@ -31,8 +30,8 @@ // RUN: --sycl-device-link --linker-path=/usr/bin/ld %t.sycl.o -o %t.dev.o // RUN: llvm-nm %t.dev.o | FileCheck %s --check-prefix=WRAPPED // RUN: llvm-readobj --sections %t.dev.o | FileCheck %s --check-prefix=SECTIONS -// WRAPPED-DAG: .sycl_offloading.binary -// WRAPPED-DAG: U __sycl_register_lib +// WRAPPED-DAG: {{^[0-9a-f]+}} r .sycl_offloading.binary{{$}} +// WRAPPED-DAG: {{^ +}}U __sycl_register_lib{{$}} // SECTIONS-NOT: Name: .llvm.offloading // SECTIONS: Name: .sycl_fatbin // SECTIONS-NOT: Name: .llvm.offloading @@ -44,10 +43,17 @@ // RUN: | FileCheck %s --check-prefix=RELINK --implicit-check-not=--sycl-link // RELINK: "/usr/bin/ld" {{.*}}dev.o -o a.out -// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \ -// RUN: --sycl-device-link --linker-path=/usr/bin/ld %t.sycl.o -o dev.obj 2>&1 \ -// RUN: | FileCheck %s --check-prefix=WIN --implicit-check-not=/usr/bin/ld -// WIN: "copy" {{.*}}dev.obj.sycl.image.wrapper{{.*}}.o dev.obj{{$}} +// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc \ +// RUN: --sycl-device-link --linker-path=link.exe %t.sycl.o -o %t.dev.obj +// RUN: llvm-readobj --file-header %t.dev.obj | FileCheck %s --check-prefix=WIN +// WIN: Format: COFF-x86-64 + +// With -v and --save-temps, the wrapping is still done in-process, because the +// image must be embedded as finalized. +// RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run -v \ +// RUN: --save-temps --sycl-device-link --linker-path=/usr/bin/ld %t.sycl.o \ +// RUN: -o dev.o 2>&1 | FileCheck %s --check-prefix=LINK \ +// RUN: --implicit-check-not=/usr/bin/ld --implicit-check-not=llvm-offload-wrapper // No device code: an empty host object without SYCL runtime registration is // written to the output. @@ -81,6 +87,12 @@ // RUN: | FileCheck %s --check-prefix=MISSING -DFILE=%t.missing.o // MISSING: error: '[[FILE]]': {{[Nn]}}o such file or directory +// A value of a host linker option is not reported as a missing input. +// RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ +// RUN: --sycl-device-link --linker-path=/usr/bin/ld %t.sycl.o -z now \ +// RUN: -Map out.map -o dev.o 2>&1 \ +// RUN: | FileCheck %s --check-prefix=LINK --implicit-check-not=/usr/bin/ld + // RUN: not clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ // RUN: --sycl-device-link --emit-fatbin-only --linker-path=/usr/bin/ld \ // RUN: %t.sycl.o -o dev.o 2>&1 | FileCheck %s --check-prefix=FATBIN diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp index d3e0eec39e723b..bb7dcc77535ee1 100644 --- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp +++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp @@ -36,6 +36,7 @@ #include "llvm/Option/Option.h" #include "llvm/Remarks/HotnessThresholdParser.h" #include "llvm/Support/CommandLine.h" +#include "llvm/Support/Errc.h" #include "llvm/Support/FileOutputBuffer.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/InitLLVM.h" @@ -793,7 +794,7 @@ wrapDeviceImages(const cl::LibraryOptionsContext &LibraryOptions, bool IsFinalizedImage = Kind == OFK_SYCL && Args.hasArg(OPT_sycl_device_link); // We use the discrete tools if we are in verbose mode with '--save-temps'. - // llvm-offload-wrapper cannot embed finalized images. + // llvm-offload-wrapper has no option to embed finalized images. if (Verbose && SaveTemps && !Args.hasArg(OPT_print_wrapped_module) && !IsFinalizedImage) return wrapDeviceImagesVerbose(Buffers, Args, Kind); @@ -1104,17 +1105,15 @@ Error handleOverrideImages( Error emitSYCLDeviceLinkOutput(const cl::LibraryOptionsContext &LibraryOptions, ArrayRef<StringRef> WrappedFiles, const ArgList &Args) { - if (WrappedFiles.size() > 1) - return createStringError("expected a single wrapped SYCL device object, " - "got %zu", - WrappedFiles.size()); + // All inputs are SYCL device code, which is wrapped into a single object. + assert(WrappedFiles.size() <= 1 && "expected one wrapped SYCL object"); - Triple HostTriple( - Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple())); StringRef File; if (WrappedFiles.empty()) { // No device code was linked. Emit an empty host object with no runtime // registration, so the output can still be used in the host link. + Triple HostTriple(Args.getLastArgValue(OPT_host_triple_EQ, + sys::getDefaultTargetTriple())); LLVMContext Context; Module M("offload.wrapper.module", Context); M.setTargetTriple(HostTriple); @@ -1127,9 +1126,6 @@ Error emitSYCLDeviceLinkOutput(const cl::LibraryOptionsContext &LibraryOptions, File = WrappedFiles.front(); } - if (Verbose || DryRun) - printCommands( - {HostTriple.isOSWindows() ? "copy" : "cp", File, ExecutableName}); if (DryRun) return Error::success(); @@ -1435,6 +1431,16 @@ getDeviceInput(const ArgList &Args) { SmallVector<OffloadFile> ObjectFilesToExtract; SmallVector<OffloadFile> ArchiveFilesToExtract; DenseMap<StringRef, StringRef> SourceForImage; + + // With --sycl-device-link no host link runs to report missing inputs, so + // report them here. An input right after an option that is not known here + // may be the value of a host linker option (e.g. '-z now'), so it is skipped + // as in a host link. + bool ReportMissingInputs = Args.hasArg(OPT_sycl_device_link); + DenseSet<unsigned> UnknownOptionIndices; + for (const opt::Arg *Arg : Args.filtered(OPT_UNKNOWN)) + UnknownOptionIndices.insert(Arg->getIndex()); + for (const opt::Arg *Arg : Args.filtered(OPT_INPUT, OPT_library, OPT_wholearchive_file, OPT_whole_archive, OPT_no_whole_archive)) { @@ -1454,12 +1460,11 @@ getDeviceInput(const ArgList &Args) { return createStringError("unable to find library -l%s", Arg->getValue()); if (!Filename || !sys::fs::exists(*Filename)) { - // With --sycl-device-link there is no host link to report missing - // inputs. - if (Args.hasArg(OPT_sycl_device_link)) + if (ReportMissingInputs && + !UnknownOptionIndices.contains(Arg->getIndex() - 1)) return createFileError( - Arg->getValue(), - std::make_error_code(std::errc::no_such_file_or_directory)); + Filename ? *Filename : Arg->getValue(), + make_error_code(errc::no_such_file_or_directory)); continue; } if (sys::fs::is_directory(*Filename)) @@ -1676,8 +1681,8 @@ int main(int Argc, char **Argv) { auto CheckKind = [](OffloadKind Kind) { if (Kind != OFK_SYCL) reportError(createStringError( - "--sycl-device-link requires SYCL device code, got '%s'", - getOffloadKindName(Kind).str().c_str())); + "--sycl-device-link requires SYCL device code, got '" + + getOffloadKindName(Kind) + "'")); }; for (const SmallVector<OffloadFile> &Files : *DeviceInputFiles) for (const OffloadFile &File : Files) >From 1225028580bf8e20e463f0873e9a4a36d6ac70c7 Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 07:41:36 -0800 Subject: [PATCH 06/21] [Clang][SYCL] Address review: forward the sysroot with -fsycl-link, clarify help text clang-linker-wrapper uses the sysroot to find -l and -L= inputs, so pass it with -fsycl-link as the host link does. Also say in the help text and docs how the output is used, and note the Windows library name. --- clang/docs/SYCLSupport.md | 2 ++ clang/include/clang/Options/Options.td | 4 ++-- clang/lib/Driver/ToolChains/Clang.cpp | 9 ++++++--- clang/test/Driver/sycl-link.cpp | 13 ++++++++----- 4 files changed, 18 insertions(+), 10 deletions(-) diff --git a/clang/docs/SYCLSupport.md b/clang/docs/SYCLSupport.md index 7cba27bdafa196..d613617bd6f206 100644 --- a/clang/docs/SYCLSupport.md +++ b/clang/docs/SYCLSupport.md @@ -119,6 +119,8 @@ clang++ -fsycl -fsycl-link a.o b.o -o dev.o clang++ main.o a.o b.o dev.o -L<libsycl dir> -lLLVMSYCL -o app ``` +On Windows, the host link uses `LLVMSYCL.lib` instead of `-lLLVMSYCL`. + The host link does not use `-fsycl`. With `-fsycl`, the device code in `a.o` and `b.o` would be linked and registered a second time. diff --git a/clang/include/clang/Options/Options.td b/clang/include/clang/Options/Options.td index 818e48613f1281..823e8cc7cf7cda 100644 --- a/clang/include/clang/Options/Options.td +++ b/clang/include/clang/Options/Options.td @@ -7855,8 +7855,8 @@ def fsycl_host_only : Flag<["-"], "fsycl-host-only">, Alias<offload_host_only>, HelpText<"Compile SYCL code for host only. Has no " "effect on non-SYCL compilations">; def fsycl_link : Flag<["-"], "fsycl-link">, - HelpText<"Link and wrap SYCL device code into a host object without running " - "the host linker">; + HelpText<"Link SYCL device code and wrap it into a host object for a later " + "host link, without running the host linker">; def sycl_link : Flag<["--"], "sycl-link">, Flags<[HelpHidden]>, HelpText<"Perform link through clang-sycl-linker via the target " "offloading toolchain.">; diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index f68ac073e9b19c..6c1be753f12236 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -10142,11 +10142,14 @@ void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA, } else if (C.isOffloadingHostKind(Action::OFK_SYCL) && Args.hasArg(options::OPT_fsycl_link)) { // With -fsycl-link, the wrapper writes the wrapped SYCL device object to - // the output and no host link runs. Pass only the link inputs and library - // paths, not the host link command with its startup files and default - // libraries. + // the output and no host link runs. Pass only what is needed to find the + // device code: the sysroot, library paths and link inputs. Other host link + // options, startup files and default libraries are not used. CmdArgs.push_back("--sycl-device-link"); CmdArgs.append({"-o", Output.getFilename()}); + const Driver &D = getToolChain().getDriver(); + if (!D.SysRoot.empty()) + CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot)); Args.AddAllArgs(CmdArgs, options::OPT_L); getToolChain().AddFilePathLibArgs(Args, CmdArgs); AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA); diff --git a/clang/test/Driver/sycl-link.cpp b/clang/test/Driver/sycl-link.cpp index d6c1458ddba73a..9d58314f9f9073 100644 --- a/clang/test/Driver/sycl-link.cpp +++ b/clang/test/Driver/sycl-link.cpp @@ -4,15 +4,18 @@ // RUN: touch %t.a.o %t.b.o /// clang-linker-wrapper is the only link job, and it gets --sycl-device-link -/// with the link inputs instead of the host link command. +/// with the sysroot, library paths and link inputs instead of the host link +/// command. // RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl -fsycl-link \ -// RUN: %t.a.o -L/foo -Wl,--whole-archive -lbar -Wl,--no-whole-archive \ -// RUN: %t.b.o -o dev.o 2>&1 \ +// RUN: --sysroot=%S/Inputs/basic_linux_tree %t.a.o -L/foo \ +// RUN: -Wl,--whole-archive -lbar -Wl,--no-whole-archive %t.b.o -o dev.o 2>&1 \ // RUN: | FileCheck %s --check-prefix=LINK --implicit-check-not=crt1.o \ // RUN: --implicit-check-not='"-lc"' // LINK: clang-linker-wrapper" -// LINK-SAME: "--sycl-device-link" "-o" "dev.o" "-L/foo" -// LINK-SAME: "{{.*}}a.o" "--whole-archive" "-lbar" "--no-whole-archive" "{{.*}}b.o"{{$}} +// LINK-SAME: "--sycl-device-link" "-o" "dev.o" +// LINK-SAME: "--sysroot={{[^"]*}}basic_linux_tree" "-L/foo" +// LINK-SAME: "-L{{[^"]*}}basic_linux_tree{{[^"]*}}{{[/\\]+}}usr{{[/\\]+}}lib" +// LINK-SAME: "{{[^"]*}}a.o" "--whole-archive" "-lbar" "--no-whole-archive" "{{[^"]*}}b.o"{{$}} // RUN: %clang -ccc-print-bindings --target=x86_64-unknown-linux-gnu -fsycl \ // RUN: -fsycl-link %t.a.o %t.b.o -o dev.o 2>&1 \ >From 72c11a33bbeee7d13a20dba47757ebba4e0cf19e Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 07:43:08 -0800 Subject: [PATCH 07/21] [clang-linker-wrapper][SYCL] Note which missing inputs are not reported --- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp index bb7dcc77535ee1..34bf137f5322d4 100644 --- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp +++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp @@ -1435,7 +1435,8 @@ getDeviceInput(const ArgList &Args) { // With --sycl-device-link no host link runs to report missing inputs, so // report them here. An input right after an option that is not known here // may be the value of a host linker option (e.g. '-z now'), so it is skipped - // as in a host link. + // as in a host link. Without the host linker's options, a file after an + // unknown flag option is skipped the same way. bool ReportMissingInputs = Args.hasArg(OPT_sycl_device_link); DenseSet<unsigned> UnknownOptionIndices; for (const opt::Arg *Arg : Args.filtered(OPT_UNKNOWN)) >From dbf5d3d5f64f9138b87dce20d24a2ab3e75a7d3c Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 09:05:01 -0800 Subject: [PATCH 08/21] [clang-linker-wrapper][SYCL] Address review: report inputs after '--', allow COFF options The '--' separator is not an option, so a missing input after it is reported. COFF linker options such as /nologo are parsed as inputs, so they are not reported as missing files. Also use --wrapper-verbose in the test so it reaches the verbose wrapping path. --- .../linker-wrapper-sycl-device-link.c | 14 ++++++++++---- .../clang-linker-wrapper/ClangLinkerWrapper.cpp | 15 ++++++++++++--- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c index 56b70fd165d94a..f1c05f5aca9e46 100644 --- a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c +++ b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c @@ -43,14 +43,17 @@ // RUN: | FileCheck %s --check-prefix=RELINK --implicit-check-not=--sycl-link // RELINK: "/usr/bin/ld" {{.*}}dev.o -o a.out +// COFF linker options are not reported as missing inputs. // RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc \ -// RUN: --sycl-device-link --linker-path=link.exe %t.sycl.o -o %t.dev.obj +// RUN: --sycl-device-link --linker-path=link.exe %t.sycl.o /nologo \ +// RUN: /IGNORE:4078 -o %t.dev.obj // RUN: llvm-readobj --file-header %t.dev.obj | FileCheck %s --check-prefix=WIN // WIN: Format: COFF-x86-64 -// With -v and --save-temps, the wrapping is still done in-process, because the -// image must be embedded as finalized. -// RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run -v \ +// With --wrapper-verbose and --save-temps, the wrapping is still done +// in-process, because the image must be embedded as finalized. +// RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ +// RUN: --wrapper-verbose \ // RUN: --save-temps --sycl-device-link --linker-path=/usr/bin/ld %t.sycl.o \ // RUN: -o dev.o 2>&1 | FileCheck %s --check-prefix=LINK \ // RUN: --implicit-check-not=/usr/bin/ld --implicit-check-not=llvm-offload-wrapper @@ -85,6 +88,9 @@ // RUN: --sycl-device-link --linker-path=/usr/bin/ld --whole-archive \ // RUN: %t.missing.o --no-whole-archive -o dev.o 2>&1 \ // RUN: | FileCheck %s --check-prefix=MISSING -DFILE=%t.missing.o +// RUN: not clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ +// RUN: --sycl-device-link --linker-path=/usr/bin/ld -o dev.o -- %t.missing.o \ +// RUN: 2>&1 | FileCheck %s --check-prefix=MISSING -DFILE=%t.missing.o // MISSING: error: '[[FILE]]': {{[Nn]}}o such file or directory // A value of a host linker option is not reported as a missing input. diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp index 34bf137f5322d4..3254f00053bc77 100644 --- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp +++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp @@ -1436,11 +1436,19 @@ getDeviceInput(const ArgList &Args) { // report them here. An input right after an option that is not known here // may be the value of a host linker option (e.g. '-z now'), so it is skipped // as in a host link. Without the host linker's options, a file after an - // unknown flag option is skipped the same way. + // unknown flag option is skipped the same way. The '--' separator is not an + // option. bool ReportMissingInputs = Args.hasArg(OPT_sycl_device_link); DenseSet<unsigned> UnknownOptionIndices; for (const opt::Arg *Arg : Args.filtered(OPT_UNKNOWN)) - UnknownOptionIndices.insert(Arg->getIndex()); + if (Arg->getSpelling() != "--") + UnknownOptionIndices.insert(Arg->getIndex()); + // COFF linker options such as '/nologo' are parsed as inputs. Unlike a path, + // they have no further path separator. + auto IsCOFFLinkerOption = [&](StringRef Input) { + return HostTriple.isOSWindows() && Input.starts_with("/") && + Input.find_first_of("/\\", 1) == StringRef::npos; + }; for (const opt::Arg *Arg : Args.filtered(OPT_INPUT, OPT_library, OPT_wholearchive_file, @@ -1462,7 +1470,8 @@ getDeviceInput(const ArgList &Args) { if (!Filename || !sys::fs::exists(*Filename)) { if (ReportMissingInputs && - !UnknownOptionIndices.contains(Arg->getIndex() - 1)) + !UnknownOptionIndices.contains(Arg->getIndex() - 1) && + !IsCOFFLinkerOption(Arg->getValue())) return createFileError( Filename ? *Filename : Arg->getValue(), make_error_code(errc::no_such_file_or_directory)); >From 246491f7527e02b0db9157d71e7e0a8276525a7b Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 09:07:20 -0800 Subject: [PATCH 09/21] [clang-linker-wrapper][SYCL] Address review: allow COFF options with path values COFF options such as /LIBPATH:C:\dir have path separators in the value, so only the option name before ':' is checked. --- .../linker-wrapper-sycl-device-link.c | 5 ++++- .../tools/clang-linker-wrapper/ClangLinkerWrapper.cpp | 11 +++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c index f1c05f5aca9e46..51c2f721a03c9e 100644 --- a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c +++ b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c @@ -46,7 +46,7 @@ // COFF linker options are not reported as missing inputs. // RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc \ // RUN: --sycl-device-link --linker-path=link.exe %t.sycl.o /nologo \ -// RUN: /IGNORE:4078 -o %t.dev.obj +// RUN: /IGNORE:4078 '/LIBPATH:C:\dir' /OUT:C:/dir/a.exe -o %t.dev.obj // RUN: llvm-readobj --file-header %t.dev.obj | FileCheck %s --check-prefix=WIN // WIN: Format: COFF-x86-64 @@ -91,6 +91,9 @@ // RUN: not clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ // RUN: --sycl-device-link --linker-path=/usr/bin/ld -o dev.o -- %t.missing.o \ // RUN: 2>&1 | FileCheck %s --check-prefix=MISSING -DFILE=%t.missing.o +// RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \ +// RUN: --sycl-device-link --linker-path=link.exe %t.sycl.o %t.missing.o \ +// RUN: -o dev.obj 2>&1 | FileCheck %s --check-prefix=MISSING -DFILE=%t.missing.o // MISSING: error: '[[FILE]]': {{[Nn]}}o such file or directory // A value of a host linker option is not reported as a missing input. diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp index 3254f00053bc77..4ccdf7aaa1f34b 100644 --- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp +++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp @@ -1443,11 +1443,14 @@ getDeviceInput(const ArgList &Args) { for (const opt::Arg *Arg : Args.filtered(OPT_UNKNOWN)) if (Arg->getSpelling() != "--") UnknownOptionIndices.insert(Arg->getIndex()); - // COFF linker options such as '/nologo' are parsed as inputs. Unlike a path, - // they have no further path separator. + // COFF linker options such as '/nologo' or '/LIBPATH:C:\dir' are parsed as + // inputs. Unlike a path, the option name before any ':' has no further path + // separator. auto IsCOFFLinkerOption = [&](StringRef Input) { - return HostTriple.isOSWindows() && Input.starts_with("/") && - Input.find_first_of("/\\", 1) == StringRef::npos; + if (!HostTriple.isOSWindows() || !Input.consume_front("/")) + return false; + StringRef Name = Input.split(':').first; + return !Name.empty() && Name.find_first_of("/\\") == StringRef::npos; }; for (const opt::Arg *Arg : >From 50c64e493e41fb69a4887916bc3605df28adab20 Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 09:31:51 -0800 Subject: [PATCH 10/21] [Clang][SYCL] Address review: use -libpath: for MSVC, pass clang-cl /link values For MSVC targets clang-linker-wrapper finds named inputs only in -libpath: paths, so render -L and toolchain paths that way, as the MSVC link job does. Also pass clang-cl /link values, and say in the docs that archive device code is extracted for the device targets of the other inputs. --- clang/docs/SYCLSupport.md | 7 ++++--- clang/lib/Driver/ToolChains/Clang.cpp | 15 +++++++++++++-- clang/test/Driver/sycl-link.cpp | 13 +++++++++++++ 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/clang/docs/SYCLSupport.md b/clang/docs/SYCLSupport.md index d613617bd6f206..4363305b242f42 100644 --- a/clang/docs/SYCLSupport.md +++ b/clang/docs/SYCLSupport.md @@ -127,9 +127,10 @@ and `b.o` would be linked and registered a second time. If the inputs contain no device code, the output is an empty object without SYCL runtime registration. -Device code in a static library is only extracted when the host link would -use the archive member. To device link a whole library, pass it with -`-Wl,--whole-archive libfoo.a -Wl,--no-whole-archive`. +Device code in a static library is only extracted for device targets that +the other inputs already have. If only static libraries provide device code, +pass them with `-Wl,--whole-archive libfoo.a -Wl,--no-whole-archive`, or with +`-Wl,/wholearchive:foo.lib` on Windows. The output of `-fsycl-link` is not yet supported in a static library: nothing in it is referenced by the host code, so the host linker does not pull it out diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index 6c1be753f12236..d472407063936f 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -10150,9 +10150,20 @@ void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA, const Driver &D = getToolChain().getDriver(); if (!D.SysRoot.empty()) CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot)); - Args.AddAllArgs(CmdArgs, options::OPT_L); - getToolChain().AddFilePathLibArgs(Args, CmdArgs); + // MSVC style links search for named inputs only in -libpath: paths. + bool IsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment(); + auto AddLibraryPath = [&](StringRef Path) { + if (!Path.empty()) + CmdArgs.push_back( + Args.MakeArgString((IsMSVC ? "-libpath:" : "-L") + Path)); + }; + for (const std::string &Path : Args.getAllArgValues(options::OPT_L)) + AddLibraryPath(Path); + for (const std::string &Path : getToolChain().getFilePaths()) + AddLibraryPath(Path); AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA); + // Inputs passed with clang-cl /link. + Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link); } else { for (const char *LinkArg : LinkCommand->getArguments()) CmdArgs.push_back(LinkArg); diff --git a/clang/test/Driver/sycl-link.cpp b/clang/test/Driver/sycl-link.cpp index 9d58314f9f9073..bb90cce277c9af 100644 --- a/clang/test/Driver/sycl-link.cpp +++ b/clang/test/Driver/sycl-link.cpp @@ -44,6 +44,19 @@ // WINDOWS-BINDINGS: "x86_64-pc-windows-msvc{{.*}}" - "Offload::Linker", inputs: ["{{.*}}a.o"], output: "dev.obj" // WINDOWS-BINDINGS-NOT: {{.}} +/// MSVC style links search for named inputs in -libpath: paths, and clang-cl +/// /link values are passed on. +// RUN: %clang -### --target=x86_64-pc-windows-msvc -fsycl -fsycl-link \ +// RUN: %t.a.o -L/foo -Wl,/wholearchive:bar.lib -o dev.obj 2>&1 \ +// RUN: | FileCheck %s --check-prefix=WINDOWS-LIBPATH +// WINDOWS-LIBPATH: clang-linker-wrapper"{{.*}} "--sycl-device-link" "-o" "dev.obj" +// WINDOWS-LIBPATH-SAME: "-libpath:/foo" "{{[^"]*}}a.o" "/wholearchive:bar.lib"{{$}} +// RUN: %clang_cl -### --target=x86_64-pc-windows-msvc -fsycl -fsycl-link \ +// RUN: %t.a.o /link /wholearchive:bar.lib /libpath:dir 2>&1 \ +// RUN: | FileCheck %s --check-prefix=CL-LINK +// CL-LINK: clang-linker-wrapper"{{.*}} "--sycl-device-link" +// CL-LINK-SAME: "{{[^"]*}}a.o" "/wholearchive:bar.lib" "/libpath:dir"{{$}} + /// Without -fsycl-link, the host link is run as usual. // RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl %t.a.o 2>&1 \ // RUN: | FileCheck %s --check-prefix=NO-SYCL-LINK >From 4750b3618a8bf9ab2e046ea8292c7ae811b5bd03 Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 09:31:52 -0800 Subject: [PATCH 11/21] [clang-linker-wrapper][SYCL] Address review: fix archive extraction comment in test --- .../clang-linker-wrapper/linker-wrapper-sycl-device-link.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c index 51c2f721a03c9e..64767b5144013b 100644 --- a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c +++ b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c @@ -17,8 +17,8 @@ // RUN: | FileCheck %s --check-prefix=LINK --implicit-check-not=/usr/bin/ld // LINK: "{{.*}}clang{{(.exe)?}}" {{.*}}--target=spirv64-unknown-unknown {{.*}}sycl-spirv64-unknown-unknown-generic{{.*}}.o --sycl-link{{$}} -// Archive members are only extracted for the host link, so use -// --whole-archive to device link a static library. +// Archive device code is only extracted for device targets that other inputs +// have. Here no other input has device code, so --whole-archive is needed. // RUN: rm -f %t.sycl.a && llvm-ar rcs %t.sycl.a %t.sycl.o // RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ // RUN: --sycl-device-link --linker-path=/usr/bin/ld --whole-archive %t.sycl.a \ >From a59ddb98a98a701cc873dcd82af2c495f1bca6c6 Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 09:36:10 -0800 Subject: [PATCH 12/21] [clang-linker-wrapper][SYCL] Address review: match COFF options in any case, search LIB link.exe options are case-insensitive, so /LIBPATH:, /WHOLEARCHIVE: and /WHOLEARCHIVE are now recognized in any case. link.exe also searches the LIB environment variable, so do the same for MSVC hosts. Without this, --sycl-device-link reported libraries found this way as missing, or skipped their device code. --- .../linker-wrapper-sycl-device-link.c | 16 +++++ .../ClangLinkerWrapper.cpp | 65 ++++++++++++++++--- 2 files changed, 73 insertions(+), 8 deletions(-) diff --git a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c index 64767b5144013b..0d02c1b2685472 100644 --- a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c +++ b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c @@ -50,6 +50,22 @@ // RUN: llvm-readobj --file-header %t.dev.obj | FileCheck %s --check-prefix=WIN // WIN: Format: COFF-x86-64 +// link.exe options are case-insensitive, and link.exe also searches LIB. +// RUN: %clang -cc1 %s -triple x86_64-pc-windows-msvc -emit-obj -o %t.win.obj \ +// RUN: -fembed-offload-object=%t.sycl.out +// RUN: rm -rf %t.libdir && mkdir %t.libdir +// RUN: llvm-ar rcs %t.libdir/foo.lib %t.win.obj +// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \ +// RUN: --sycl-device-link --linker-path=link.exe /LIBPATH:%t.libdir \ +// RUN: /WHOLEARCHIVE:foo.lib -o dev.obj 2>&1 | FileCheck %s --check-prefix=WINLIB +// RUN: env LIB=%t.libdir clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc \ +// RUN: --dry-run --sycl-device-link --linker-path=link.exe /WHOLEARCHIVE \ +// RUN: foo.lib -o dev.obj 2>&1 | FileCheck %s --check-prefix=WINLIB +// WINLIB: --target=spirv64-unknown-unknown {{.*}}win-spirv64-unknown-unknown-generic{{.*}}.o --sycl-link{{$}} +// RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \ +// RUN: --sycl-device-link --linker-path=link.exe /WHOLEARCHIVE:nope.lib \ +// RUN: -o dev.obj 2>&1 | FileCheck %s --check-prefix=MISSING -DFILE=nope.lib + // With --wrapper-verbose and --save-temps, the wrapping is still done // in-process, because the image must be embedded as finalized. // RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \ diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp index 4ccdf7aaa1f34b..695582522bfb36 100644 --- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp +++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp @@ -44,6 +44,7 @@ #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Parallel.h" #include "llvm/Support/Path.h" +#include "llvm/Support/Process.h" #include "llvm/Support/Program.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" @@ -1413,6 +1414,18 @@ getDeviceInput(const ArgList &Args) { const llvm::Triple HostTriple( Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple())); + // link.exe options are case-insensitive, but the COFF options in the option + // table only match lower case. Returns the value of option \p Name if + // \p Input is that option in any case. + auto GetCOFFOptionValue = [&](StringRef Input, + StringRef Name) -> std::optional<StringRef> { + if (!HostTriple.isOSWindows() || + !(Input.consume_front("/") || Input.consume_front("-")) || + !Input.consume_front_insensitive(Name)) + return std::nullopt; + return Input; + }; + StringRef Root = Args.getLastArgValue(OPT_sysroot_EQ); SmallVector<StringRef> LibraryPaths; for (const opt::Arg *Arg : Args.filtered(OPT_library_path, OPT_libpath)) @@ -1422,12 +1435,37 @@ getDeviceInput(const ArgList &Args) { SmallVector<StringRef> InputPaths; for (const opt::Arg *Arg : Args.filtered(OPT_libpath)) InputPaths.push_back(Arg->getValue()); + for (const opt::Arg *Arg : Args.filtered(OPT_INPUT)) { + if (std::optional<StringRef> Path = + GetCOFFOptionValue(Arg->getValue(), "libpath:")) { + LibraryPaths.push_back(*Path); + InputPaths.push_back(*Path); + } + } + + // link.exe also searches the paths in the LIB environment variable. + std::optional<std::string> LibEnv; + if (HostTriple.isWindowsMSVCEnvironment()) + LibEnv = sys::Process::GetEnv("LIB"); + if (LibEnv) { + SmallVector<StringRef> EnvPaths; + StringRef(*LibEnv).split(EnvPaths, ';', /*MaxSplit=*/-1, + /*KeepEmpty=*/false); + LibraryPaths.append(EnvPaths); + InputPaths.append(EnvPaths); + } BumpPtrAllocator Alloc; StringSaver Saver(Alloc); // Try to extract device code from the linker input files. - bool WholeArchive = Args.hasArg(OPT_wholearchive_flag); + bool WholeArchive = + Args.hasArg(OPT_wholearchive_flag) || + llvm::any_of(Args.filtered(OPT_INPUT), [&](const opt::Arg *Arg) { + std::optional<StringRef> Rest = + GetCOFFOptionValue(Arg->getValue(), "wholearchive"); + return Rest && Rest->empty(); + }); SmallVector<OffloadFile> ObjectFilesToExtract; SmallVector<OffloadFile> ArchiveFilesToExtract; DenseMap<StringRef, StringRef> SourceForImage; @@ -1462,11 +1500,23 @@ getDeviceInput(const ArgList &Args) { continue; } + StringRef Input = Arg->getValue(); + bool IsWholeArchiveFile = Arg->getOption().matches(OPT_wholearchive_file); + if (Arg->getOption().matches(OPT_INPUT)) { + // Upper-case spellings of the COFF options in the option table. + std::optional<StringRef> Rest = GetCOFFOptionValue(Input, "wholearchive"); + if (Rest && Rest->consume_front(":")) { + Input = *Rest; + IsWholeArchiveFile = true; + } else if (Rest || GetCOFFOptionValue(Input, "libpath:")) { + continue; + } + } + std::optional<std::string> Filename = Arg->getOption().matches(OPT_library) - ? searchLibrary(Arg->getValue(), Root, LibraryPaths, - HostTriple.isOSWindows()) - : searchInput(Arg->getValue(), Root, InputPaths); + ? searchLibrary(Input, Root, LibraryPaths, HostTriple.isOSWindows()) + : searchInput(Input, Root, InputPaths); if (!Filename && Arg->getOption().matches(OPT_library)) return createStringError("unable to find library -l%s", Arg->getValue()); @@ -1474,9 +1524,9 @@ getDeviceInput(const ArgList &Args) { if (!Filename || !sys::fs::exists(*Filename)) { if (ReportMissingInputs && !UnknownOptionIndices.contains(Arg->getIndex() - 1) && - !IsCOFFLinkerOption(Arg->getValue())) + !IsCOFFLinkerOption(Input)) return createFileError( - Filename ? *Filename : Arg->getValue(), + Filename ? *Filename : Input, make_error_code(errc::no_such_file_or_directory)); continue; } @@ -1484,8 +1534,7 @@ getDeviceInput(const ArgList &Args) { continue; // Unlike `--whole-archive`, `/wholearchive:` applies to a single library. - bool ExtractWholeArchive = - WholeArchive || Arg->getOption().matches(OPT_wholearchive_file); + bool ExtractWholeArchive = WholeArchive || IsWholeArchiveFile; ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = MemoryBuffer::getFileOrSTDIN(*Filename); >From 245bceff11d425bc3555ce8dedd7044a7973d6ea Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 09:36:53 -0800 Subject: [PATCH 13/21] [Clang][SYCL] Address review: clarify forwarded options, default name, tests Say that -Wl and -Xlinker values are forwarded with -fsycl-link, note the default output name in the docs, and tighten the Windows test. --- clang/docs/SYCLSupport.md | 3 ++- clang/lib/Driver/ToolChains/Clang.cpp | 5 +++-- clang/test/Driver/sycl-link.cpp | 5 ++++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/clang/docs/SYCLSupport.md b/clang/docs/SYCLSupport.md index 4363305b242f42..855cdcee117dfb 100644 --- a/clang/docs/SYCLSupport.md +++ b/clang/docs/SYCLSupport.md @@ -119,7 +119,8 @@ clang++ -fsycl -fsycl-link a.o b.o -o dev.o clang++ main.o a.o b.o dev.o -L<libsycl dir> -lLLVMSYCL -o app ``` -On Windows, the host link uses `LLVMSYCL.lib` instead of `-lLLVMSYCL`. +On Windows, the host link uses `LLVMSYCL.lib` instead of `-lLLVMSYCL`. Without +`-o`, the output is named as for a host link, e.g. `a.out` or `a.exe`. The host link does not use `-fsycl`. With `-fsycl`, the device code in `a.o` and `b.o` would be linked and registered a second time. diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index d472407063936f..499859bff40064 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -10143,8 +10143,9 @@ void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA, Args.hasArg(options::OPT_fsycl_link)) { // With -fsycl-link, the wrapper writes the wrapped SYCL device object to // the output and no host link runs. Pass only what is needed to find the - // device code: the sysroot, library paths and link inputs. Other host link - // options, startup files and default libraries are not used. + // device code: the sysroot, library paths and link inputs, which include + // -Wl and -Xlinker values. Startup files and default libraries are not + // added. CmdArgs.push_back("--sycl-device-link"); CmdArgs.append({"-o", Output.getFilename()}); const Driver &D = getToolChain().getDriver(); diff --git a/clang/test/Driver/sycl-link.cpp b/clang/test/Driver/sycl-link.cpp index bb90cce277c9af..1d5f11ffe5c219 100644 --- a/clang/test/Driver/sycl-link.cpp +++ b/clang/test/Driver/sycl-link.cpp @@ -37,7 +37,7 @@ // RUN: %clang -### --target=x86_64-pc-windows-msvc -fsycl -fsycl-link \ // RUN: %t.a.o -o dev.obj 2>&1 | FileCheck %s --check-prefix=WINDOWS -// WINDOWS: clang-linker-wrapper"{{.*}} "--sycl-device-link" "-o" "dev.obj" "{{.*}}a.o"{{$}} +// WINDOWS: clang-linker-wrapper"{{.*}} "--sycl-device-link" "-o" "dev.obj" "{{[^"]*}}a.o"{{$}} // RUN: %clang -ccc-print-bindings --target=x86_64-pc-windows-msvc -fsycl \ // RUN: -fsycl-link %t.a.o -o dev.obj 2>&1 \ // RUN: | FileCheck %s --check-prefix=WINDOWS-BINDINGS @@ -84,6 +84,9 @@ // ONLY: error: invalid argument '-fsycl-link' not allowed with '[[OPT]]' /// The last of the mode options selects the mode. +// RUN: not %clang -### --target=x86_64-unknown-linux-gnu -fsycl -fsycl-link \ +// RUN: -fsycl-device-only -fsycl-host-only %t.a.o 2>&1 \ +// RUN: | FileCheck %s --check-prefix=ONLY -DOPT=-fsycl-host-only // RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl -fsycl-link \ // RUN: --offload-device-only --offload-host-device %t.a.o 2>&1 \ // RUN: | FileCheck %s --check-prefix=HOST-DEVICE >From ef619c32692134b93189d97b0f74903432fe54d3 Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 09:39:48 -0800 Subject: [PATCH 14/21] [clang-linker-wrapper][SYCL] Address review: search COFF paths in order, drop unused '-' match Collect -L, -libpath: and /LIBPATH: paths in one pass so they are searched in command line order, as link.exe does. '-' spellings in other cases are parsed as options, not inputs, so only '/' spellings are matched. --- .../ClangLinkerWrapper.cpp | 35 +++++++++++-------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp index 695582522bfb36..272cdd69a4e919 100644 --- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp +++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp @@ -1415,32 +1415,37 @@ getDeviceInput(const ArgList &Args) { Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple())); // link.exe options are case-insensitive, but the COFF options in the option - // table only match lower case. Returns the value of option \p Name if - // \p Input is that option in any case. + // table only match lower case. A '/' spelling in another case, e.g. + // '/LIBPATH:', is parsed as an input. Returns the value of option \p Name if + // \p Input is such a spelling of it. auto GetCOFFOptionValue = [&](StringRef Input, StringRef Name) -> std::optional<StringRef> { - if (!HostTriple.isOSWindows() || - !(Input.consume_front("/") || Input.consume_front("-")) || + if (!HostTriple.isOSWindows() || !Input.consume_front("/") || !Input.consume_front_insensitive(Name)) return std::nullopt; return Input; }; + // Libraries are searched in -L and -libpath: paths. Only `link.exe` style + // linkers also search -libpath: paths for other inputs. Paths are searched + // in command line order. StringRef Root = Args.getLastArgValue(OPT_sysroot_EQ); SmallVector<StringRef> LibraryPaths; - for (const opt::Arg *Arg : Args.filtered(OPT_library_path, OPT_libpath)) - LibraryPaths.push_back(Arg->getValue()); - - // Only `link.exe` style linkers search for their input files. SmallVector<StringRef> InputPaths; - for (const opt::Arg *Arg : Args.filtered(OPT_libpath)) - InputPaths.push_back(Arg->getValue()); - for (const opt::Arg *Arg : Args.filtered(OPT_INPUT)) { - if (std::optional<StringRef> Path = - GetCOFFOptionValue(Arg->getValue(), "libpath:")) { - LibraryPaths.push_back(*Path); - InputPaths.push_back(*Path); + for (const opt::Arg *Arg : + Args.filtered(OPT_library_path, OPT_libpath, OPT_INPUT)) { + if (Arg->getOption().matches(OPT_library_path)) { + LibraryPaths.push_back(Arg->getValue()); + continue; } + std::optional<StringRef> Path = + Arg->getOption().matches(OPT_libpath) + ? std::optional<StringRef>(Arg->getValue()) + : GetCOFFOptionValue(Arg->getValue(), "libpath:"); + if (!Path) + continue; + LibraryPaths.push_back(*Path); + InputPaths.push_back(*Path); } // link.exe also searches the paths in the LIB environment variable. >From 7e21190b33aeb5b5b2cbc5f61251223c0a5a4ffa Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 12:24:44 -0800 Subject: [PATCH 15/21] [clang-linker-wrapper][SYCL] Address review: keep inputs that start like /WHOLEARCHIVE Only a bare /WHOLEARCHIVE is the flag. A path such as /wholearchive-dir/a.obj, possible when targeting Windows from a POSIX host, is an input and was skipped. --- .../clang-linker-wrapper/linker-wrapper-sycl-device-link.c | 5 +++++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp | 5 ++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c index 0d02c1b2685472..5315036756fa50 100644 --- a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c +++ b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c @@ -65,6 +65,11 @@ // RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \ // RUN: --sycl-device-link --linker-path=link.exe /WHOLEARCHIVE:nope.lib \ // RUN: -o dev.obj 2>&1 | FileCheck %s --check-prefix=MISSING -DFILE=nope.lib +// A path that starts like a COFF option is still an input. +// RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \ +// RUN: --sycl-device-link --linker-path=link.exe /wholearchive-dir/missing.obj \ +// RUN: -o dev.obj 2>&1 \ +// RUN: | FileCheck %s --check-prefix=MISSING -DFILE=/wholearchive-dir/missing.obj // With --wrapper-verbose and --save-temps, the wrapping is still done // in-process, because the image must be embedded as finalized. diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp index 272cdd69a4e919..fe670e5765590d 100644 --- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp +++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp @@ -1513,7 +1513,10 @@ getDeviceInput(const ArgList &Args) { if (Rest && Rest->consume_front(":")) { Input = *Rest; IsWholeArchiveFile = true; - } else if (Rest || GetCOFFOptionValue(Input, "libpath:")) { + } else if ((Rest && Rest->empty()) || + GetCOFFOptionValue(Input, "libpath:")) { + // '/WHOLEARCHIVE' or '/LIBPATH:', both handled above. Anything else, + // e.g. '/wholearchive-dir/a.obj', is an input path. continue; } } >From 357326be7cc7f67a871c44a9e92afa68aadb3a49 Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 12:25:54 -0800 Subject: [PATCH 16/21] [clang-linker-wrapper][SYCL] Note the limit of the COFF option check --- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp index fe670e5765590d..fe6d2987c82187 100644 --- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp +++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp @@ -1488,7 +1488,8 @@ getDeviceInput(const ArgList &Args) { UnknownOptionIndices.insert(Arg->getIndex()); // COFF linker options such as '/nologo' or '/LIBPATH:C:\dir' are parsed as // inputs. Unlike a path, the option name before any ':' has no further path - // separator. + // separator. A missing root-level path such as '/a.obj' looks the same, so it + // is not reported. auto IsCOFFLinkerOption = [&](StringRef Input) { if (!HostTriple.isOSWindows() || !Input.consume_front("/")) return false; >From bfafd2f945913df038e9b121ac3dc3390b53071b Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 12:40:25 -0800 Subject: [PATCH 17/21] [clang-linker-wrapper] Address review: accept /OUT: in any case link.exe options are case-insensitive, but only a lower-case /out: set the output name. With /OUT: and no -o, the output was written to a.exe. --- .../linker-wrapper-sycl-device-link.c | 5 +++++ .../clang-linker-wrapper/ClangLinkerWrapper.cpp | 15 +++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c index 5315036756fa50..ab2dea71d5f882 100644 --- a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c +++ b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c @@ -48,6 +48,11 @@ // RUN: --sycl-device-link --linker-path=link.exe %t.sycl.o /nologo \ // RUN: /IGNORE:4078 '/LIBPATH:C:\dir' /OUT:C:/dir/a.exe -o %t.dev.obj // RUN: llvm-readobj --file-header %t.dev.obj | FileCheck %s --check-prefix=WIN +// link.exe options are case-insensitive, so /OUT: names the output too. +// RUN: rm -f %t.out.obj +// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc \ +// RUN: --sycl-device-link --linker-path=link.exe %t.sycl.o /OUT:%t.out.obj +// RUN: llvm-readobj --file-header %t.out.obj | FileCheck %s --check-prefix=WIN // WIN: Format: COFF-x86-64 // link.exe options are case-insensitive, and link.exe also searches LIB. diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp index fe6d2987c82187..b60b7d0b43c7fb 100644 --- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp +++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp @@ -1698,10 +1698,21 @@ int main(int Argc, char **Argv) { llvm::Triple Triple( Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple())); + // link.exe options are case-insensitive, but the option table only matches + // '/out:' in lower case. Another spelling, e.g. '/OUT:', is parsed as an + // input. + StringRef COFFOutput; + for (const opt::Arg *Arg : Args.filtered(OPT_out, OPT_INPUT)) { + StringRef Value = Arg->getValue(); + if (Arg->getOption().matches(OPT_out) || + (Triple.isOSWindows() && Value.consume_front("/") && + Value.consume_front_insensitive("out:"))) + COFFOutput = Value; + } if (Args.hasArg(OPT_o)) ExecutableName = Args.getLastArgValue(OPT_o, "a.out"); - else if (Args.hasArg(OPT_out)) - ExecutableName = Args.getLastArgValue(OPT_out, "a.exe"); + else if (!COFFOutput.empty()) + ExecutableName = COFFOutput; else ExecutableName = Triple.isOSWindows() ? "a.exe" : "a.out"; >From e049de23df305f13bded195b408f6786f4e47155 Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 12:43:49 -0800 Subject: [PATCH 18/21] [clang-linker-wrapper] Address review: pass the wrapped image after /OUT: in any case The wrapped device image is added to the host link after the output option, but only a lower-case /out: was recognized. With /OUT: the image was not linked. Share the case-insensitive COFF option match between main, runLinker and getDeviceInput. --- .../linker-wrapper-sycl-device-link.c | 5 ++ .../ClangLinkerWrapper.cpp | 49 ++++++++++++------- 2 files changed, 35 insertions(+), 19 deletions(-) diff --git a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c index ab2dea71d5f882..ecc899a18922d0 100644 --- a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c +++ b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c @@ -66,6 +66,11 @@ // RUN: env LIB=%t.libdir clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc \ // RUN: --dry-run --sycl-device-link --linker-path=link.exe /WHOLEARCHIVE \ // RUN: foo.lib -o dev.obj 2>&1 | FileCheck %s --check-prefix=WINLIB +// In a host link, the wrapped image follows /OUT: in any case. +// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \ +// RUN: --linker-path=link.exe %t.win.obj /OUT:app.exe 2>&1 \ +// RUN: | FileCheck %s --check-prefix=WIN-LINK +// WIN-LINK: "link.exe" {{.*}}win.obj /OUT:app.exe {{.*}}app.exe.sycl.image.wrapper{{[^ ]*}}.o{{$}} // WINLIB: --target=spirv64-unknown-unknown {{.*}}win-spirv64-unknown-unknown-generic{{.*}}.o --sycl-link{{$}} // RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \ // RUN: --sycl-device-link --linker-path=link.exe /WHOLEARCHIVE:nope.lib \ diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp index b60b7d0b43c7fb..951e15b13d8d3a 100644 --- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp +++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp @@ -358,6 +358,25 @@ Error relocateOffloadSection(const ArgList &Args, StringRef Output) { return Error::success(); } +/// link.exe options are case-insensitive, but the COFF options in the option +/// table only match lower case, so a '/' spelling in another case, e.g. +/// '/OUT:', is parsed as an input. Returns the value of option \p Name if +/// \p Input is such a spelling of it and the host is Windows. +std::optional<StringRef> getCOFFOptionValue(StringRef Input, StringRef Name, + const Triple &HostTriple) { + if (!HostTriple.isOSWindows() || !Input.consume_front("/") || + !Input.consume_front_insensitive(Name)) + return std::nullopt; + return Input; +} + +/// Returns true if \p Arg names the output file. +bool isOutputArg(const opt::Arg *Arg, const Triple &HostTriple) { + return Arg->getOption().matches(OPT_o) || Arg->getOption().matches(OPT_out) || + (Arg->getOption().matches(OPT_INPUT) && + getCOFFOptionValue(Arg->getValue(), "out:", HostTriple)); +} + /// Runs the wrapped linker job with the newly created input. Error runLinker(ArrayRef<StringRef> Files, const ArgList &Args) { llvm::TimeTraceScope TimeScope("Execute host linker"); @@ -367,6 +386,8 @@ Error runLinker(ArrayRef<StringRef> Files, const ArgList &Args) { StringRef LinkerPath = Args.getLastArgValue(OPT_linker_path_EQ); if (LinkerPath.empty()) return createStringError("linker path missing, must pass 'linker-path'"); + const Triple HostTriple( + Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple())); ArgStringList NewLinkerArgs; for (const opt::Arg *Arg : Args) { // Do not forward arguments only intended for the linker wrapper. @@ -374,7 +395,7 @@ Error runLinker(ArrayRef<StringRef> Files, const ArgList &Args) { continue; Arg->render(Args, NewLinkerArgs); - if (Arg->getOption().matches(OPT_o) || Arg->getOption().matches(OPT_out)) + if (isOutputArg(Arg, HostTriple)) llvm::transform(Files, std::back_inserter(NewLinkerArgs), [&](StringRef A) { return Args.MakeArgString(A); }); } @@ -1414,16 +1435,8 @@ getDeviceInput(const ArgList &Args) { const llvm::Triple HostTriple( Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple())); - // link.exe options are case-insensitive, but the COFF options in the option - // table only match lower case. A '/' spelling in another case, e.g. - // '/LIBPATH:', is parsed as an input. Returns the value of option \p Name if - // \p Input is such a spelling of it. - auto GetCOFFOptionValue = [&](StringRef Input, - StringRef Name) -> std::optional<StringRef> { - if (!HostTriple.isOSWindows() || !Input.consume_front("/") || - !Input.consume_front_insensitive(Name)) - return std::nullopt; - return Input; + auto GetCOFFOptionValue = [&](StringRef Input, StringRef Name) { + return getCOFFOptionValue(Input, Name, HostTriple); }; // Libraries are searched in -L and -libpath: paths. Only `link.exe` style @@ -1698,16 +1711,14 @@ int main(int Argc, char **Argv) { llvm::Triple Triple( Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple())); - // link.exe options are case-insensitive, but the option table only matches - // '/out:' in lower case. Another spelling, e.g. '/OUT:', is parsed as an - // input. + // The last '/out:' in any case names the output if there is no -o. StringRef COFFOutput; for (const opt::Arg *Arg : Args.filtered(OPT_out, OPT_INPUT)) { - StringRef Value = Arg->getValue(); - if (Arg->getOption().matches(OPT_out) || - (Triple.isOSWindows() && Value.consume_front("/") && - Value.consume_front_insensitive("out:"))) - COFFOutput = Value; + if (Arg->getOption().matches(OPT_out)) + COFFOutput = Arg->getValue(); + else if (std::optional<StringRef> Value = + getCOFFOptionValue(Arg->getValue(), "out:", Triple)) + COFFOutput = *Value; } if (Args.hasArg(OPT_o)) ExecutableName = Args.getLastArgValue(OPT_o, "a.out"); >From f5178eab09554d253423182577d40a8c72568f21 Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 12:46:07 -0800 Subject: [PATCH 19/21] [clang-linker-wrapper] Address review: add the wrapped image to the host link once The image was added after every output option, so -o x.exe /OUT:x.exe or -o with /out: passed the same object twice. --- .../clang-linker-wrapper/linker-wrapper-sycl-device-link.c | 5 +++++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp | 6 +++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c index ecc899a18922d0..02b92de7dbe355 100644 --- a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c +++ b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c @@ -71,6 +71,11 @@ // RUN: --linker-path=link.exe %t.win.obj /OUT:app.exe 2>&1 \ // RUN: | FileCheck %s --check-prefix=WIN-LINK // WIN-LINK: "link.exe" {{.*}}win.obj /OUT:app.exe {{.*}}app.exe.sycl.image.wrapper{{[^ ]*}}.o{{$}} +// The image is added once, even if the output is named more than once. +// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \ +// RUN: --linker-path=link.exe %t.win.obj -o app.exe /OUT:app.exe 2>&1 \ +// RUN: | FileCheck %s --check-prefix=WIN-ONCE +// WIN-ONCE: "link.exe" {{.*}}win.obj -o app.exe {{[^ ]*}}app.exe.sycl.image.wrapper{{[^ ]*}}.o /OUT:app.exe{{$}} // WINLIB: --target=spirv64-unknown-unknown {{.*}}win-spirv64-unknown-unknown-generic{{.*}}.o --sycl-link{{$}} // RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \ // RUN: --sycl-device-link --linker-path=link.exe /WHOLEARCHIVE:nope.lib \ diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp index 951e15b13d8d3a..20a50ff9c6b7f1 100644 --- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp +++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp @@ -389,15 +389,19 @@ Error runLinker(ArrayRef<StringRef> Files, const ArgList &Args) { const Triple HostTriple( Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple())); ArgStringList NewLinkerArgs; + bool AddedFiles = false; for (const opt::Arg *Arg : Args) { // Do not forward arguments only intended for the linker wrapper. if (Arg->getOption().hasFlag(WrapperOnlyOption)) continue; Arg->render(Args, NewLinkerArgs); - if (isOutputArg(Arg, HostTriple)) + // Add the image once, even if the output is named more than once. + if (!AddedFiles && isOutputArg(Arg, HostTriple)) { llvm::transform(Files, std::back_inserter(NewLinkerArgs), [&](StringRef A) { return Args.MakeArgString(A); }); + AddedFiles = true; + } } SmallVector<StringRef> LinkerArgs({LinkerPath}); >From a7b08d88080cfc8e8229b70c47ad08203307f5ff Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 12:53:21 -0800 Subject: [PATCH 20/21] [clang-linker-wrapper] Address review: use the last output option on Windows hosts link.exe uses the last of its output options, so clang-cl '/link /out:x' names the output in a host link. The wrapper preferred -o over /out:, so with --sycl-device-link the output was written to the -o name instead. On Windows hosts the last of -o and /out: in any case now wins. --- .../linker-wrapper-sycl-device-link.c | 7 +++++ .../ClangLinkerWrapper.cpp | 28 +++++++++++-------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c index 02b92de7dbe355..a9a1e7c2380577 100644 --- a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c +++ b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper-sycl-device-link.c @@ -53,6 +53,13 @@ // RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc \ // RUN: --sycl-device-link --linker-path=link.exe %t.sycl.o /OUT:%t.out.obj // RUN: llvm-readobj --file-header %t.out.obj | FileCheck %s --check-prefix=WIN +// As with link.exe, the last of -o and /out: names the output, e.g. for +// clang-cl '/link /out:'. +// RUN: rm -f %t.last.obj +// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc \ +// RUN: --sycl-device-link --linker-path=link.exe -o %t.first.exe %t.sycl.o \ +// RUN: /Out:%t.last.obj +// RUN: llvm-readobj --file-header %t.last.obj | FileCheck %s --check-prefix=WIN // WIN: Format: COFF-x86-64 // link.exe options are case-insensitive, and link.exe also searches LIB. diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp index 20a50ff9c6b7f1..c8cf1f34840f73 100644 --- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp +++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp @@ -1715,19 +1715,23 @@ int main(int Argc, char **Argv) { llvm::Triple Triple( Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple())); - // The last '/out:' in any case names the output if there is no -o. - StringRef COFFOutput; - for (const opt::Arg *Arg : Args.filtered(OPT_out, OPT_INPUT)) { - if (Arg->getOption().matches(OPT_out)) - COFFOutput = Arg->getValue(); - else if (std::optional<StringRef> Value = - getCOFFOptionValue(Arg->getValue(), "out:", Triple)) - COFFOutput = *Value; + StringRef Output; + if (Triple.isOSWindows()) { + // As with link.exe, the last of -o and '/out:' in any case names the + // output, e.g. for clang-cl '/link /out:'. + for (const opt::Arg *Arg : Args.filtered(OPT_o, OPT_out, OPT_INPUT)) { + if (!Arg->getOption().matches(OPT_INPUT)) + Output = Arg->getValue(); + else if (std::optional<StringRef> Value = + getCOFFOptionValue(Arg->getValue(), "out:", Triple)) + Output = *Value; + } + } else { + Output = Args.hasArg(OPT_o) ? Args.getLastArgValue(OPT_o) + : Args.getLastArgValue(OPT_out); } - if (Args.hasArg(OPT_o)) - ExecutableName = Args.getLastArgValue(OPT_o, "a.out"); - else if (!COFFOutput.empty()) - ExecutableName = COFFOutput; + if (!Output.empty()) + ExecutableName = Output; else ExecutableName = Triple.isOSWindows() ? "a.exe" : "a.out"; >From 2fe4658b1c65b917956f87c023a45d889d582f88 Mon Sep 17 00:00:00 2001 From: srividya sundaram <[email protected]> Date: Tue, 10 Nov 2026 12:54:09 -0800 Subject: [PATCH 21/21] [Clang][SYCL] Address review: complete the doc example, test /link /out: The example linked main.o without creating it. Also test that a clang-cl /link /out: comes after -o, so it names the output as in a host link. --- clang/docs/SYCLSupport.md | 4 ++++ clang/test/Driver/sycl-link.cpp | 9 +++++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/clang/docs/SYCLSupport.md b/clang/docs/SYCLSupport.md index 855cdcee117dfb..ba9a9a7ee8a1f0 100644 --- a/clang/docs/SYCLSupport.md +++ b/clang/docs/SYCLSupport.md @@ -116,9 +116,13 @@ then used in a later host link, which can be done by any host linker. ```console clang++ -fsycl -c a.cpp b.cpp clang++ -fsycl -fsycl-link a.o b.o -o dev.o +clang++ -c main.cpp clang++ main.o a.o b.o dev.o -L<libsycl dir> -lLLVMSYCL -o app ``` +Here `main.cpp` has no SYCL device code. Device code that is not in the +inputs of `-fsycl-link` is not in `dev.o`. + On Windows, the host link uses `LLVMSYCL.lib` instead of `-lLLVMSYCL`. Without `-o`, the output is named as for a host link, e.g. `a.out` or `a.exe`. diff --git a/clang/test/Driver/sycl-link.cpp b/clang/test/Driver/sycl-link.cpp index 1d5f11ffe5c219..c7f4fbdc28a768 100644 --- a/clang/test/Driver/sycl-link.cpp +++ b/clang/test/Driver/sycl-link.cpp @@ -45,17 +45,18 @@ // WINDOWS-BINDINGS-NOT: {{.}} /// MSVC style links search for named inputs in -libpath: paths, and clang-cl -/// /link values are passed on. +/// /link values are passed on after -o, so a /link /out: names the output as in +/// a host link. // RUN: %clang -### --target=x86_64-pc-windows-msvc -fsycl -fsycl-link \ // RUN: %t.a.o -L/foo -Wl,/wholearchive:bar.lib -o dev.obj 2>&1 \ // RUN: | FileCheck %s --check-prefix=WINDOWS-LIBPATH // WINDOWS-LIBPATH: clang-linker-wrapper"{{.*}} "--sycl-device-link" "-o" "dev.obj" // WINDOWS-LIBPATH-SAME: "-libpath:/foo" "{{[^"]*}}a.o" "/wholearchive:bar.lib"{{$}} // RUN: %clang_cl -### --target=x86_64-pc-windows-msvc -fsycl -fsycl-link \ -// RUN: %t.a.o /link /wholearchive:bar.lib /libpath:dir 2>&1 \ +// RUN: %t.a.o /link /wholearchive:bar.lib /libpath:dir /out:dev.obj 2>&1 \ // RUN: | FileCheck %s --check-prefix=CL-LINK -// CL-LINK: clang-linker-wrapper"{{.*}} "--sycl-device-link" -// CL-LINK-SAME: "{{[^"]*}}a.o" "/wholearchive:bar.lib" "/libpath:dir"{{$}} +// CL-LINK: clang-linker-wrapper"{{.*}} "--sycl-device-link" "-o" +// CL-LINK-SAME: "{{[^"]*}}a.o" "/wholearchive:bar.lib" "/libpath:dir" "/out:dev.obj"{{$}} /// Without -fsycl-link, the host link is run as usual. // RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl %t.a.o 2>&1 \ _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
