[clang] [LinkerWrapper] Do not parse GNU -l/-L options for MSVC-style linkers (PR #243300)

Vicky Nguyen via cfe-commits cfe-commits at lists.llvm.org
Tue Dec 1 13:51:34 PST 2026


https://github.com/dotrucvi updated https://github.com/llvm/llvm-project/pull/243300

>From ebede944aa94ee3682c29478555ffee3f2bcf1b6 Mon Sep 17 00:00:00 2001
From: Vicky Nguyen <vicky.nguyen at intel.com>
Date: Mon, 16 Nov 2026 11:24:44 -0800
Subject: [PATCH 1/9] [LinkerWrapper] Skip GNU -l/-L for Windows MSVC links

link.exe does not accept -l or -L. Parsing them turned -link into the
library name "ink" and split -LTCG into "-L" and "TCG". The Clang driver
already rewrites GNU -l and -L for MSVC, so the wrapper skips those
options and forwards the original text.
---
 .../clang-linker-wrapper/msvc-link-options.c  | 21 +++++++++++++++++
 .../ClangLinkerWrapper.cpp                    | 19 +++++++++++++++
 .../clang-linker-wrapper/LinkerWrapperOpts.td | 23 ++++++++++++-------
 3 files changed, 55 insertions(+), 8 deletions(-)
 create mode 100644 clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c

diff --git a/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c b/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
new file mode 100644
index 00000000000000..e615ce9f8d3e4e
--- /dev/null
+++ b/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
@@ -0,0 +1,21 @@
+// A link.exe-style host linker has no GNU '-l' or '-L' options. Dash-prefixed
+// MSVC linker options that start with 'l' or 'L' must be forwarded verbatim
+// to the host linker rather than being misparsed as '-l <lib>' or '-L <dir>'.
+
+// The wrapper only scans the input for offload sections, which '--dry-run'
+// skips, so an empty file stands in for a real object.
+// RUN: touch %t.o
+
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-path=/usr/bin/lld-link %t.o -link -LTCG -LARGEADDRESSAWARE \
+// RUN:   /link -libpath:%t.dir -out:%t.exe 2>&1 | FileCheck %s --check-prefix=MSVC
+
+// MSVC-NOT: error
+// MSVC: "/usr/bin/lld-link" {{.*}}.o -link -LTCG -LARGEADDRESSAWARE /link -libpath:{{.*}} -out:{{.*}}.exe
+
+// GNU-style host linkers still treat '-l' and '-L' as library options.
+// RUN: not clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --dry-run \
+// RUN:   --linker-path=/usr/bin/ld.lld %t.o -L%t.dir -link -o %t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=GNU
+
+// GNU: error: unable to find library -link
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index f305a0a4bdac1a..ef07fef053a018 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -157,6 +157,8 @@ using std::error_code;
 enum WrapperFlags {
   WrapperOnlyOption = (1 << 4), // Options only used by the linker wrapper.
   DeviceOnlyOption = (1 << 5),  // Options only used for device linking.
+  // Options only valid for GNU-style host linkers.
+  GNULinkerOnlyOption = (1 << 6),
 };
 
 enum ID {
@@ -1538,6 +1540,23 @@ int main(int Argc, char **Argv) {
     reportError(createStringError(Err));
   });
 
+  // link.exe does not accept GNU -l or -L. The Clang driver already
+  // rewrites -lfoo as foo.lib and -L<dir> as -libpath:<dir>. Parsing those
+  // options here reads -link as library "ink" and splits -LTCG into "-L"
+  // and "TCG". For a Windows MSVC host, parse again without them and
+  // forward -link and -LTCG unchanged.
+  if (llvm::Triple(Args.getLastArgValue(OPT_host_triple_EQ,
+                                        sys::getDefaultTargetTriple()))
+          .isWindowsMSVCEnvironment()) {
+    SmallVector<const char *, 0> ArgStrings;
+    for (unsigned I = 0, E = Args.getNumInputArgStrings(); I != E; ++I)
+      ArgStrings.push_back(Args.getArgString(I));
+    unsigned MissingArgIndex, MissingArgCount;
+    Args = Tbl.ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
+                         /*FlagsToInclude=*/0,
+                         /*FlagsToExclude=*/GNULinkerOnlyOption);
+  }
+
   if (Args.hasArg(OPT_help) || Args.hasArg(OPT_help_hidden)) {
     Tbl.printHelp(
         outs(),
diff --git a/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td b/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
index fc48eac2637eeb..467cc9ec74e49a 100644
--- a/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
+++ b/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
@@ -2,6 +2,8 @@ include "llvm/Option/OptParser.td"
 
 def WrapperOnlyOption : OptionFlag;
 def DeviceOnlyOption : OptionFlag;
+// Options that only exist for GNU-style host linkers (ld, ld.lld).
+def GNULinkerOnlyOption : OptionFlag;
 
 def help : Flag<["--"], "help">,
   HelpText<"Display available options (--help-hidden for more)">;
@@ -110,19 +112,24 @@ def output_EQ : Joined<["--"], "output=">, Alias<o>, Flags<[HelpHidden]>,
 def output : Separate<["--"], "output">, Alias<o>, Flags<[HelpHidden]>,
   HelpText<"Alias for -o">;
 
+// GNU-style library and library path options. link.exe-style linkers have no
+// such options (the driver renders them as 'foo.lib' and '-libpath:'), so they
+// are not parsed for a Windows MSVC host; see GNULinkerOnlyOption.
 def library_path : JoinedOrSeparate<["-"], "L">, MetaVarName<"<dir>">,
+  Flags<[GNULinkerOnlyOption]>,
   HelpText<"Add <dir> to the library search path">;
-def library_path_S : Separate<["--", "-"], "library-path">, Flags<[HelpHidden]>,
-  Alias<library_path>;
-def library_path_EQ : Joined<["--", "-"], "library-path=">, Flags<[HelpHidden]>,
-  Alias<library_path>;
+def library_path_S : Separate<["--", "-"], "library-path">,
+  Flags<[GNULinkerOnlyOption, HelpHidden]>, Alias<library_path>;
+def library_path_EQ : Joined<["--", "-"], "library-path=">,
+  Flags<[GNULinkerOnlyOption, HelpHidden]>, Alias<library_path>;
 
 def library : JoinedOrSeparate<["-"], "l">, MetaVarName<"<libname>">,
+  Flags<[GNULinkerOnlyOption]>,
   HelpText<"Search for library <libname>">;
-def library_S : Separate<["--", "-"], "library">, Flags<[HelpHidden]>,
-  Alias<library>;
-def library_EQ : Joined<["--", "-"], "library=">, Flags<[HelpHidden]>,
-  Alias<library>;
+def library_S : Separate<["--", "-"], "library">,
+  Flags<[GNULinkerOnlyOption, HelpHidden]>, Alias<library>;
+def library_EQ : Joined<["--", "-"], "library=">,
+  Flags<[GNULinkerOnlyOption, HelpHidden]>, Alias<library>;
 
 def rpath : Separate<["--", "-"], "rpath">;
 def rpath_EQ : Joined<["--", "-"], "rpath=">, Flags<[HelpHidden]>, Alias<rpath>;

>From 81e4171287805783990edf694a165acb5b03afe2 Mon Sep 17 00:00:00 2001
From: Vicky Nguyen <vicky.nguyen at intel.com>
Date: Tue, 17 Nov 2026 12:13:25 -0800
Subject: [PATCH 2/9] [LinkerWrapper] Select GNU -l/-L by option visibility in
 one parse

Read the host triple from the expanded arguments before parsing, and
parse once with a visibility mask that hides GNU -l/-L for a Windows
MSVC host.
---
 .../ClangLinkerWrapper.cpp                    | 42 +++++++++++--------
 .../clang-linker-wrapper/LinkerWrapperOpts.td | 16 +++----
 2 files changed, 32 insertions(+), 26 deletions(-)

diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index ef07fef053a018..17827769e6ba29 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -157,8 +157,11 @@ using std::error_code;
 enum WrapperFlags {
   WrapperOnlyOption = (1 << 4), // Options only used by the linker wrapper.
   DeviceOnlyOption = (1 << 5),  // Options only used for device linking.
-  // Options only valid for GNU-style host linkers.
-  GNULinkerOnlyOption = (1 << 6),
+};
+
+/// Must not overlap with llvm::opt::DriverVisibility.
+enum WrapperVisibility {
+  GNULinkerVis = (1 << 1), // Options only valid for GNU-style host linkers.
 };
 
 enum ID {
@@ -1536,26 +1539,29 @@ int main(int Argc, char **Argv) {
   const OptTable &Tbl = getOptTable();
   BumpPtrAllocator Alloc;
   StringSaver Saver(Alloc);
-  auto Args = Tbl.parseArgs(Argc, Argv, OPT_INVALID, Saver, [&](StringRef Err) {
-    reportError(createStringError(Err));
-  });
+  SmallVector<const char *, 0> ArgStrings;
+  cl::expandResponseFiles(Argc, Argv, /*EnvVar=*/nullptr, Saver, ArgStrings);
 
   // link.exe does not accept GNU -l or -L. The Clang driver already
   // rewrites -lfoo as foo.lib and -L<dir> as -libpath:<dir>. Parsing those
-  // options here reads -link as library "ink" and splits -LTCG into "-L"
-  // and "TCG". For a Windows MSVC host, parse again without them and
-  // forward -link and -LTCG unchanged.
-  if (llvm::Triple(Args.getLastArgValue(OPT_host_triple_EQ,
-                                        sys::getDefaultTargetTriple()))
-          .isWindowsMSVCEnvironment()) {
-    SmallVector<const char *, 0> ArgStrings;
-    for (unsigned I = 0, E = Args.getNumInputArgStrings(); I != E; ++I)
-      ArgStrings.push_back(Args.getArgString(I));
-    unsigned MissingArgIndex, MissingArgCount;
-    Args = Tbl.ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
-                         /*FlagsToInclude=*/0,
-                         /*FlagsToExclude=*/GNULinkerOnlyOption);
+  // options here would read -link as library "ink" and split -LTCG into "-L"
+  // and "TCG". The host triple selects the visible options, so it is read
+  // before parsing.
+  std::string HostTriple = sys::getDefaultTargetTriple();
+  for (StringRef Arg : ArgStrings) {
+    if (Arg.consume_front("--host-triple="))
+      HostTriple = Arg.str();
   }
+  unsigned VisibilityMask = DefaultVis;
+  if (!llvm::Triple(HostTriple).isWindowsMSVCEnvironment())
+    VisibilityMask |= GNULinkerVis;
+
+  unsigned MissingArgIndex, MissingArgCount;
+  auto Args = Tbl.ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
+                            Visibility(VisibilityMask));
+  if (MissingArgCount)
+    reportError(createStringError(Twine(Args.getArgString(MissingArgIndex)) +
+                                  ": missing argument"));
 
   if (Args.hasArg(OPT_help) || Args.hasArg(OPT_help_hidden)) {
     Tbl.printHelp(
diff --git a/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td b/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
index 467cc9ec74e49a..e3067decb97902 100644
--- a/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
+++ b/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
@@ -3,7 +3,7 @@ include "llvm/Option/OptParser.td"
 def WrapperOnlyOption : OptionFlag;
 def DeviceOnlyOption : OptionFlag;
 // Options that only exist for GNU-style host linkers (ld, ld.lld).
-def GNULinkerOnlyOption : OptionFlag;
+def GNULinkerVis : OptionVisibility;
 
 def help : Flag<["--"], "help">,
   HelpText<"Display available options (--help-hidden for more)">;
@@ -114,22 +114,22 @@ def output : Separate<["--"], "output">, Alias<o>, Flags<[HelpHidden]>,
 
 // GNU-style library and library path options. link.exe-style linkers have no
 // such options (the driver renders them as 'foo.lib' and '-libpath:'), so they
-// are not parsed for a Windows MSVC host; see GNULinkerOnlyOption.
+// are not visible for a Windows MSVC host; see GNULinkerVis.
 def library_path : JoinedOrSeparate<["-"], "L">, MetaVarName<"<dir>">,
-  Flags<[GNULinkerOnlyOption]>,
+  Visibility<[GNULinkerVis]>,
   HelpText<"Add <dir> to the library search path">;
 def library_path_S : Separate<["--", "-"], "library-path">,
-  Flags<[GNULinkerOnlyOption, HelpHidden]>, Alias<library_path>;
+  Flags<[HelpHidden]>, Visibility<[GNULinkerVis]>, Alias<library_path>;
 def library_path_EQ : Joined<["--", "-"], "library-path=">,
-  Flags<[GNULinkerOnlyOption, HelpHidden]>, Alias<library_path>;
+  Flags<[HelpHidden]>, Visibility<[GNULinkerVis]>, Alias<library_path>;
 
 def library : JoinedOrSeparate<["-"], "l">, MetaVarName<"<libname>">,
-  Flags<[GNULinkerOnlyOption]>,
+  Visibility<[GNULinkerVis]>,
   HelpText<"Search for library <libname>">;
 def library_S : Separate<["--", "-"], "library">,
-  Flags<[GNULinkerOnlyOption, HelpHidden]>, Alias<library>;
+  Flags<[HelpHidden]>, Visibility<[GNULinkerVis]>, Alias<library>;
 def library_EQ : Joined<["--", "-"], "library=">,
-  Flags<[GNULinkerOnlyOption, HelpHidden]>, Alias<library>;
+  Flags<[HelpHidden]>, Visibility<[GNULinkerVis]>, Alias<library>;
 
 def rpath : Separate<["--", "-"], "rpath">;
 def rpath_EQ : Joined<["--", "-"], "rpath=">, Flags<[HelpHidden]>, Alias<rpath>;

>From 48dc2897827c7d54f2188d29b17c869e8dd94a48 Mon Sep 17 00:00:00 2001
From: Vicky Nguyen <vicky.nguyen at intel.com>
Date: Wed, 18 Nov 2026 15:01:29 -0800
Subject: [PATCH 3/9] [LinkerWrapper] Apply MSVC -l/-L handling to the
 per-device parse

---
 .../clang-linker-wrapper/msvc-link-options.c  | 17 +++++-
 .../ClangLinkerWrapper.cpp                    | 59 ++++++++++---------
 2 files changed, 46 insertions(+), 30 deletions(-)

diff --git a/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c b/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
index e615ce9f8d3e4e..7453e1de058f63 100644
--- a/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
+++ b/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
@@ -2,8 +2,7 @@
 // MSVC linker options that start with 'l' or 'L' must be forwarded verbatim
 // to the host linker rather than being misparsed as '-l <lib>' or '-L <dir>'.
 
-// The wrapper only scans the input for offload sections, which '--dry-run'
-// skips, so an empty file stands in for a real object.
+// An empty object has no embedded device code, so only the host link is run.
 // RUN: touch %t.o
 
 // RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
@@ -13,6 +12,20 @@
 // MSVC-NOT: error
 // MSVC: "/usr/bin/lld-link" {{.*}}.o -link -LTCG -LARGEADDRESSAWARE /link -libpath:{{.*}} -out:{{.*}}.exe
 
+// The same options must not be misparsed when the wrapper re-parses them to
+// link a CPU offload image, which copies library options into the device link.
+// RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.elf.o
+// RUN: llvm-offload-binary -o %t.out \
+// RUN:   --image=file=%t.elf.o,kind=openmp,triple=x86_64-unknown-linux-gnu
+// RUN: %clang -cc1 %s -triple x86_64-pc-windows-msvc -emit-obj -o %t.host.o \
+// RUN:   -fembed-offload-object=%t.out
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-path=/usr/bin/lld-link %t.host.o -link -LTCG -out:%t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MSVC-CPU
+
+// MSVC-CPU: clang{{.*}} --target=x86_64-unknown-linux-gnu {{.*}} -Wl,-Bsymbolic -shared{{$}}
+// MSVC-CPU: "/usr/bin/lld-link" {{.*}}.o -link -LTCG -out:{{.*}}.exe
+
 // GNU-style host linkers still treat '-l' and '-L' as library options.
 // RUN: not clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --dry-run \
 // RUN:   --linker-path=/usr/bin/ld.lld %t.o -L%t.dir -link -o %t.exe 2>&1 \
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 17827769e6ba29..502eacbc15ef85 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -201,6 +201,35 @@ void printCommands(ArrayRef<StringRef> CmdArgs) {
   exit(EXIT_FAILURE);
 }
 
+/// Parse the wrapper's command line. Expanded response file strings are owned
+/// by \p Saver, which must outlive the returned list.
+InputArgList parseWrapperArgs(int Argc, char **Argv, StringSaver &Saver) {
+  SmallVector<const char *, 0> ArgStrings;
+  cl::expandResponseFiles(Argc, Argv, /*EnvVar=*/nullptr, Saver, ArgStrings);
+
+  // link.exe does not accept GNU -l or -L. The Clang driver already
+  // rewrites -lfoo as foo.lib and -L<dir> as -libpath:<dir>. Parsing those
+  // options here would read -link as library "ink" and split -LTCG into "-L"
+  // and "TCG". The host triple selects the visible options, so it is read
+  // before parsing.
+  std::string HostTriple = sys::getDefaultTargetTriple();
+  for (StringRef Arg : ArgStrings) {
+    if (Arg.consume_front("--host-triple="))
+      HostTriple = Arg.str();
+  }
+  unsigned VisibilityMask = DefaultVis;
+  if (!llvm::Triple(HostTriple).isWindowsMSVCEnvironment())
+    VisibilityMask |= GNULinkerVis;
+
+  unsigned MissingArgIndex, MissingArgCount;
+  InputArgList Args = getOptTable().ParseArgs(
+      ArgStrings, MissingArgIndex, MissingArgCount, Visibility(VisibilityMask));
+  if (MissingArgCount)
+    reportError(createStringError(Twine(Args.getArgString(MissingArgIndex)) +
+                                  ": missing argument"));
+  return Args;
+}
+
 std::string getExecutableDir(const char *Name) {
   if (!CanonicalPrefixes)
     return sys::path::parent_path(LinkerExecutable).str();
@@ -1124,13 +1153,9 @@ linkAndWrapDeviceFiles(ArrayRef<SmallVector<OffloadFile>> LinkerInputFiles,
 
     // Each thread needs its own copy of the base arguments to maintain
     // per-device argument storage of synthetic strings.
-    const OptTable &Tbl = getOptTable();
     BumpPtrAllocator Alloc;
     StringSaver Saver(Alloc);
-    auto BaseArgs =
-        Tbl.parseArgs(Argc, Argv, OPT_INVALID, Saver, [](StringRef Err) {
-          reportError(createStringError(Err));
-        });
+    auto BaseArgs = parseWrapperArgs(Argc, Argv, Saver);
     auto LinkerArgs = getLinkerArgs(Input, BaseArgs);
 
     uint16_t ActiveOffloadKindMask = 0u;
@@ -1539,29 +1564,7 @@ int main(int Argc, char **Argv) {
   const OptTable &Tbl = getOptTable();
   BumpPtrAllocator Alloc;
   StringSaver Saver(Alloc);
-  SmallVector<const char *, 0> ArgStrings;
-  cl::expandResponseFiles(Argc, Argv, /*EnvVar=*/nullptr, Saver, ArgStrings);
-
-  // link.exe does not accept GNU -l or -L. The Clang driver already
-  // rewrites -lfoo as foo.lib and -L<dir> as -libpath:<dir>. Parsing those
-  // options here would read -link as library "ink" and split -LTCG into "-L"
-  // and "TCG". The host triple selects the visible options, so it is read
-  // before parsing.
-  std::string HostTriple = sys::getDefaultTargetTriple();
-  for (StringRef Arg : ArgStrings) {
-    if (Arg.consume_front("--host-triple="))
-      HostTriple = Arg.str();
-  }
-  unsigned VisibilityMask = DefaultVis;
-  if (!llvm::Triple(HostTriple).isWindowsMSVCEnvironment())
-    VisibilityMask |= GNULinkerVis;
-
-  unsigned MissingArgIndex, MissingArgCount;
-  auto Args = Tbl.ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
-                            Visibility(VisibilityMask));
-  if (MissingArgCount)
-    reportError(createStringError(Twine(Args.getArgString(MissingArgIndex)) +
-                                  ": missing argument"));
+  auto Args = parseWrapperArgs(Argc, Argv, Saver);
 
   if (Args.hasArg(OPT_help) || Args.hasArg(OPT_help_hidden)) {
     Tbl.printHelp(

>From 231056d65eef0bf33f344bfa0cbdad514d728fc5 Mon Sep 17 00:00:00 2001
From: Vicky Nguyen <vicky.nguyen at intel.com>
Date: Mon, 23 Nov 2026 08:31:27 -0800
Subject: [PATCH 4/9] [LinkerWrapper] Add isMSVCHost helper and test long
 library options

---
 .../clang-linker-wrapper/msvc-link-options.c  | 21 +++++++++++++++
 .../ClangLinkerWrapper.cpp                    | 26 +++++++++++--------
 2 files changed, 36 insertions(+), 11 deletions(-)

diff --git a/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c b/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
index 7453e1de058f63..f89d2f3a628132 100644
--- a/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
+++ b/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
@@ -32,3 +32,24 @@
 // RUN:   | FileCheck %s --check-prefix=GNU
 
 // GNU: error: unable to find library -link
+
+// The long forms of the GNU library options are also hidden for a Windows MSVC
+// host and forwarded verbatim.
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-path=/usr/bin/lld-link %t.o --library=foo --library bar \
+// RUN:   --library-path=%t.dir --library-path %t.dir -out:%t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MSVC-LONG
+
+// MSVC-LONG-NOT: error
+// MSVC-LONG: "/usr/bin/lld-link" {{.*}}.o --library=foo --library bar --library-path={{.*}} --library-path {{.*}} -out:{{.*}}.exe
+
+// GNU-style host linkers still treat the long forms as library options.
+// RUN: not clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --dry-run \
+// RUN:   --linker-path=/usr/bin/ld.lld %t.o --library-path=%t.dir --library=foo \
+// RUN:   -o %t.exe 2>&1 | FileCheck %s --check-prefix=GNU-LONG-EQ
+// RUN: not clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --dry-run \
+// RUN:   --linker-path=/usr/bin/ld.lld %t.o --library-path %t.dir --library bar \
+// RUN:   -o %t.exe 2>&1 | FileCheck %s --check-prefix=GNU-LONG-S
+
+// GNU-LONG-EQ: error: unable to find library -lfoo
+// GNU-LONG-S: error: unable to find library -lbar
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 502eacbc15ef85..5ef51d680aa23a 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -201,24 +201,28 @@ void printCommands(ArrayRef<StringRef> CmdArgs) {
   exit(EXIT_FAILURE);
 }
 
+/// Return true if the host uses an MSVC-style linker such as link.exe. The
+/// host triple decides which options we parse, so read it before parsing.
+bool isMSVCHost(ArrayRef<const char *> ArgStrings) {
+  StringRef HostTriple;
+  for (StringRef Arg : ArgStrings)
+    if (Arg.consume_front("--host-triple="))
+      HostTriple = Arg;
+  return llvm::Triple(HostTriple.empty() ? sys::getDefaultTargetTriple()
+                                         : HostTriple.str())
+      .isWindowsMSVCEnvironment();
+}
+
 /// Parse the wrapper's command line. Expanded response file strings are owned
 /// by \p Saver, which must outlive the returned list.
 InputArgList parseWrapperArgs(int Argc, char **Argv, StringSaver &Saver) {
   SmallVector<const char *, 0> ArgStrings;
   cl::expandResponseFiles(Argc, Argv, /*EnvVar=*/nullptr, Saver, ArgStrings);
 
-  // link.exe does not accept GNU -l or -L. The Clang driver already
-  // rewrites -lfoo as foo.lib and -L<dir> as -libpath:<dir>. Parsing those
-  // options here would read -link as library "ink" and split -LTCG into "-L"
-  // and "TCG". The host triple selects the visible options, so it is read
-  // before parsing.
-  std::string HostTriple = sys::getDefaultTargetTriple();
-  for (StringRef Arg : ArgStrings) {
-    if (Arg.consume_front("--host-triple="))
-      HostTriple = Arg.str();
-  }
+  // MSVC linkers have no -l or -L. Hide those options so that MSVC options
+  // such as -link and -LTCG are not misread as "-l ink" and "-L TCG".
   unsigned VisibilityMask = DefaultVis;
-  if (!llvm::Triple(HostTriple).isWindowsMSVCEnvironment())
+  if (!isMSVCHost(ArgStrings))
     VisibilityMask |= GNULinkerVis;
 
   unsigned MissingArgIndex, MissingArgCount;

>From bce6abeb22207d39839ebb8f4b8ea47093a5def5 Mon Sep 17 00:00:00 2001
From: Vicky Nguyen <vicky.nguyen at intel.com>
Date: Tue, 24 Nov 2026 13:54:42 -0800
Subject: [PATCH 5/9] [LinkerWrapper] Use MSVC-aware visibility for --help and
 add REQUIRES

---
 .../clang-linker-wrapper/msvc-link-options.c  | 13 +++++++
 .../ClangLinkerWrapper.cpp                    | 34 +++++++++++++------
 2 files changed, 36 insertions(+), 11 deletions(-)

diff --git a/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c b/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
index f89d2f3a628132..2ccf078e18dc3a 100644
--- a/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
+++ b/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
@@ -1,3 +1,5 @@
+// REQUIRES: x86-registered-target
+
 // A link.exe-style host linker has no GNU '-l' or '-L' options. Dash-prefixed
 // MSVC linker options that start with 'l' or 'L' must be forwarded verbatim
 // to the host linker rather than being misparsed as '-l <lib>' or '-L <dir>'.
@@ -53,3 +55,14 @@
 
 // GNU-LONG-EQ: error: unable to find library -lfoo
 // GNU-LONG-S: error: unable to find library -lbar
+
+// '--help' only lists the GNU library options for GNU-style host linkers.
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --help \
+// RUN:   | FileCheck %s --check-prefix=MSVC-HELP
+// RUN: clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --help \
+// RUN:   | FileCheck %s --check-prefix=GNU-HELP
+
+// MSVC-HELP-NOT: -L <dir>
+// MSVC-HELP-NOT: -l <libname>
+// GNU-HELP: -L <dir>
+// GNU-HELP: -l <libname>
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 5ef51d680aa23a..53082c23420c1e 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -213,21 +213,31 @@ bool isMSVCHost(ArrayRef<const char *> ArgStrings) {
       .isWindowsMSVCEnvironment();
 }
 
+/// Return the options visible for this host. MSVC linkers have no -l or -L, so
+/// hide those options to keep MSVC options such as -link and -LTCG from being
+/// misread as "-l ink" and "-L TCG".
+Visibility getWrapperVisibility(ArrayRef<const char *> ArgStrings) {
+  unsigned VisibilityMask = DefaultVis;
+  if (!isMSVCHost(ArgStrings))
+    VisibilityMask |= GNULinkerVis;
+  return Visibility(VisibilityMask);
+}
+
 /// Parse the wrapper's command line. Expanded response file strings are owned
-/// by \p Saver, which must outlive the returned list.
-InputArgList parseWrapperArgs(int Argc, char **Argv, StringSaver &Saver) {
+/// by \p Saver, which must outlive the returned list. If \p VisibilityOut is
+/// set, it receives the visibility mask used for parsing.
+InputArgList parseWrapperArgs(int Argc, char **Argv, StringSaver &Saver,
+                              Visibility *VisibilityOut = nullptr) {
   SmallVector<const char *, 0> ArgStrings;
   cl::expandResponseFiles(Argc, Argv, /*EnvVar=*/nullptr, Saver, ArgStrings);
 
-  // MSVC linkers have no -l or -L. Hide those options so that MSVC options
-  // such as -link and -LTCG are not misread as "-l ink" and "-L TCG".
-  unsigned VisibilityMask = DefaultVis;
-  if (!isMSVCHost(ArgStrings))
-    VisibilityMask |= GNULinkerVis;
+  Visibility VisibilityMask = getWrapperVisibility(ArgStrings);
+  if (VisibilityOut)
+    *VisibilityOut = VisibilityMask;
 
   unsigned MissingArgIndex, MissingArgCount;
-  InputArgList Args = getOptTable().ParseArgs(
-      ArgStrings, MissingArgIndex, MissingArgCount, Visibility(VisibilityMask));
+  InputArgList Args = getOptTable().ParseArgs(ArgStrings, MissingArgIndex,
+                                              MissingArgCount, VisibilityMask);
   if (MissingArgCount)
     reportError(createStringError(Twine(Args.getArgString(MissingArgIndex)) +
                                   ": missing argument"));
@@ -1568,7 +1578,8 @@ int main(int Argc, char **Argv) {
   const OptTable &Tbl = getOptTable();
   BumpPtrAllocator Alloc;
   StringSaver Saver(Alloc);
-  auto Args = parseWrapperArgs(Argc, Argv, Saver);
+  Visibility VisibilityMask;
+  auto Args = parseWrapperArgs(Argc, Argv, Saver, &VisibilityMask);
 
   if (Args.hasArg(OPT_help) || Args.hasArg(OPT_help_hidden)) {
     Tbl.printHelp(
@@ -1578,7 +1589,8 @@ int main(int Argc, char **Argv) {
         "for sections that require additional processing prior to linking.\n"
         "It will then transparently pass all arguments and input to the\n"
         "specified host linker to create the final binary.\n",
-        Args.hasArg(OPT_help_hidden), Args.hasArg(OPT_help_hidden));
+        Args.hasArg(OPT_help_hidden), Args.hasArg(OPT_help_hidden),
+        VisibilityMask);
     return EXIT_SUCCESS;
   }
   if (Args.hasArg(OPT_version)) {

>From 533fbc4d5bc8bcd655c81cd49eae4989c2ba272d Mon Sep 17 00:00:00 2001
From: Vicky Nguyen <vicky.nguyen at intel.com>
Date: Thu, 26 Nov 2026 07:26:28 -0800
Subject: [PATCH 6/9] [LinkerWrapper] Pick -l/-L handling by linker style, not
 host triple

---
 .../clang-linker-wrapper/msvc-link-options.c  | 61 ++++++++++++++++---
 .../ClangLinkerWrapper.cpp                    | 39 +++++++++---
 .../clang-linker-wrapper/LinkerWrapperOpts.td |  8 +--
 3 files changed, 86 insertions(+), 22 deletions(-)

diff --git a/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c b/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
index 2ccf078e18dc3a..542128ce747247 100644
--- a/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
+++ b/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
@@ -1,8 +1,8 @@
 // REQUIRES: x86-registered-target
 
-// A link.exe-style host linker has no GNU '-l' or '-L' options. Dash-prefixed
-// MSVC linker options that start with 'l' or 'L' must be forwarded verbatim
-// to the host linker rather than being misparsed as '-l <lib>' or '-L <dir>'.
+// An MSVC-style linker has no '-l' or '-L' options. Options such as '-link'
+// and '-LTCG' must be passed to the linker as they are, not read as '-l ink'
+// or '-L TCG'.
 
 // An empty object has no embedded device code, so only the host link is run.
 // RUN: touch %t.o
@@ -28,15 +28,14 @@
 // MSVC-CPU: clang{{.*}} --target=x86_64-unknown-linux-gnu {{.*}} -Wl,-Bsymbolic -shared{{$}}
 // MSVC-CPU: "/usr/bin/lld-link" {{.*}}.o -link -LTCG -out:{{.*}}.exe
 
-// GNU-style host linkers still treat '-l' and '-L' as library options.
+// GNU-style linkers treat '-l' and '-L' as library options.
 // RUN: not clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --dry-run \
 // RUN:   --linker-path=/usr/bin/ld.lld %t.o -L%t.dir -link -o %t.exe 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=GNU
 
 // GNU: error: unable to find library -link
 
-// The long forms of the GNU library options are also hidden for a Windows MSVC
-// host and forwarded verbatim.
+// The long forms '--library' and '--library-path' are passed as they are too.
 // RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
 // RUN:   --linker-path=/usr/bin/lld-link %t.o --library=foo --library bar \
 // RUN:   --library-path=%t.dir --library-path %t.dir -out:%t.exe 2>&1 \
@@ -45,7 +44,7 @@
 // MSVC-LONG-NOT: error
 // MSVC-LONG: "/usr/bin/lld-link" {{.*}}.o --library=foo --library bar --library-path={{.*}} --library-path {{.*}} -out:{{.*}}.exe
 
-// GNU-style host linkers still treat the long forms as library options.
+// GNU-style linkers treat the long forms as library options.
 // RUN: not clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --dry-run \
 // RUN:   --linker-path=/usr/bin/ld.lld %t.o --library-path=%t.dir --library=foo \
 // RUN:   -o %t.exe 2>&1 | FileCheck %s --check-prefix=GNU-LONG-EQ
@@ -56,13 +55,59 @@
 // GNU-LONG-EQ: error: unable to find library -lfoo
 // GNU-LONG-S: error: unable to find library -lbar
 
-// '--help' only lists the GNU library options for GNU-style host linkers.
+// '--help' lists '-l' and '-L' only for GNU-style linkers. Without
+// '--linker-path=', an MSVC target means MSVC style.
 // RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --help \
 // RUN:   | FileCheck %s --check-prefix=MSVC-HELP
 // RUN: clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --help \
 // RUN:   | FileCheck %s --check-prefix=GNU-HELP
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc \
+// RUN:   --linker-path=/usr/bin/ld.bfd --help | FileCheck %s --check-prefix=GNU-HELP
 
+// MSVC-HELP: OPTIONS:
 // MSVC-HELP-NOT: -L <dir>
 // MSVC-HELP-NOT: -l <libname>
 // GNU-HELP: -L <dir>
 // GNU-HELP: -l <libname>
+
+// A GNU linker can link an MSVC target (as with '-fuse-ld=bfd'). Then '-l'
+// and '-L' are library options.
+// RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-path=/usr/bin/ld.bfd %t.o -L%t.dir -lfoo -o %t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MSVC-GNU-LD
+// RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-path=ld %t.o -L%t.dir -lfoo -o %t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MSVC-GNU-LD
+
+// MSVC-GNU-LD: error: unable to find library -lfoo
+
+// Device code in a library found with '-L' and '-l' is extracted.
+// RUN: rm -rf %t.lib && mkdir %t.lib
+// RUN: llvm-ar rcs %t.lib/libfoo.a %t.host.o
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-path=/usr/bin/ld.bfd -L%t.lib --whole-archive -lfoo \
+// RUN:   --no-whole-archive -o %t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MSVC-GNU-LIB
+
+// MSVC-GNU-LIB: clang{{.*}} --target=x86_64-unknown-linux-gnu {{.*}}.o -Wl,-Bsymbolic -shared -L {{.*}}.lib -Wl,--whole-archive -l foo -Wl,--no-whole-archive{{$}}
+// MSVC-GNU-LIB: "/usr/bin/ld.bfd" -L {{.*}}.lib --whole-archive -l foo --no-whole-archive -o {{.*}}.exe {{.*}}.wrapper{{.*}}.o
+
+// MSVC linker names keep MSVC style, with any case, with or without '.exe',
+// and with a version such as 'lld-link-19' (as with '-fuse-ld=lld-link-19').
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-path=/usr/bin/lld-link.exe %t.o -link -LTCG -out:%t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MSVC-NAME -DLINKER=/usr/bin/lld-link.exe
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-path=/tools/LINK.EXE %t.o -link -LTCG -out:%t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MSVC-NAME -DLINKER=/tools/LINK.EXE
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-path=/usr/bin/lld-link-19 %t.o -link -LTCG -out:%t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MSVC-NAME -DLINKER=/usr/bin/lld-link-19
+
+// MSVC-NAME-NOT: error
+// MSVC-NAME: "[[LINKER]]" {{.*}}.o -link -LTCG -out:{{.*}}.exe
+
+// Any other linker name means GNU style, so a misread '-link' is a clear error.
+// RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-path=/tools/my-msvc-link %t.o -link -out:%t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=GNU
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 53082c23420c1e..c510050f181478 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -161,7 +161,7 @@ enum WrapperFlags {
 
 /// Must not overlap with llvm::opt::DriverVisibility.
 enum WrapperVisibility {
-  GNULinkerVis = (1 << 1), // Options only valid for GNU-style host linkers.
+  GNULinkerVis = (1 << 1), // Options only valid for GNU-style linkers.
 };
 
 enum ID {
@@ -201,24 +201,43 @@ void printCommands(ArrayRef<StringRef> CmdArgs) {
   exit(EXIT_FAILURE);
 }
 
-/// Return true if the host uses an MSVC-style linker such as link.exe. The
-/// host triple decides which options we parse, so read it before parsing.
-bool isMSVCHost(ArrayRef<const char *> ArgStrings) {
-  StringRef HostTriple;
-  for (StringRef Arg : ArgStrings)
+/// Return true if \p LinkerPath names an MSVC-style linker: 'link',
+/// 'lld-link' or a versioned 'lld-link-19', with or without '.exe'.
+static bool isMSVCLinkerName(StringRef LinkerPath) {
+  StringRef Name = sys::path::filename(LinkerPath);
+  if (Name.ends_with_insensitive(".exe"))
+    Name = Name.drop_back(4);
+  return Name.equals_insensitive("link") ||
+         Name.starts_with_insensitive("lld-link");
+}
+
+/// Return true if the linker takes MSVC-style arguments. Every linker uses one
+/// of two styles:
+/// - MSVC style (link.exe, lld-link) reads '-link' as one option.
+/// - GNU style (ld, ld.bfd, ld.lld, mold, others) reads '-link' as '-l ink'.
+///
+/// The linker name decides the style. If no linker is given (as in '--help'),
+/// a Windows MSVC target means MSVC style.
+bool usesMSVCStyleLinker(ArrayRef<const char *> ArgStrings) {
+  StringRef HostTriple, LinkerPath;
+  for (StringRef Arg : ArgStrings) {
     if (Arg.consume_front("--host-triple="))
       HostTriple = Arg;
+    else if (Arg.consume_front("--linker-path="))
+      LinkerPath = Arg;
+  }
+  if (!LinkerPath.empty())
+    return isMSVCLinkerName(LinkerPath);
   return llvm::Triple(HostTriple.empty() ? sys::getDefaultTargetTriple()
                                          : HostTriple.str())
       .isWindowsMSVCEnvironment();
 }
 
-/// Return the options visible for this host. MSVC linkers have no -l or -L, so
-/// hide those options to keep MSVC options such as -link and -LTCG from being
-/// misread as "-l ink" and "-L TCG".
+/// Return the options to parse. MSVC-style linkers have no -l or -L, so hide
+/// them. Otherwise -link and -LTCG would be read as "-l ink" and "-L TCG".
 Visibility getWrapperVisibility(ArrayRef<const char *> ArgStrings) {
   unsigned VisibilityMask = DefaultVis;
-  if (!isMSVCHost(ArgStrings))
+  if (!usesMSVCStyleLinker(ArgStrings))
     VisibilityMask |= GNULinkerVis;
   return Visibility(VisibilityMask);
 }
diff --git a/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td b/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
index e3067decb97902..4107e3af1fac7c 100644
--- a/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
+++ b/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
@@ -2,7 +2,7 @@ include "llvm/Option/OptParser.td"
 
 def WrapperOnlyOption : OptionFlag;
 def DeviceOnlyOption : OptionFlag;
-// Options that only exist for GNU-style host linkers (ld, ld.lld).
+// Options that only exist for GNU-style linkers (ld, ld.lld).
 def GNULinkerVis : OptionVisibility;
 
 def help : Flag<["--"], "help">,
@@ -112,9 +112,9 @@ def output_EQ : Joined<["--"], "output=">, Alias<o>, Flags<[HelpHidden]>,
 def output : Separate<["--"], "output">, Alias<o>, Flags<[HelpHidden]>,
   HelpText<"Alias for -o">;
 
-// GNU-style library and library path options. link.exe-style linkers have no
-// such options (the driver renders them as 'foo.lib' and '-libpath:'), so they
-// are not visible for a Windows MSVC host; see GNULinkerVis.
+// GNU-style library and library path options. MSVC-style linkers have no such
+// options (the driver renders them as 'foo.lib' and '-libpath:'), so they are
+// not visible for an MSVC-style linker; see GNULinkerVis.
 def library_path : JoinedOrSeparate<["-"], "L">, MetaVarName<"<dir>">,
   Visibility<[GNULinkerVis]>,
   HelpText<"Add <dir> to the library search path">;

>From 40c2c2e569caf05147385bc4065b98e8cd1ae913 Mon Sep 17 00:00:00 2001
From: Vicky Nguyen <vicky.nguyen at intel.com>
Date: Thu, 26 Nov 2026 14:03:00 -0800
Subject: [PATCH 7/9] [LinkerWrapper] Give the unknown linker name test its own
 check prefix

---
 .../OffloadTools/clang-linker-wrapper/msvc-link-options.c     | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c b/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
index 542128ce747247..1b7d679dacd719 100644
--- a/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
+++ b/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
@@ -110,4 +110,6 @@
 // Any other linker name means GNU style, so a misread '-link' is a clear error.
 // RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
 // RUN:   --linker-path=/tools/my-msvc-link %t.o -link -out:%t.exe 2>&1 \
-// RUN:   | FileCheck %s --check-prefix=GNU
+// RUN:   | FileCheck %s --check-prefix=UNKNOWN-LINKER
+
+// UNKNOWN-LINKER: error: unable to find library -link

>From 73734c8632e8b041e62fab31f989b1d6032f2a11 Mon Sep 17 00:00:00 2001
From: Vicky Nguyen <vicky.nguyen at intel.com>
Date: Tue, 1 Dec 2026 12:42:06 -0800
Subject: [PATCH 8/9] Revert the linker-name heuristic for MSVC -l/-L handling

Revert these commits; the following commit replaces the approach. The
wrapper guessed the linker argument style from the linker name and host
triple, which misses custom MSVC-style linkers. The driver knows the style
and now passes it explicitly.

  40c2c2e569 [LinkerWrapper] Give the unknown linker name test its own check prefix
  533fbc4d5b [LinkerWrapper] Pick -l/-L handling by linker style, not host triple
  bce6abeb22 [LinkerWrapper] Use MSVC-aware visibility for --help and add REQUIRES
  231056d65e [LinkerWrapper] Add isMSVCHost helper and test long library options
  48dc289782 [LinkerWrapper] Apply MSVC -l/-L handling to the per-device parse
  81e4171287 [LinkerWrapper] Select GNU -l/-L by option visibility in one parse
  ebede944aa [LinkerWrapper] Skip GNU -l/-L for Windows MSVC links

Co-Authored-By: Claude Opus 5.5 <noreply at anthropic.com>
---
 .../clang-linker-wrapper/msvc-link-options.c  | 115 ------------------
 .../ClangLinkerWrapper.cpp                    |  81 ++----------
 .../clang-linker-wrapper/LinkerWrapperOpts.td |  23 ++--
 3 files changed, 17 insertions(+), 202 deletions(-)
 delete mode 100644 clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c

diff --git a/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c b/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
deleted file mode 100644
index 1b7d679dacd719..00000000000000
--- a/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
+++ /dev/null
@@ -1,115 +0,0 @@
-// REQUIRES: x86-registered-target
-
-// An MSVC-style linker has no '-l' or '-L' options. Options such as '-link'
-// and '-LTCG' must be passed to the linker as they are, not read as '-l ink'
-// or '-L TCG'.
-
-// An empty object has no embedded device code, so only the host link is run.
-// RUN: touch %t.o
-
-// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
-// RUN:   --linker-path=/usr/bin/lld-link %t.o -link -LTCG -LARGEADDRESSAWARE \
-// RUN:   /link -libpath:%t.dir -out:%t.exe 2>&1 | FileCheck %s --check-prefix=MSVC
-
-// MSVC-NOT: error
-// MSVC: "/usr/bin/lld-link" {{.*}}.o -link -LTCG -LARGEADDRESSAWARE /link -libpath:{{.*}} -out:{{.*}}.exe
-
-// The same options must not be misparsed when the wrapper re-parses them to
-// link a CPU offload image, which copies library options into the device link.
-// RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.elf.o
-// RUN: llvm-offload-binary -o %t.out \
-// RUN:   --image=file=%t.elf.o,kind=openmp,triple=x86_64-unknown-linux-gnu
-// RUN: %clang -cc1 %s -triple x86_64-pc-windows-msvc -emit-obj -o %t.host.o \
-// RUN:   -fembed-offload-object=%t.out
-// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
-// RUN:   --linker-path=/usr/bin/lld-link %t.host.o -link -LTCG -out:%t.exe 2>&1 \
-// RUN:   | FileCheck %s --check-prefix=MSVC-CPU
-
-// MSVC-CPU: clang{{.*}} --target=x86_64-unknown-linux-gnu {{.*}} -Wl,-Bsymbolic -shared{{$}}
-// MSVC-CPU: "/usr/bin/lld-link" {{.*}}.o -link -LTCG -out:{{.*}}.exe
-
-// GNU-style linkers treat '-l' and '-L' as library options.
-// RUN: not clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --dry-run \
-// RUN:   --linker-path=/usr/bin/ld.lld %t.o -L%t.dir -link -o %t.exe 2>&1 \
-// RUN:   | FileCheck %s --check-prefix=GNU
-
-// GNU: error: unable to find library -link
-
-// The long forms '--library' and '--library-path' are passed as they are too.
-// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
-// RUN:   --linker-path=/usr/bin/lld-link %t.o --library=foo --library bar \
-// RUN:   --library-path=%t.dir --library-path %t.dir -out:%t.exe 2>&1 \
-// RUN:   | FileCheck %s --check-prefix=MSVC-LONG
-
-// MSVC-LONG-NOT: error
-// MSVC-LONG: "/usr/bin/lld-link" {{.*}}.o --library=foo --library bar --library-path={{.*}} --library-path {{.*}} -out:{{.*}}.exe
-
-// GNU-style linkers treat the long forms as library options.
-// RUN: not clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --dry-run \
-// RUN:   --linker-path=/usr/bin/ld.lld %t.o --library-path=%t.dir --library=foo \
-// RUN:   -o %t.exe 2>&1 | FileCheck %s --check-prefix=GNU-LONG-EQ
-// RUN: not clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --dry-run \
-// RUN:   --linker-path=/usr/bin/ld.lld %t.o --library-path %t.dir --library bar \
-// RUN:   -o %t.exe 2>&1 | FileCheck %s --check-prefix=GNU-LONG-S
-
-// GNU-LONG-EQ: error: unable to find library -lfoo
-// GNU-LONG-S: error: unable to find library -lbar
-
-// '--help' lists '-l' and '-L' only for GNU-style linkers. Without
-// '--linker-path=', an MSVC target means MSVC style.
-// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --help \
-// RUN:   | FileCheck %s --check-prefix=MSVC-HELP
-// RUN: clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --help \
-// RUN:   | FileCheck %s --check-prefix=GNU-HELP
-// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc \
-// RUN:   --linker-path=/usr/bin/ld.bfd --help | FileCheck %s --check-prefix=GNU-HELP
-
-// MSVC-HELP: OPTIONS:
-// MSVC-HELP-NOT: -L <dir>
-// MSVC-HELP-NOT: -l <libname>
-// GNU-HELP: -L <dir>
-// GNU-HELP: -l <libname>
-
-// A GNU linker can link an MSVC target (as with '-fuse-ld=bfd'). Then '-l'
-// and '-L' are library options.
-// RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
-// RUN:   --linker-path=/usr/bin/ld.bfd %t.o -L%t.dir -lfoo -o %t.exe 2>&1 \
-// RUN:   | FileCheck %s --check-prefix=MSVC-GNU-LD
-// RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
-// RUN:   --linker-path=ld %t.o -L%t.dir -lfoo -o %t.exe 2>&1 \
-// RUN:   | FileCheck %s --check-prefix=MSVC-GNU-LD
-
-// MSVC-GNU-LD: error: unable to find library -lfoo
-
-// Device code in a library found with '-L' and '-l' is extracted.
-// RUN: rm -rf %t.lib && mkdir %t.lib
-// RUN: llvm-ar rcs %t.lib/libfoo.a %t.host.o
-// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
-// RUN:   --linker-path=/usr/bin/ld.bfd -L%t.lib --whole-archive -lfoo \
-// RUN:   --no-whole-archive -o %t.exe 2>&1 \
-// RUN:   | FileCheck %s --check-prefix=MSVC-GNU-LIB
-
-// MSVC-GNU-LIB: clang{{.*}} --target=x86_64-unknown-linux-gnu {{.*}}.o -Wl,-Bsymbolic -shared -L {{.*}}.lib -Wl,--whole-archive -l foo -Wl,--no-whole-archive{{$}}
-// MSVC-GNU-LIB: "/usr/bin/ld.bfd" -L {{.*}}.lib --whole-archive -l foo --no-whole-archive -o {{.*}}.exe {{.*}}.wrapper{{.*}}.o
-
-// MSVC linker names keep MSVC style, with any case, with or without '.exe',
-// and with a version such as 'lld-link-19' (as with '-fuse-ld=lld-link-19').
-// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
-// RUN:   --linker-path=/usr/bin/lld-link.exe %t.o -link -LTCG -out:%t.exe 2>&1 \
-// RUN:   | FileCheck %s --check-prefix=MSVC-NAME -DLINKER=/usr/bin/lld-link.exe
-// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
-// RUN:   --linker-path=/tools/LINK.EXE %t.o -link -LTCG -out:%t.exe 2>&1 \
-// RUN:   | FileCheck %s --check-prefix=MSVC-NAME -DLINKER=/tools/LINK.EXE
-// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
-// RUN:   --linker-path=/usr/bin/lld-link-19 %t.o -link -LTCG -out:%t.exe 2>&1 \
-// RUN:   | FileCheck %s --check-prefix=MSVC-NAME -DLINKER=/usr/bin/lld-link-19
-
-// MSVC-NAME-NOT: error
-// MSVC-NAME: "[[LINKER]]" {{.*}}.o -link -LTCG -out:{{.*}}.exe
-
-// Any other linker name means GNU style, so a misread '-link' is a clear error.
-// RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
-// RUN:   --linker-path=/tools/my-msvc-link %t.o -link -out:%t.exe 2>&1 \
-// RUN:   | FileCheck %s --check-prefix=UNKNOWN-LINKER
-
-// UNKNOWN-LINKER: error: unable to find library -link
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index c510050f181478..f305a0a4bdac1a 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -159,11 +159,6 @@ enum WrapperFlags {
   DeviceOnlyOption = (1 << 5),  // Options only used for device linking.
 };
 
-/// Must not overlap with llvm::opt::DriverVisibility.
-enum WrapperVisibility {
-  GNULinkerVis = (1 << 1), // Options only valid for GNU-style linkers.
-};
-
 enum ID {
   OPT_INVALID = 0, // This is not an option ID.
 #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
@@ -201,68 +196,6 @@ void printCommands(ArrayRef<StringRef> CmdArgs) {
   exit(EXIT_FAILURE);
 }
 
-/// Return true if \p LinkerPath names an MSVC-style linker: 'link',
-/// 'lld-link' or a versioned 'lld-link-19', with or without '.exe'.
-static bool isMSVCLinkerName(StringRef LinkerPath) {
-  StringRef Name = sys::path::filename(LinkerPath);
-  if (Name.ends_with_insensitive(".exe"))
-    Name = Name.drop_back(4);
-  return Name.equals_insensitive("link") ||
-         Name.starts_with_insensitive("lld-link");
-}
-
-/// Return true if the linker takes MSVC-style arguments. Every linker uses one
-/// of two styles:
-/// - MSVC style (link.exe, lld-link) reads '-link' as one option.
-/// - GNU style (ld, ld.bfd, ld.lld, mold, others) reads '-link' as '-l ink'.
-///
-/// The linker name decides the style. If no linker is given (as in '--help'),
-/// a Windows MSVC target means MSVC style.
-bool usesMSVCStyleLinker(ArrayRef<const char *> ArgStrings) {
-  StringRef HostTriple, LinkerPath;
-  for (StringRef Arg : ArgStrings) {
-    if (Arg.consume_front("--host-triple="))
-      HostTriple = Arg;
-    else if (Arg.consume_front("--linker-path="))
-      LinkerPath = Arg;
-  }
-  if (!LinkerPath.empty())
-    return isMSVCLinkerName(LinkerPath);
-  return llvm::Triple(HostTriple.empty() ? sys::getDefaultTargetTriple()
-                                         : HostTriple.str())
-      .isWindowsMSVCEnvironment();
-}
-
-/// Return the options to parse. MSVC-style linkers have no -l or -L, so hide
-/// them. Otherwise -link and -LTCG would be read as "-l ink" and "-L TCG".
-Visibility getWrapperVisibility(ArrayRef<const char *> ArgStrings) {
-  unsigned VisibilityMask = DefaultVis;
-  if (!usesMSVCStyleLinker(ArgStrings))
-    VisibilityMask |= GNULinkerVis;
-  return Visibility(VisibilityMask);
-}
-
-/// Parse the wrapper's command line. Expanded response file strings are owned
-/// by \p Saver, which must outlive the returned list. If \p VisibilityOut is
-/// set, it receives the visibility mask used for parsing.
-InputArgList parseWrapperArgs(int Argc, char **Argv, StringSaver &Saver,
-                              Visibility *VisibilityOut = nullptr) {
-  SmallVector<const char *, 0> ArgStrings;
-  cl::expandResponseFiles(Argc, Argv, /*EnvVar=*/nullptr, Saver, ArgStrings);
-
-  Visibility VisibilityMask = getWrapperVisibility(ArgStrings);
-  if (VisibilityOut)
-    *VisibilityOut = VisibilityMask;
-
-  unsigned MissingArgIndex, MissingArgCount;
-  InputArgList Args = getOptTable().ParseArgs(ArgStrings, MissingArgIndex,
-                                              MissingArgCount, VisibilityMask);
-  if (MissingArgCount)
-    reportError(createStringError(Twine(Args.getArgString(MissingArgIndex)) +
-                                  ": missing argument"));
-  return Args;
-}
-
 std::string getExecutableDir(const char *Name) {
   if (!CanonicalPrefixes)
     return sys::path::parent_path(LinkerExecutable).str();
@@ -1186,9 +1119,13 @@ linkAndWrapDeviceFiles(ArrayRef<SmallVector<OffloadFile>> LinkerInputFiles,
 
     // Each thread needs its own copy of the base arguments to maintain
     // per-device argument storage of synthetic strings.
+    const OptTable &Tbl = getOptTable();
     BumpPtrAllocator Alloc;
     StringSaver Saver(Alloc);
-    auto BaseArgs = parseWrapperArgs(Argc, Argv, Saver);
+    auto BaseArgs =
+        Tbl.parseArgs(Argc, Argv, OPT_INVALID, Saver, [](StringRef Err) {
+          reportError(createStringError(Err));
+        });
     auto LinkerArgs = getLinkerArgs(Input, BaseArgs);
 
     uint16_t ActiveOffloadKindMask = 0u;
@@ -1597,8 +1534,9 @@ int main(int Argc, char **Argv) {
   const OptTable &Tbl = getOptTable();
   BumpPtrAllocator Alloc;
   StringSaver Saver(Alloc);
-  Visibility VisibilityMask;
-  auto Args = parseWrapperArgs(Argc, Argv, Saver, &VisibilityMask);
+  auto Args = Tbl.parseArgs(Argc, Argv, OPT_INVALID, Saver, [&](StringRef Err) {
+    reportError(createStringError(Err));
+  });
 
   if (Args.hasArg(OPT_help) || Args.hasArg(OPT_help_hidden)) {
     Tbl.printHelp(
@@ -1608,8 +1546,7 @@ int main(int Argc, char **Argv) {
         "for sections that require additional processing prior to linking.\n"
         "It will then transparently pass all arguments and input to the\n"
         "specified host linker to create the final binary.\n",
-        Args.hasArg(OPT_help_hidden), Args.hasArg(OPT_help_hidden),
-        VisibilityMask);
+        Args.hasArg(OPT_help_hidden), Args.hasArg(OPT_help_hidden));
     return EXIT_SUCCESS;
   }
   if (Args.hasArg(OPT_version)) {
diff --git a/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td b/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
index 4107e3af1fac7c..fc48eac2637eeb 100644
--- a/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
+++ b/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
@@ -2,8 +2,6 @@ include "llvm/Option/OptParser.td"
 
 def WrapperOnlyOption : OptionFlag;
 def DeviceOnlyOption : OptionFlag;
-// Options that only exist for GNU-style linkers (ld, ld.lld).
-def GNULinkerVis : OptionVisibility;
 
 def help : Flag<["--"], "help">,
   HelpText<"Display available options (--help-hidden for more)">;
@@ -112,24 +110,19 @@ def output_EQ : Joined<["--"], "output=">, Alias<o>, Flags<[HelpHidden]>,
 def output : Separate<["--"], "output">, Alias<o>, Flags<[HelpHidden]>,
   HelpText<"Alias for -o">;
 
-// GNU-style library and library path options. MSVC-style linkers have no such
-// options (the driver renders them as 'foo.lib' and '-libpath:'), so they are
-// not visible for an MSVC-style linker; see GNULinkerVis.
 def library_path : JoinedOrSeparate<["-"], "L">, MetaVarName<"<dir>">,
-  Visibility<[GNULinkerVis]>,
   HelpText<"Add <dir> to the library search path">;
-def library_path_S : Separate<["--", "-"], "library-path">,
-  Flags<[HelpHidden]>, Visibility<[GNULinkerVis]>, Alias<library_path>;
-def library_path_EQ : Joined<["--", "-"], "library-path=">,
-  Flags<[HelpHidden]>, Visibility<[GNULinkerVis]>, Alias<library_path>;
+def library_path_S : Separate<["--", "-"], "library-path">, Flags<[HelpHidden]>,
+  Alias<library_path>;
+def library_path_EQ : Joined<["--", "-"], "library-path=">, Flags<[HelpHidden]>,
+  Alias<library_path>;
 
 def library : JoinedOrSeparate<["-"], "l">, MetaVarName<"<libname>">,
-  Visibility<[GNULinkerVis]>,
   HelpText<"Search for library <libname>">;
-def library_S : Separate<["--", "-"], "library">,
-  Flags<[HelpHidden]>, Visibility<[GNULinkerVis]>, Alias<library>;
-def library_EQ : Joined<["--", "-"], "library=">,
-  Flags<[HelpHidden]>, Visibility<[GNULinkerVis]>, Alias<library>;
+def library_S : Separate<["--", "-"], "library">, Flags<[HelpHidden]>,
+  Alias<library>;
+def library_EQ : Joined<["--", "-"], "library=">, Flags<[HelpHidden]>,
+  Alias<library>;
 
 def rpath : Separate<["--", "-"], "rpath">;
 def rpath_EQ : Joined<["--", "-"], "rpath=">, Flags<[HelpHidden]>, Alias<rpath>;

>From 86c833e90b53d1b45893cd336e5698d3aaa8ac2b Mon Sep 17 00:00:00 2001
From: Vicky Nguyen <vicky.nguyen at intel.com>
Date: Tue, 1 Dec 2026 12:41:38 -0800
Subject: [PATCH 9/9] [LinkerWrapper][Driver] Pass the host linker flavor to
 clang-linker-wrapper

The wrapper parsed every host link line as GNU-style, so MSVC-style options
were misread: -link as '-l ink', -LTCG as '-L TCG', -opt:ref as '-o pt:ref'.

The driver now passes --linker-flavor=msvc when the link tool writes
MSVC-style arguments . The wrapper hides GNU-only options
(-l, -L, --library*, -o) for msvc and MSVC-only ones (-libpath:,
-wholearchive) for gnu, the default. Direct MSVC-style callers must now pass
--linker-flavor=msvc.

Co-Authored-By: Claude Sonnet 5.5 <noreply at anthropic.com>
---
 clang/docs/ClangLinkerWrapper.md              |  14 ++
 clang/include/clang/Basic/LinkerFlavor.h      |  52 +++++++
 clang/include/clang/Driver/Tool.h             |   2 +
 clang/lib/Driver/ToolChains/Clang.cpp         |   7 +
 clang/lib/Driver/ToolChains/MSVC.h            |   1 +
 clang/lib/Driver/ToolChains/UEFI.h            |   1 +
 clang/test/Driver/linker-wrapper-flavor.c     |  36 +++++
 .../clang-linker-wrapper/linker-wrapper.c     |   8 +-
 .../clang-linker-wrapper/msvc-link-options.c  | 138 ++++++++++++++++++
 .../ClangLinkerWrapper.cpp                    |  73 +++++++--
 .../clang-linker-wrapper/LinkerWrapperOpts.td |  44 ++++--
 11 files changed, 351 insertions(+), 25 deletions(-)
 create mode 100644 clang/include/clang/Basic/LinkerFlavor.h
 create mode 100644 clang/test/Driver/linker-wrapper-flavor.c
 create mode 100644 clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c

diff --git a/clang/docs/ClangLinkerWrapper.md b/clang/docs/ClangLinkerWrapper.md
index 7245d3cead6ad9..7b25d77f0c0e9a 100644
--- a/clang/docs/ClangLinkerWrapper.md
+++ b/clang/docs/ClangLinkerWrapper.md
@@ -29,6 +29,8 @@ OPTIONS:
   --help-hidden          Display all available options
   --help                 Display available options (--help-hidden for more)
   --host-triple=<triple> Triple to use for the host compilation
+  --linker-flavor=<gnu|msvc>
+                         Argument style of the host linker (default: gnu)
   --linker-path=<path>   The linker executable to invoke
   -L <dir>               Add <dir> to the library search path
   -l <libname>           Search for library <libname>
@@ -132,3 +134,15 @@ section and run a device linking job on it.
 ```console
 clang-linker-wrapper --host-triple=x86_64 --linker-path=/usr/bin/ld -- <Args>
 ```
+
+For an MSVC-style linker (`link.exe`, `lld-link`), pass `--linker-flavor=msvc`
+so that options such as `-libpath:` are understood and options such as `-link`
+and `-LTCG` are passed through unchanged, instead of being misread as `-l ink`
+and `-L TCG`. The host linker arguments are parsed as GNU-style (`ld`, `ld.lld`)
+by default. The Clang driver passes this option when it builds an MSVC-style
+link.
+
+```console
+clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --linker-flavor=msvc \
+  --linker-path=lld-link -- <Args>
+```
diff --git a/clang/include/clang/Basic/LinkerFlavor.h b/clang/include/clang/Basic/LinkerFlavor.h
new file mode 100644
index 00000000000000..d1e0be6e984f3a
--- /dev/null
+++ b/clang/include/clang/Basic/LinkerFlavor.h
@@ -0,0 +1,52 @@
+//===--- LinkerFlavor.h - Linker argument styles ----------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// The argument styles a host link line can use. The Clang driver passes the
+// name to clang-linker-wrapper with '--linker-flavor=', and the wrapper reads
+// it back, so both sides share the names defined here.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_BASIC_LINKERFLAVOR_H
+#define LLVM_CLANG_BASIC_LINKERFLAVOR_H
+
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/ErrorHandling.h"
+#include <optional>
+
+namespace clang {
+
+/// The argument style a link tool writes.
+enum class LinkerFlavor {
+  GNU,  // ld, ld.lld, ld64 and others: '-o', '-l', '-L'.
+  MSVC, // link.exe, lld-link: '-out:', '-libpath:', no '-l' or '-L'.
+};
+
+/// Return the name of \p Flavor, as used by '--linker-flavor='.
+inline llvm::StringRef getLinkerFlavorName(LinkerFlavor Flavor) {
+  switch (Flavor) {
+  case LinkerFlavor::GNU:
+    return "gnu";
+  case LinkerFlavor::MSVC:
+    return "msvc";
+  }
+  llvm_unreachable("unknown linker flavor");
+}
+
+/// Return the flavor named \p Name, or std::nullopt if there is none.
+inline std::optional<LinkerFlavor>
+getLinkerFlavorFromName(llvm::StringRef Name) {
+  for (LinkerFlavor Flavor : {LinkerFlavor::GNU, LinkerFlavor::MSVC})
+    if (Name == getLinkerFlavorName(Flavor))
+      return Flavor;
+  return std::nullopt;
+}
+
+} // namespace clang
+
+#endif // LLVM_CLANG_BASIC_LINKERFLAVOR_H
diff --git a/clang/include/clang/Driver/Tool.h b/clang/include/clang/Driver/Tool.h
index f356d13bd95e92..036a096529046c 100644
--- a/clang/include/clang/Driver/Tool.h
+++ b/clang/include/clang/Driver/Tool.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_DRIVER_TOOL_H
 
 #include "clang/Basic/LLVM.h"
+#include "clang/Basic/LinkerFlavor.h"
 
 namespace llvm {
 namespace opt {
@@ -55,6 +56,7 @@ class Tool {
   virtual bool canEmitIR() const { return false; }
   virtual bool hasIntegratedCPP() const = 0;
   virtual bool isLinkJob() const { return false; }
+  virtual LinkerFlavor getLinkerFlavor() const { return LinkerFlavor::GNU; }
   virtual bool isDsymutilJob() const { return false; }
 
   /// Does this tool have "good" standardized diagnostics, or should the
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp
index bd80f146f3a45d..056fae3c78212f 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -10042,6 +10042,13 @@ void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
     }
   }
 
+  // Pass the host linker flavor to the wrapper. Only MSVC is supported for
+  // now; add other flavors here when they need special handling.
+  if (LinkerFlavor Flavor = Linker->getLinkerFlavor();
+      Flavor == LinkerFlavor::MSVC)
+    CmdArgs.push_back(
+        Args.MakeArgString("--linker-flavor=" + getLinkerFlavorName(Flavor)));
+
   if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
     CmdArgs.push_back(
         Args.MakeArgString("--host-triple=" + AuxTriple->getTriple()));
diff --git a/clang/lib/Driver/ToolChains/MSVC.h b/clang/lib/Driver/ToolChains/MSVC.h
index 90461a1443da31..f741dbcd96431a 100644
--- a/clang/lib/Driver/ToolChains/MSVC.h
+++ b/clang/lib/Driver/ToolChains/MSVC.h
@@ -31,6 +31,7 @@ class LLVM_LIBRARY_VISIBILITY Linker final : public Tool {
 
   bool hasIntegratedCPP() const override { return false; }
   bool isLinkJob() const override { return true; }
+  LinkerFlavor getLinkerFlavor() const override { return LinkerFlavor::MSVC; }
 
   void ConstructJob(Compilation &C, const JobAction &JA,
                     const InputInfo &Output, const InputInfoList &Inputs,
diff --git a/clang/lib/Driver/ToolChains/UEFI.h b/clang/lib/Driver/ToolChains/UEFI.h
index 4474c2fcc6939d..367ad6479f880b 100644
--- a/clang/lib/Driver/ToolChains/UEFI.h
+++ b/clang/lib/Driver/ToolChains/UEFI.h
@@ -21,6 +21,7 @@ class LLVM_LIBRARY_VISIBILITY Linker : public Tool {
 
   bool hasIntegratedCPP() const override { return false; }
   bool isLinkJob() const override { return true; }
+  LinkerFlavor getLinkerFlavor() const override { return LinkerFlavor::MSVC; }
 
   void ConstructJob(Compilation &C, const JobAction &JA,
                     const InputInfo &Output, const InputInfoList &Inputs,
diff --git a/clang/test/Driver/linker-wrapper-flavor.c b/clang/test/Driver/linker-wrapper-flavor.c
new file mode 100644
index 00000000000000..7c24e9d9855401
--- /dev/null
+++ b/clang/test/Driver/linker-wrapper-flavor.c
@@ -0,0 +1,36 @@
+// The driver passes '--linker-flavor=msvc' to clang-linker-wrapper when the
+// host link line is built by an MSVC-style linker tool. The tool decides, not
+// the linker name or the target triple.
+
+// RUN: rm -rf %t && mkdir -p %t && touch %t/my-msvc-link.exe
+// RUN: touch %t/ld.bfd %t/ld.bfd.exe && chmod +x %t/ld.bfd %t/ld.bfd.exe
+
+// RUN: %clang -### --target=x86_64-pc-windows-msvc -fopenmp=libomp \
+// RUN:   --offload-arch=gfx90a -nogpulib -nogpuinc %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MSVC
+// RUN: %clang -### --target=x86_64-pc-windows-msvc -fopenmp=libomp \
+// RUN:   --offload-arch=gfx90a -nogpulib -nogpuinc -fuse-ld=lld %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MSVC
+// RUN: %clang -### --target=x86_64-pc-windows-msvc -fopenmp=libomp \
+// RUN:   --offload-arch=gfx90a -nogpulib -nogpuinc \
+// RUN:   -fuse-ld=%t/my-msvc-link.exe %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MSVC
+// RUN: %clang_cl -### --target=x86_64-pc-windows-msvc -clang:-fopenmp=libomp \
+// RUN:   -clang:--offload-arch=gfx90a -clang:-nogpulib -clang:-nogpuinc \
+// RUN:   -- %s 2>&1 | FileCheck %s --check-prefix=MSVC
+
+// MSVC: clang-linker-wrapper{{.*}} "--linker-flavor=msvc"
+
+// '-fuse-ld=bfd' on an MSVC target builds a GNU-style link line.
+// RUN: %clang -### --target=x86_64-pc-windows-msvc -fopenmp=libomp \
+// RUN:   --offload-arch=gfx90a -nogpulib -nogpuinc -fuse-ld=bfd -B %t %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=GNU
+// RUN: %clang -### --target=x86_64-w64-windows-gnu -fopenmp=libomp \
+// RUN:   --offload-arch=gfx90a -nogpulib -nogpuinc %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=GNU
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp \
+// RUN:   --offload-arch=gfx90a -nogpulib -nogpuinc %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=GNU
+
+// GNU: clang-linker-wrapper
+// GNU-NOT: --linker-flavor
diff --git a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper.c b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper.c
index d37d7a4eca641a..c59f787c6ad64c 100644
--- a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper.c
+++ b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper.c
@@ -185,7 +185,7 @@ __attribute__((visibility("protected"), used)) int x;
 // RUN:   --image=file=%t.elf.o,kind=openmp,triple=nvptx64-nvidia-cuda,arch=sm_70
 // RUN: %clang -cc1 %s -triple x86_64-unknown-windows-msvc -emit-obj -o %t.o -fembed-offload-object=%t.out
 // RUN: clang-linker-wrapper --host-triple=x86_64-unknown-windows-msvc --dry-run \
-// RUN:   --linker-path=/usr/bin/lld-link %t.o -libpath:./ -out:a.exe 2>&1 | FileCheck %s --check-prefix=COFF
+// RUN:   --linker-flavor=msvc --linker-path=/usr/bin/lld-link %t.o -libpath:./ -out:a.exe 2>&1 | FileCheck %s --check-prefix=COFF
 
 // COFF: "/usr/bin/lld-link" {{.*}}.o -libpath:./ -out:a.exe {{.*}}openmp.image.wrapper{{.*}}
 
@@ -193,7 +193,7 @@ __attribute__((visibility("protected"), used)) int x;
 // RUN: llvm-ar rcs %t.dir/foo.lib %t.o
 // RUN: llvm-ar rcs %t.dir/libbar.dll.a %t.o
 // RUN: clang-linker-wrapper --host-triple=x86_64-unknown-windows-msvc --dry-run \
-// RUN:   --linker-path=/usr/bin/lld-link %t.o -libpath:%t.dir foo.lib -out:a.exe 2>&1 \
+// RUN:   --linker-flavor=msvc --linker-path=/usr/bin/lld-link %t.o -libpath:%t.dir foo.lib -out:a.exe 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=COFF-LIBRARY
 // RUN: clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --dry-run \
 // RUN:   --linker-path=/usr/bin/ld.lld %t.o -L%t.dir -lbar -o a.exe 2>&1 \
@@ -202,10 +202,10 @@ __attribute__((visibility("protected"), used)) int x;
 // COFF-LIBRARY: clang{{.*}} --target=nvptx64-nvidia-cuda -march=sm_70 {{.*}}.o {{.*}}.o
 
 // RUN: clang-linker-wrapper --host-triple=x86_64-unknown-windows-msvc --dry-run \
-// RUN:   --linker-path=/usr/bin/lld-link -wholearchive:%t.dir/foo.lib -out:a.exe 2>&1 \
+// RUN:   --linker-flavor=msvc --linker-path=/usr/bin/lld-link -wholearchive:%t.dir/foo.lib -out:a.exe 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=COFF-WHOLE-ARCHIVE
 // RUN: clang-linker-wrapper --host-triple=x86_64-unknown-windows-msvc --dry-run \
-// RUN:   --linker-path=/usr/bin/lld-link -libpath:%t.dir -wholearchive:foo.lib -out:a.exe 2>&1 \
+// RUN:   --linker-flavor=msvc --linker-path=/usr/bin/lld-link -libpath:%t.dir -wholearchive:foo.lib -out:a.exe 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=COFF-WHOLE-ARCHIVE
 
 // COFF-WHOLE-ARCHIVE: clang{{.*}} --target=nvptx64-nvidia-cuda -march=sm_70 {{[^ ]*}}.o{{$}}
diff --git a/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c b/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
new file mode 100644
index 00000000000000..d998776524c779
--- /dev/null
+++ b/clang/test/OffloadTools/clang-linker-wrapper/msvc-link-options.c
@@ -0,0 +1,138 @@
+// REQUIRES: x86-registered-target
+
+// '--linker-flavor=' tells the wrapper how the host link line is written. The
+// Clang driver sets it from the tool that built the line. An MSVC-style linker
+// has no '-l' or '-L' options, so options such as '-link' and '-LTCG' must be
+// passed to the linker as they are, not read as '-l ink' or '-L TCG'.
+
+// An empty object has no embedded device code, so only the host link is run.
+// RUN: touch %t.o
+
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-flavor=msvc --linker-path=/usr/bin/lld-link %t.o -link -LTCG \
+// RUN:   -LARGEADDRESSAWARE /link -libpath:%t.dir -out:%t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MSVC
+
+// MSVC-NOT: error
+// MSVC: "/usr/bin/lld-link" {{.*}}.o -link -LTCG -LARGEADDRESSAWARE /link -libpath:{{.*}} -out:{{.*}}.exe
+
+// The same options must not be misparsed when the wrapper re-parses them to
+// link a CPU offload image, which copies library options into the device link.
+// RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.elf.o
+// RUN: llvm-offload-binary -o %t.out \
+// RUN:   --image=file=%t.elf.o,kind=openmp,triple=x86_64-unknown-linux-gnu
+// RUN: %clang -cc1 %s -triple x86_64-pc-windows-msvc -emit-obj -o %t.host.o \
+// RUN:   -fembed-offload-object=%t.out
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-flavor=msvc --linker-path=/usr/bin/lld-link %t.host.o -link \
+// RUN:   -LTCG -out:%t.exe 2>&1 | FileCheck %s --check-prefix=MSVC-CPU
+
+// MSVC-CPU: clang{{.*}} --target=x86_64-unknown-linux-gnu {{.*}} -Wl,-Bsymbolic -shared{{$}}
+// MSVC-CPU: "/usr/bin/lld-link" {{.*}}.o -link -LTCG -out:{{.*}}.exe
+
+// The flavor, not the linker name, decides. Any name works.
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-flavor=msvc --linker-path=/tools/my-msvc-link %t.o -link \
+// RUN:   -LTCG -out:%t.exe 2>&1 | FileCheck %s --check-prefix=MSVC-ANY
+
+// MSVC-ANY-NOT: error
+// MSVC-ANY: "/tools/my-msvc-link" {{.*}}.o -link -LTCG -out:{{.*}}.exe
+
+// '-o' is not a prefix for MSVC-style options such as '-opt:ref' or
+// '-order:@file'.
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-flavor=msvc --linker-path=/usr/bin/lld-link %t.o -opt:ref \
+// RUN:   -order:@%t.ord -out:%t.exe 2>&1 | FileCheck %s --check-prefix=MSVC-OPT
+
+// MSVC-OPT-NOT: error
+// MSVC-OPT: "/usr/bin/lld-link" {{.*}}.o -opt:ref -order:@{{.*}}.ord -out:{{.*}}.exe
+// MSVC-OPT-NOT: -o
+
+// The long forms '--library' and '--library-path' are passed as they are too.
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-flavor=msvc --linker-path=/usr/bin/lld-link %t.o --library=foo \
+// RUN:   --library bar --library-path=%t.dir --library-path %t.dir -out:%t.exe \
+// RUN:   2>&1 | FileCheck %s --check-prefix=MSVC-LONG
+
+// MSVC-LONG-NOT: error
+// MSVC-LONG: "/usr/bin/lld-link" {{.*}}.o --library=foo --library bar --library-path={{.*}} --library-path {{.*}} -out:{{.*}}.exe
+
+// The flag is read from a response file.
+// RUN: echo "--linker-flavor=msvc" > %t.rsp
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   @%t.rsp --linker-path=/usr/bin/lld-link %t.o -link -out:%t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MSVC-RSP
+
+// MSVC-RSP-NOT: error
+// MSVC-RSP: "/usr/bin/lld-link" {{.*}}.o -link -out:{{.*}}.exe
+
+// Without the flag, the flavor is GNU, even for lld-link. The last flag wins.
+// RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-path=/usr/bin/lld-link %t.o -link -out:%t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=DEFAULT-GNU
+// RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-flavor=msvc --linker-flavor=gnu --linker-path=/usr/bin/lld-link \
+// RUN:   %t.o -link -out:%t.exe 2>&1 | FileCheck %s --check-prefix=DEFAULT-GNU
+
+// DEFAULT-GNU: error: unable to find library -link
+
+// GNU-style linkers treat '-l' and '-L' as library options.
+// RUN: not clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --dry-run \
+// RUN:   --linker-path=/usr/bin/ld.lld %t.o -L%t.dir -link -o %t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=GNU
+
+// GNU: error: unable to find library -link
+
+// GNU-style linkers treat the long forms as library options.
+// RUN: not clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --dry-run \
+// RUN:   --linker-path=/usr/bin/ld.lld %t.o --library-path=%t.dir --library=foo \
+// RUN:   -o %t.exe 2>&1 | FileCheck %s --check-prefix=GNU-LONG-EQ
+// RUN: not clang-linker-wrapper --host-triple=x86_64-w64-windows-gnu --dry-run \
+// RUN:   --linker-path=/usr/bin/ld.lld %t.o --library-path %t.dir --library bar \
+// RUN:   -o %t.exe 2>&1 | FileCheck %s --check-prefix=GNU-LONG-S
+
+// GNU-LONG-EQ: error: unable to find library -lfoo
+// GNU-LONG-S: error: unable to find library -lbar
+
+// MSVC-only options are not options for GNU, so '-libpath:' is '-l ibpath:'.
+// RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-path=/usr/bin/ld.lld %t.o -libpath:%t.dir -o %t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=GNU-NO-LIBPATH
+
+// GNU-NO-LIBPATH: error: unable to find library -libpath:
+
+// With an MSVC target and '-fuse-ld=bfd', the driver writes a GNU-style line
+// and sends no flavor. Then '-l' and '-L' are library options.
+// RUN: not clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-path=ld %t.o -L%t.dir -lfoo -o %t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MSVC-GNU-LD
+
+// MSVC-GNU-LD: error: unable to find library -lfoo
+
+// Device code in a library found with '-L' and '-l' is extracted.
+// RUN: rm -rf %t.lib && mkdir %t.lib
+// RUN: llvm-ar rcs %t.lib/libfoo.a %t.host.o
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --dry-run \
+// RUN:   --linker-path=/usr/bin/ld.bfd -L%t.lib --whole-archive -lfoo \
+// RUN:   --no-whole-archive -o %t.exe 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=MSVC-GNU-LIB
+
+// MSVC-GNU-LIB: clang{{.*}} --target=x86_64-unknown-linux-gnu {{.*}}.o -Wl,-Bsymbolic -shared -L {{.*}}.lib -Wl,--whole-archive -l foo -Wl,--no-whole-archive{{$}}
+// MSVC-GNU-LIB: "/usr/bin/ld.bfd" -L {{.*}}.lib --whole-archive -l foo --no-whole-archive -o {{.*}}.exe {{.*}}.wrapper{{.*}}.o
+
+// RUN: not clang-linker-wrapper --linker-flavor=bogus --dry-run %t.o 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=BAD
+
+// BAD: error: invalid linker flavor 'bogus'
+
+// '--help' lists '-l' and '-L' only for the GNU flavor.
+// RUN: clang-linker-wrapper --linker-flavor=msvc --help \
+// RUN:   | FileCheck %s --check-prefix=MSVC-HELP
+// RUN: clang-linker-wrapper --host-triple=x86_64-pc-windows-msvc --help \
+// RUN:   | FileCheck %s --check-prefix=GNU-HELP
+
+// MSVC-HELP: OPTIONS:
+// MSVC-HELP-NOT: -L <dir>
+// MSVC-HELP-NOT: -l <libname>
+// GNU-HELP: -L <dir>
+// GNU-HELP: -l <libname>
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index f305a0a4bdac1a..054ec08357cad1 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -14,6 +14,7 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "clang/Basic/LinkerFlavor.h"
 #include "clang/Basic/TargetID.h"
 #include "clang/Basic/Version.h"
 #include "llvm/ADT/MapVector.h"
@@ -159,6 +160,13 @@ enum WrapperFlags {
   DeviceOnlyOption = (1 << 5),  // Options only used for device linking.
 };
 
+/// One visibility per linker flavor; see LinkerWrapperOpts.td. Must not overlap
+/// with llvm::opt::DefaultVis.
+enum WrapperVisibility {
+  GNUFlavor = (1 << 1),  // Options only valid for GNU-style linkers.
+  MSVCFlavor = (1 << 2), // Options only valid for MSVC-style linkers.
+};
+
 enum ID {
   OPT_INVALID = 0, // This is not an option ID.
 #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
@@ -196,6 +204,57 @@ void printCommands(ArrayRef<StringRef> CmdArgs) {
   exit(EXIT_FAILURE);
 }
 
+/// Return the option visibility for the last '--linker-flavor=' (default
+/// 'gnu'), so that only options valid for that linker flavor are parsed. The
+/// flavor must be known before parsing, so read it from the raw arguments.
+static unsigned getFlavorVisibility(ArrayRef<const char *> ArgStrings) {
+  StringRef Name = clang::getLinkerFlavorName(clang::LinkerFlavor::GNU);
+  for (StringRef Arg : ArgStrings)
+    if (Arg.consume_front("--linker-flavor="))
+      Name = Arg;
+
+  std::optional<clang::LinkerFlavor> Flavor =
+      clang::getLinkerFlavorFromName(Name);
+  if (!Flavor)
+    reportError(
+        createStringError("invalid linker flavor '" + Name.str() + "'"));
+
+  switch (*Flavor) {
+  case clang::LinkerFlavor::GNU:
+    return GNUFlavor;
+  case clang::LinkerFlavor::MSVC:
+    return MSVCFlavor;
+  }
+  llvm_unreachable("unknown linker flavor");
+}
+
+/// Return the visibility mask to parse with: shared options plus the options
+/// of the linker flavor.
+Visibility getWrapperVisibility(ArrayRef<const char *> ArgStrings) {
+  return Visibility(DefaultVis | getFlavorVisibility(ArgStrings));
+}
+
+/// Parse the wrapper's command line. Expanded response file strings are owned
+/// by \p Saver, which must outlive the returned list. If \p VisibilityOut is
+/// set, it receives the visibility mask used for parsing.
+InputArgList parseWrapperArgs(int Argc, char **Argv, StringSaver &Saver,
+                              Visibility *VisibilityOut = nullptr) {
+  SmallVector<const char *, 0> ArgStrings;
+  cl::expandResponseFiles(Argc, Argv, /*EnvVar=*/nullptr, Saver, ArgStrings);
+
+  Visibility VisibilityMask = getWrapperVisibility(ArgStrings);
+  if (VisibilityOut)
+    *VisibilityOut = VisibilityMask;
+
+  unsigned MissingArgIndex, MissingArgCount;
+  InputArgList Args = getOptTable().ParseArgs(ArgStrings, MissingArgIndex,
+                                              MissingArgCount, VisibilityMask);
+  if (MissingArgCount)
+    reportError(createStringError(Twine(Args.getArgString(MissingArgIndex)) +
+                                  ": missing argument"));
+  return Args;
+}
+
 std::string getExecutableDir(const char *Name) {
   if (!CanonicalPrefixes)
     return sys::path::parent_path(LinkerExecutable).str();
@@ -1119,13 +1178,9 @@ linkAndWrapDeviceFiles(ArrayRef<SmallVector<OffloadFile>> LinkerInputFiles,
 
     // Each thread needs its own copy of the base arguments to maintain
     // per-device argument storage of synthetic strings.
-    const OptTable &Tbl = getOptTable();
     BumpPtrAllocator Alloc;
     StringSaver Saver(Alloc);
-    auto BaseArgs =
-        Tbl.parseArgs(Argc, Argv, OPT_INVALID, Saver, [](StringRef Err) {
-          reportError(createStringError(Err));
-        });
+    auto BaseArgs = parseWrapperArgs(Argc, Argv, Saver);
     auto LinkerArgs = getLinkerArgs(Input, BaseArgs);
 
     uint16_t ActiveOffloadKindMask = 0u;
@@ -1534,9 +1589,8 @@ int main(int Argc, char **Argv) {
   const OptTable &Tbl = getOptTable();
   BumpPtrAllocator Alloc;
   StringSaver Saver(Alloc);
-  auto Args = Tbl.parseArgs(Argc, Argv, OPT_INVALID, Saver, [&](StringRef Err) {
-    reportError(createStringError(Err));
-  });
+  Visibility VisibilityMask;
+  auto Args = parseWrapperArgs(Argc, Argv, Saver, &VisibilityMask);
 
   if (Args.hasArg(OPT_help) || Args.hasArg(OPT_help_hidden)) {
     Tbl.printHelp(
@@ -1546,7 +1600,8 @@ int main(int Argc, char **Argv) {
         "for sections that require additional processing prior to linking.\n"
         "It will then transparently pass all arguments and input to the\n"
         "specified host linker to create the final binary.\n",
-        Args.hasArg(OPT_help_hidden), Args.hasArg(OPT_help_hidden));
+        Args.hasArg(OPT_help_hidden), Args.hasArg(OPT_help_hidden),
+        VisibilityMask);
     return EXIT_SUCCESS;
   }
   if (Args.hasArg(OPT_version)) {
diff --git a/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td b/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
index fc48eac2637eeb..8bd9f93de8c1e7 100644
--- a/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
+++ b/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
@@ -2,6 +2,14 @@ include "llvm/Option/OptParser.td"
 
 def WrapperOnlyOption : OptionFlag;
 def DeviceOnlyOption : OptionFlag;
+// Each linker flavor is an option visibility, picked with '--linker-flavor='.
+// Options tagged with a flavor are parsed only for that flavor; untagged
+// options are shared. For example, MSVC-style linkers have no -l or -L, so
+// those are GNU-only; otherwise -link and -LTCG would be read as '-l ink' and
+// '-L TCG'. A new flavor needs a def here, tags on its options, and a row in
+// getFlavorVisibility().
+def GNUFlavor : OptionVisibility;
+def MSVCFlavor : OptionVisibility;
 
 def help : Flag<["--"], "help">,
   HelpText<"Display available options (--help-hidden for more)">;
@@ -16,6 +24,9 @@ def linker_path_EQ : Joined<["--"], "linker-path=">,
 def cuda_path_EQ : Joined<["--"], "cuda-path=">,
   Flags<[WrapperOnlyOption]>, MetaVarName<"<dir>">,
   HelpText<"Set the system CUDA path">;
+def linker_flavor_EQ : Joined<["--"], "linker-flavor=">,
+  Flags<[WrapperOnlyOption]>, MetaVarName<"<gnu|msvc>">,
+  HelpText<"Argument style of the host linker (default: gnu)">;
 def host_triple_EQ : Joined<["--"], "host-triple=">,
                      Flags<[WrapperOnlyOption]>,
                      MetaVarName<"<triple>">,
@@ -103,26 +114,32 @@ def offload_opt_eq_minus : Joined<["--", "-"], "offload-opt=">, Flags<[HelpHidde
 // Standard linker flags also used by the linker wrapper.
 def sysroot_EQ : Joined<["--"], "sysroot=">, HelpText<"Set the system root">;
 
+// GNU-only: MSVC-style linkers use '-out:', and a '-o' prefix would eat options
+// such as '-opt:ref' and '-order:@file'.
 def o : JoinedOrSeparate<["-"], "o">, MetaVarName<"<path>">,
-  HelpText<"Path to file to write output">;
+  Visibility<[GNUFlavor]>, HelpText<"Path to file to write output">;
 def output_EQ : Joined<["--"], "output=">, Alias<o>, Flags<[HelpHidden]>,
   HelpText<"Alias for -o">;
 def output : Separate<["--"], "output">, Alias<o>, Flags<[HelpHidden]>,
   HelpText<"Alias for -o">;
 
+// GNU-style library and library path options. The driver renders them as
+// 'foo.lib' and '-libpath:' for MSVC-style linkers.
 def library_path : JoinedOrSeparate<["-"], "L">, MetaVarName<"<dir>">,
+  Visibility<[GNUFlavor]>,
   HelpText<"Add <dir> to the library search path">;
-def library_path_S : Separate<["--", "-"], "library-path">, Flags<[HelpHidden]>,
-  Alias<library_path>;
-def library_path_EQ : Joined<["--", "-"], "library-path=">, Flags<[HelpHidden]>,
-  Alias<library_path>;
+def library_path_S : Separate<["--", "-"], "library-path">,
+  Flags<[HelpHidden]>, Visibility<[GNUFlavor]>, Alias<library_path>;
+def library_path_EQ : Joined<["--", "-"], "library-path=">,
+  Flags<[HelpHidden]>, Visibility<[GNUFlavor]>, Alias<library_path>;
 
 def library : JoinedOrSeparate<["-"], "l">, MetaVarName<"<libname>">,
+  Visibility<[GNUFlavor]>,
   HelpText<"Search for library <libname>">;
-def library_S : Separate<["--", "-"], "library">, Flags<[HelpHidden]>,
-  Alias<library>;
-def library_EQ : Joined<["--", "-"], "library=">, Flags<[HelpHidden]>,
-  Alias<library>;
+def library_S : Separate<["--", "-"], "library">,
+  Flags<[HelpHidden]>, Visibility<[GNUFlavor]>, Alias<library>;
+def library_EQ : Joined<["--", "-"], "library=">,
+  Flags<[HelpHidden]>, Visibility<[GNUFlavor]>, Alias<library>;
 
 def rpath : Separate<["--", "-"], "rpath">;
 def rpath_EQ : Joined<["--", "-"], "rpath=">, Flags<[HelpHidden]>, Alias<rpath>;
@@ -138,6 +155,9 @@ def r : Flag<["-"], "r">, Alias<relocatable>;
 
 // link.exe-style linker options.
 def out : Joined<["/", "-", "/?", "-?"], "out:">, Flags<[HelpHidden]>;
-def libpath : Joined<["/", "-", "/?", "-?"], "libpath:">, Flags<[HelpHidden]>;
-def wholearchive_file : Joined<["/", "-", "/?", "-?"], "wholearchive:">, Flags<[HelpHidden]>;
-def wholearchive_flag : Flag<["/", "-", "/?", "-?"], "wholearchive">, Flags<[HelpHidden]>;
+def libpath : Joined<["/", "-", "/?", "-?"], "libpath:">, Flags<[HelpHidden]>,
+  Visibility<[MSVCFlavor]>;
+def wholearchive_file : Joined<["/", "-", "/?", "-?"], "wholearchive:">,
+  Flags<[HelpHidden]>, Visibility<[MSVCFlavor]>;
+def wholearchive_flag : Flag<["/", "-", "/?", "-?"], "wholearchive">,
+  Flags<[HelpHidden]>, Visibility<[MSVCFlavor]>;



More information about the cfe-commits mailing list