[clang] [llvm] [Option] Let a tool parse its command line into an options struct (PR #246881)
Fangrui Song via cfe-commits
cfe-commits at lists.llvm.org
Sun Nov 29 10:04:38 PST 2026
https://github.com/MaskRay updated https://github.com/llvm/llvm-project/pull/246881
>From f27e6eb9b085a15830cdc679b481d58b7934ab9d Mon Sep 17 00:00:00 2001
From: Fangrui Song <i at maskray.me>
Date: Sat, 28 Nov 2026 10:28:54 -0800
Subject: [PATCH 1/3] [Option] Let a tool parse its command line into an
options struct
Follow-up to #246766: Generalize `OptionsStruct` so that a tool, not
only a library, can get its options as a generated struct.
opt::parseToolArgs parses argv with OptTable::parseArgs, keeping
response files and typo suggestions, and fills the struct.
OptionsStruct<""> gives a tool's struct internal linkage.
`RepeatedField` appends each occurrence's whole value, for options such
as -extra-arg whose values contain commas.
The parts a struct needs without cl:: move from LibraryOptions.h to the
new OptionsStruct.h, and LibraryOptTable becomes OptionsStructTable.
Convert clang-diff.
LLM-aided
---
clang/tools/clang-diff/ClangDiff.cpp | 123 +++++--------
clang/tools/clang-diff/Opts.td | 29 ++-
llvm/docs/CommandLine.md | 6 +
llvm/include/llvm/Option/LibraryOptions.h | 103 +----------
llvm/include/llvm/Option/LibraryOptions.td | 9 +
llvm/include/llvm/Option/OptionsStruct.h | 166 ++++++++++++++++++
llvm/lib/Option/CMakeLists.txt | 1 +
llvm/lib/Option/LibraryOptions.cpp | 2 -
llvm/lib/Option/OptionsStruct.cpp | 41 +++++
llvm/unittests/Option/LibraryOptionsTest.cpp | 24 +++
llvm/unittests/Option/LibraryOpts.td | 1 +
.../TableGen/Basic/OptionParserEmitter.cpp | 16 +-
.../gn/secondary/llvm/lib/Option/BUILD.gn | 1 +
13 files changed, 320 insertions(+), 202 deletions(-)
create mode 100644 llvm/include/llvm/Option/OptionsStruct.h
create mode 100644 llvm/lib/Option/OptionsStruct.cpp
diff --git a/clang/tools/clang-diff/ClangDiff.cpp b/clang/tools/clang-diff/ClangDiff.cpp
index 1cee8f62cd9f5d..00701ee3c45ebf 100644
--- a/clang/tools/clang-diff/ClangDiff.cpp
+++ b/clang/tools/clang-diff/ClangDiff.cpp
@@ -11,59 +11,47 @@
//
//===----------------------------------------------------------------------===//
+#define OPTIONS_STRUCT_DECL
+#include "Opts.inc"
+
#include "clang/Tooling/ASTDiff/ASTDiff.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
-#include "llvm/Option/ArgList.h"
-#include "llvm/Option/OptTable.h"
+#include "llvm/Option/OptionsStruct.h"
+
+#define OPTIONS_STRUCT_DEFS
+#include "Opts.inc"
using namespace llvm;
using namespace clang;
using namespace clang::tooling;
-namespace {
-using namespace llvm::opt;
-enum ID {
- OPT_INVALID = 0,
-#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
-#include "Opts.inc"
-#undef OPTION
-};
-
-#define OPTTABLE_CODE
-#include "Opts.inc"
-
-class ClangDiffOptTable : public OptTable {
-public:
- ClangDiffOptTable() : OptTable(optionTables()) {}
-};
-} // namespace
-
-static std::string BuildPath;
-static std::vector<std::string> ArgsAfter;
-static std::vector<std::string> ArgsBefore;
-
-static void addExtraArgs(std::unique_ptr<CompilationDatabase> &Compilations) {
+static void addExtraArgs(const ClangDiffOptions &Opts,
+ std::unique_ptr<CompilationDatabase> &Compilations) {
if (!Compilations)
return;
auto AdjustingCompilations =
std::make_unique<ArgumentsAdjustingCompilations>(
std::move(Compilations));
- AdjustingCompilations->appendArgumentsAdjuster(
- getInsertArgumentAdjuster(ArgsBefore, ArgumentInsertPosition::BEGIN));
- AdjustingCompilations->appendArgumentsAdjuster(
- getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END));
+ AdjustingCompilations->appendArgumentsAdjuster(getInsertArgumentAdjuster(
+ std::vector<std::string>(Opts.extra_arg_before.begin(),
+ Opts.extra_arg_before.end()),
+ ArgumentInsertPosition::BEGIN));
+ AdjustingCompilations->appendArgumentsAdjuster(getInsertArgumentAdjuster(
+ std::vector<std::string>(Opts.extra_arg.begin(), Opts.extra_arg.end()),
+ ArgumentInsertPosition::END));
Compilations = std::move(AdjustingCompilations);
}
static std::unique_ptr<ASTUnit>
-getAST(const std::unique_ptr<CompilationDatabase> &CommonCompilations,
+getAST(const ClangDiffOptions &Opts,
+ const std::unique_ptr<CompilationDatabase> &CommonCompilations,
const StringRef Filename) {
std::string ErrorMessage;
std::unique_ptr<CompilationDatabase> Compilations;
if (!CommonCompilations) {
Compilations = CompilationDatabase::autoDetectFromSource(
- BuildPath.empty() ? Filename : BuildPath, ErrorMessage);
+ Opts.p.empty() ? Filename : Opts.p, ErrorMessage);
if (!Compilations) {
llvm::errs()
<< "Error while trying to load a compilation database, running "
@@ -74,7 +62,7 @@ getAST(const std::unique_ptr<CompilationDatabase> &CommonCompilations,
".", std::vector<std::string>());
}
}
- addExtraArgs(Compilations);
+ addExtraArgs(Opts, Compilations);
std::array<std::string, 1> Files = {{std::string(Filename)}};
ClangTool Tool(Compilations ? *Compilations : *CommonCompilations, Files);
std::vector<std::unique_ptr<ASTUnit>> ASTs;
@@ -420,54 +408,37 @@ int main(int argc, const char **argv) {
if (!CommonCompilations && !ErrorMessage.empty())
llvm::errs() << ErrorMessage;
BumpPtrAllocator Alloc;
- StringSaver Saver(Alloc);
- ClangDiffOptTable Tbl;
- opt::InputArgList Args = Tbl.parseArgs(
- argc, const_cast<char **>(argv), OPT_UNKNOWN, Saver, [](StringRef Msg) {
- llvm::errs() << "Error: " << Msg << "\n";
- exit(1);
- });
- if (Args.hasArg(OPT_help)) {
- Tbl.printHelp(llvm::outs(), "clang-diff [options] <source> [<destination>]",
- "Compare source files by AST nodes");
+ ClangDiffOptions Opts;
+ SmallVector<StringRef, 2> Inputs;
+ if (Error E = opt::parseToolArgs(Opts, argc, argv, Alloc, Inputs)) {
+ llvm::errs() << "Error: " << toString(std::move(E)) << "\n";
+ return 1;
+ }
+ if (Opts.help) {
+ ClangDiffOptions::optTable().printHelp(
+ llvm::outs(), "clang-diff [options] <source> [<destination>]",
+ "Compare source files by AST nodes");
return 0;
}
- std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
if (Inputs.empty() || Inputs.size() > 2) {
llvm::errs() << "Error: Expected one or two paths.\n";
return 1;
}
- std::string SourcePath = Inputs[0];
- std::string DestinationPath = Inputs.size() > 1 ? Inputs[1] : "";
- bool ASTDump = Args.hasArg(OPT_ast_dump);
- bool ASTDumpJson = Args.hasArg(OPT_ast_dump_json);
- bool PrintMatches = Args.hasArg(OPT_dump_matches);
- bool HtmlDiff = Args.hasArg(OPT_html);
- std::string StopAfter = Args.getLastArgValue(OPT_stop_diff_after).str();
- int MaxSize = -1;
- if (const opt::Arg *A = Args.getLastArg(OPT_s)) {
- if (StringRef(A->getValue()).getAsInteger(0, MaxSize)) {
- llvm::errs() << "Error: Invalid argument '" << A->getValue()
- << "' for -s\n";
- return 1;
- }
- }
- BuildPath = Args.getLastArgValue(OPT_p).str();
- ArgsAfter = Args.getAllArgValues(OPT_extra_arg);
- ArgsBefore = Args.getAllArgValues(OPT_extra_arg_before);
+ StringRef SourcePath = Inputs[0];
+ StringRef DestinationPath = Inputs.size() > 1 ? Inputs[1] : "";
- addExtraArgs(CommonCompilations);
+ addExtraArgs(Opts, CommonCompilations);
- if (ASTDump || ASTDumpJson) {
+ if (Opts.ast_dump || Opts.ast_dump_json) {
if (!DestinationPath.empty()) {
llvm::errs() << "Error: Please specify exactly one filename.\n";
return 1;
}
- std::unique_ptr<ASTUnit> AST = getAST(CommonCompilations, SourcePath);
+ std::unique_ptr<ASTUnit> AST = getAST(Opts, CommonCompilations, SourcePath);
if (!AST)
return 1;
diff::SyntaxTree Tree(AST->getASTContext());
- if (ASTDump) {
+ if (Opts.ast_dump) {
printTree(llvm::outs(), Tree);
return 0;
}
@@ -484,27 +455,21 @@ int main(int argc, const char **argv) {
return 1;
}
- std::unique_ptr<ASTUnit> Src = getAST(CommonCompilations, SourcePath);
- std::unique_ptr<ASTUnit> Dst = getAST(CommonCompilations, DestinationPath);
+ std::unique_ptr<ASTUnit> Src = getAST(Opts, CommonCompilations, SourcePath);
+ std::unique_ptr<ASTUnit> Dst =
+ getAST(Opts, CommonCompilations, DestinationPath);
if (!Src || !Dst)
return 1;
diff::ComparisonOptions Options;
- if (MaxSize != -1)
- Options.MaxSize = MaxSize;
- if (!StopAfter.empty()) {
- if (StopAfter == "topdown")
- Options.StopAfterTopDown = true;
- else if (StopAfter != "bottomup") {
- llvm::errs() << "Error: Invalid argument for -stop-after\n";
- return 1;
- }
- }
+ if (Opts.s)
+ Options.MaxSize = *Opts.s;
+ Options.StopAfterTopDown = Opts.stop_after_topdown;
diff::SyntaxTree SrcTree(Src->getASTContext());
diff::SyntaxTree DstTree(Dst->getASTContext());
diff::ASTDiff Diff(SrcTree, DstTree, Options);
- if (HtmlDiff) {
+ if (Opts.html) {
llvm::outs() << HtmlDiffHeader << "<pre>";
llvm::outs() << "<div id='L' class='code'>";
printHtmlForNode(llvm::outs(), Diff, SrcTree, true, SrcTree.getRootId(), 0);
@@ -519,7 +484,7 @@ int main(int argc, const char **argv) {
for (diff::NodeId Dst : DstTree) {
diff::NodeId Src = Diff.getMapped(DstTree, Dst);
- if (PrintMatches && Src.isValid()) {
+ if (Opts.dump_matches && Src.isValid()) {
llvm::outs() << "Match ";
printNode(llvm::outs(), SrcTree, Src);
llvm::outs() << " to ";
diff --git a/clang/tools/clang-diff/Opts.td b/clang/tools/clang-diff/Opts.td
index c0a7d108889c49..b60e3ccd9b0027 100644
--- a/clang/tools/clang-diff/Opts.td
+++ b/clang/tools/clang-diff/Opts.td
@@ -1,19 +1,14 @@
-include "llvm/Option/OptParser.td"
+include "llvm/Option/LibraryOptions.td"
-class F<string name, string help> : Flag<["-", "--"], name>, HelpText<help>;
+def ClangDiffOptions : OptionsStruct<"">;
-multiclass Eq<string name, string help> {
- def NAME : Separate<["-", "--"], name>, HelpText<help>;
- def : Joined<["-", "--"], name #"=">, Alias<!cast<Separate>(NAME)>;
-}
-
-def ast_dump : F<"ast-dump", "Print the internal representation of the AST.">;
-def ast_dump_json : F<"ast-dump-json", "Print the internal representation of the AST as JSON.">;
-def dump_matches : F<"dump-matches", "Print the matched nodes.">;
-defm extra_arg : Eq<"extra-arg", "Additional argument to append to the compiler command line">, MetaVarName<"<arg>">;
-defm extra_arg_before : Eq<"extra-arg-before", "Additional argument to prepend to the compiler command line">, MetaVarName<"<arg>">;
-def help : F<"help", "Display available options">;
-def html : F<"html", "Output a side-by-side diff in HTML.">;
-defm p : Eq<"p", "Build path">, MetaVarName<"<build-path>">;
-defm s : Eq<"s", "Maximum subtree size for the optimal bottom-up mapping">, MetaVarName<"<maxsize>">;
-defm stop_diff_after : Eq<"stop-diff-after", "Stop after the given matching phase">, MetaVarName<"<topdown|bottomup>">;
+defm : BoolField<"ast-dump", "false", "Print the internal representation of the AST">;
+defm : BoolField<"ast-dump-json", "false", "Print the internal representation of the AST as JSON">;
+defm : BoolField<"dump-matches", "false", "Print the matched nodes">;
+defm : RepeatedField<"extra-arg", "StringRef", "Additional argument to append to the compiler command line">, MetaVarName<"<arg>">;
+defm : RepeatedField<"extra-arg-before", "StringRef", "Additional argument to prepend to the compiler command line">, MetaVarName<"<arg>">;
+defm : BoolField<"help", "false", "Display available options">;
+defm : BoolField<"html", "false", "Output a side-by-side diff in HTML">;
+defm : ValueField<"p", "StringRef", "", "Build path">, MetaVarName<"<build-path>">;
+defm : OptionalValueField<"s", "int", "Maximum subtree size for the optimal bottom-up mapping">, MetaVarName<"<maxsize>">;
+defm stop_after_topdown : EnumField<"stop-diff-after", "bool", "false", "topdown,bottomup", ["true", "false"], "Stop after the given matching phase">;
diff --git a/llvm/docs/CommandLine.md b/llvm/docs/CommandLine.md
index 795555aaecf97e..7ce1f5b3f4c7db 100644
--- a/llvm/docs/CommandLine.md
+++ b/llvm/docs/CommandLine.md
@@ -1582,6 +1582,7 @@ defm : ValueField<"foo-path", "StringRef", "\"-\"", "The input path">;
```
The struct is in namespace `llvm` unless the def names another, as in `OptionsStruct<"mlir">`.
+A tool's `OptionsStruct<"">` is in an anonymous namespace.
A member is named after its option, `enable_foo` for `-enable-foo`; a named `defm` such as `defm threshold` names it `threshold`.
`OptionsStruct<prefix = "foo-">` drops that prefix from member names, so `-foo-path` sets `path`.
@@ -1592,6 +1593,7 @@ A reader applies a `cl::list_init` default to an empty list, since a given optio
An `OptionalBoolField` is a `BoolOrDefault` that stays `Default` unless the option is given, replacing `cl::boolOrDefault`; read it with `valueOr(X, Default)`.
An `EnumField` maps each of its comma-separated values to an enumerator, replacing `cl::values`: `defm : EnumField<"foo-mode", "FooMode", "FooMode::Fast", "fast,safe", ["FooMode::Fast", "FooMode::Safe"], "The mode">;` accepts `-foo-mode=fast` and `-foo-mode=safe`.
An `EnumListField` is a `ListField` whose values map to enumerators as in an `EnumField`.
+A `RepeatedField` is an `ArrayRef` to which each occurrence appends its whole value, commas included, replacing a `cl::list` without `cl::CommaSeparated`.
A `FlagOrEnumField` takes one more argument, the enumerator the bare option selects, replacing `cl::ValueOptional`: with `"FooMode::Fast"`, `-foo-mode` sets `FooMode::Fast`, and `-foo-mode safe` does not consume `safe`.
A `DefaultOnOffField` is a `BoolOrDefault` set by `=Default`, `=Enable`, or `=Disable`.
Both accept `--` for `-`.
@@ -1606,3 +1608,7 @@ The library then lists `FooOptionsTableGen` under `DEPENDS` and `Option` under `
A library that otherwise needs only `llvm-min-tblgen` sets `LLVM_TABLEGEN_PROJECT` to `LLVM_HEADERS` before its `llvm_tablegen()` call, so that its sources need not wait for `llvm-tblgen`.
Code reads `C.get<FooOptions>().enable_foo` from the context `C` that the tool parsed its command line into, usually through an `LLVMContext`.
Keep the header in `lib/`, as private as the `static cl::opt` it replaces; another library that needs a value calls a function or takes a parameter.
+
+A tool can declare its own options the same way and, including `llvm/Option/OptionsStruct.h`, parse its command line without `cl::`.
+`opt::parseToolArgs(Opts, argc, argv, Alloc, Inputs)` expands response files, sets the members of `Opts`, whose strings refer to `argv` or `Alloc`, and collects the positional arguments, and every argument after `--`, in `Inputs`.
+`T::optTable().printHelp` prints the tool's help.
diff --git a/llvm/include/llvm/Option/LibraryOptions.h b/llvm/include/llvm/Option/LibraryOptions.h
index e30fc5e105089a..bbda8dea15703c 100644
--- a/llvm/include/llvm/Option/LibraryOptions.h
+++ b/llvm/include/llvm/Option/LibraryOptions.h
@@ -6,119 +6,24 @@
//
//===----------------------------------------------------------------------===//
//
-// Support for the options struct that -gen-opt-parser-defs generates from an
-// OptionsStruct def. See "Declaring a Library's Options in TableGen" in
-// llvm/docs/CommandLine.md.
+// Connects the options struct that -gen-opt-parser-defs generates from an
+// OptionsStruct def to cl::parseCommandLineOptions. See "Declaring a Library's
+// Options in TableGen" in llvm/docs/CommandLine.md.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_OPTION_LIBRARYOPTIONS_H
#define LLVM_OPTION_LIBRARYOPTIONS_H
-#include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/BoolOrDefault.h"
-#include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringExtras.h"
-#include "llvm/Option/Arg.h"
-#include "llvm/Option/OptTable.h"
-#include "llvm/Option/Option.h"
+#include "llvm/Option/OptionsStruct.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
-#include <optional>
-#include <type_traits>
#include <utility>
namespace llvm {
namespace opt {
-// Each accepts the spellings cl::opt accepts for the type.
-inline bool parseArgValue(StringRef S, bool &V) {
- if (S == "true" || S == "1")
- V = true;
- else if (S == "false" || S == "0")
- V = false;
- else
- return false;
- return true;
-}
-
-inline bool parseArgValue(StringRef S, BoolOrDefault &V) {
- bool B;
- if (!parseArgValue(S, B))
- return false;
- V = B ? BoolOrDefault::True : BoolOrDefault::False;
- return true;
-}
-
-inline bool parseArgValue(StringRef S, StringRef &V) {
- V = S;
- return true;
-}
-
-template <typename T>
-std::enable_if_t<std::is_arithmetic_v<T> && !std::is_same_v<T, bool>, bool>
-parseArgValue(StringRef S, T &V) {
- if constexpr (std::is_floating_point_v<T>)
- return to_float(S, V);
- else
- return to_integer(S, V);
-}
-
-// A std::optional member is set only when its option is given.
-template <typename T> bool parseArgValue(StringRef S, std::optional<T> &V) {
- T X{};
- if (!parseArgValue(S, X))
- return false;
- V = X;
- return true;
-}
-
-// The generated apply() passes Alloc, which only a list member uses.
-template <typename T>
-bool parseArgValue(StringRef S, T &V, BumpPtrAllocator &) {
- return parseArgValue(S, V);
-}
-
-// An enum member is set by Parse, the generated value-to-enumerator mapping.
-template <typename T, typename F>
-bool parseArgValue(StringRef S, T &V, BumpPtrAllocator &, F Parse) {
- return Parse(S, V);
-}
-
-// A list member appends the comma-separated values of each occurrence. Its
-// storage comes from Alloc, keeping the options struct trivially destructible.
-template <typename T, typename F>
-bool parseArgValue(StringRef S, ArrayRef<T> &List, BumpPtrAllocator &Alloc,
- F ParseElem) {
- static_assert(std::is_trivially_copyable_v<T>);
- SmallVector<T, 4> Elems(List.begin(), List.end());
- for (StringRef Item : split(S, ',')) {
- T Elem{};
- if (!ParseElem(Item, Elem))
- return false;
- Elems.push_back(Elem);
- }
- T *Storage = Alloc.Allocate<T>(Elems.size());
- llvm::copy(Elems, Storage);
- List = ArrayRef(Storage, Elems.size());
- return true;
-}
-
-template <typename T>
-bool parseArgValue(StringRef S, ArrayRef<T> &List, BumpPtrAllocator &Alloc) {
- return parseArgValue(S, List, Alloc, [](StringRef Item, T &Elem) {
- return parseArgValue(Item, Elem);
- });
-}
-
-/// An OptTable with a public constructor, shared by every options struct.
-class LLVM_ABI LibraryOptTable : public OptTable {
-public:
- explicit LibraryOptTable(const Tables &T) : OptTable(T) {}
- ~LibraryOptTable() override;
-};
-
/// Connects options struct T to cl::parseCommandLineOptions and
/// cl::LibraryOptionsContext.
class LLVM_ABI LibraryOptionsParser final : public cl::LibraryOptions {
diff --git a/llvm/include/llvm/Option/LibraryOptions.td b/llvm/include/llvm/Option/LibraryOptions.td
index d54145debc299e..6630f8dc77d4c0 100644
--- a/llvm/include/llvm/Option/LibraryOptions.td
+++ b/llvm/include/llvm/Option/LibraryOptions.td
@@ -113,6 +113,15 @@ multiclass ListField<string name, string type, string help> {
Field<NAME, "llvm::ArrayRef<"#type#">", "">, HelpText<help>;
}
+// An llvm::ArrayRef<<type>> member. Each -<name>=<value> or -<name> <value>
+// appends its whole value, commas included.
+multiclass RepeatedField<string name, string type, string help> {
+ def NAME : SeparateOrEq<["-", "--"], name>,
+ Field<NAME, "llvm::ArrayRef<"#type#">", "">, HelpText<help> {
+ bit Repeated = 1;
+ }
+}
+
// A ListField of the enumeration <type>, with <values> mapping to <enumerators>
// as in EnumField.
multiclass EnumListField<string name, string type, string values,
diff --git a/llvm/include/llvm/Option/OptionsStruct.h b/llvm/include/llvm/Option/OptionsStruct.h
new file mode 100644
index 00000000000000..39ce8bdcd23189
--- /dev/null
+++ b/llvm/include/llvm/Option/OptionsStruct.h
@@ -0,0 +1,166 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+//
+// Support for the options struct that -gen-opt-parser-defs generates from an
+// OptionsStruct def, and for a tool that parses its command line into one.
+// See "Declaring a Library's Options in TableGen" in llvm/docs/CommandLine.md.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OPTION_OPTIONSSTRUCT_H
+#define LLVM_OPTION_OPTIONSSTRUCT_H
+
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/BoolOrDefault.h"
+#include "llvm/ADT/STLFunctionalExtras.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Option/Arg.h"
+#include "llvm/Option/OptTable.h"
+#include "llvm/Option/Option.h"
+#include "llvm/Support/Allocator.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Support/StringSaver.h"
+#include <optional>
+#include <type_traits>
+
+namespace llvm {
+namespace opt {
+
+// Each accepts the spellings cl::opt accepts for the type.
+inline bool parseArgValue(StringRef S, bool &V) {
+ if (S == "true" || S == "1")
+ V = true;
+ else if (S == "false" || S == "0")
+ V = false;
+ else
+ return false;
+ return true;
+}
+
+inline bool parseArgValue(StringRef S, BoolOrDefault &V) {
+ bool B;
+ if (!parseArgValue(S, B))
+ return false;
+ V = B ? BoolOrDefault::True : BoolOrDefault::False;
+ return true;
+}
+
+inline bool parseArgValue(StringRef S, StringRef &V) {
+ V = S;
+ return true;
+}
+
+template <typename T>
+std::enable_if_t<std::is_arithmetic_v<T> && !std::is_same_v<T, bool>, bool>
+parseArgValue(StringRef S, T &V) {
+ if constexpr (std::is_floating_point_v<T>)
+ return to_float(S, V);
+ else
+ return to_integer(S, V);
+}
+
+// A std::optional member is set only when its option is given.
+template <typename T> bool parseArgValue(StringRef S, std::optional<T> &V) {
+ T X{};
+ if (!parseArgValue(S, X))
+ return false;
+ V = X;
+ return true;
+}
+
+// The generated apply() passes Alloc, which only a list member uses.
+template <typename T>
+bool parseArgValue(StringRef S, T &V, BumpPtrAllocator &) {
+ return parseArgValue(S, V);
+}
+
+// An enum member is set by Parse, the generated value-to-enumerator mapping.
+template <typename T, typename F>
+bool parseArgValue(StringRef S, T &V, BumpPtrAllocator &, F Parse) {
+ return Parse(S, V);
+}
+
+// Appends Elems to a list member, whose storage comes from Alloc, keeping the
+// options struct trivially destructible.
+template <typename T>
+void appendList(ArrayRef<T> &List, ArrayRef<T> Elems, BumpPtrAllocator &Alloc) {
+ static_assert(std::is_trivially_copyable_v<T>);
+ T *Storage = Alloc.Allocate<T>(List.size() + Elems.size());
+ llvm::copy(Elems, llvm::copy(List, Storage));
+ List = ArrayRef(Storage, List.size() + Elems.size());
+}
+
+// A ListField member appends the comma-separated values of each occurrence.
+template <typename T, typename F>
+bool parseArgValue(StringRef S, ArrayRef<T> &List, BumpPtrAllocator &Alloc,
+ F ParseElem) {
+ SmallVector<T, 4> Elems;
+ for (StringRef Item : split(S, ',')) {
+ T Elem{};
+ if (!ParseElem(Item, Elem))
+ return false;
+ Elems.push_back(Elem);
+ }
+ appendList(List, ArrayRef<T>(Elems), Alloc);
+ return true;
+}
+
+template <typename T>
+bool parseArgValue(StringRef S, ArrayRef<T> &List, BumpPtrAllocator &Alloc) {
+ return parseArgValue(S, List, Alloc, [](StringRef Item, T &Elem) {
+ return parseArgValue(Item, Elem);
+ });
+}
+
+// A RepeatedField member appends the whole value of each occurrence.
+template <typename T>
+bool appendArgValue(StringRef S, ArrayRef<T> &List, BumpPtrAllocator &Alloc) {
+ T Elem{};
+ if (!parseArgValue(S, Elem))
+ return false;
+ appendList(List, ArrayRef(Elem), Alloc);
+ return true;
+}
+
+/// An OptTable with a public constructor, shared by every options struct.
+class LLVM_ABI OptionsStructTable : public OptTable {
+public:
+ explicit OptionsStructTable(const Tables &T) : OptTable(T) {
+ setDashDashParsing(true);
+ }
+ ~OptionsStructTable() override;
+};
+
+/// Parses a tool's command line, expanding response files, with the options
+/// table \p T. \p Apply sets the member an option names. Positional
+/// arguments, and every argument after "--", are appended to \p Inputs.
+namespace detail {
+LLVM_ABI Error parseToolArgsImpl(const OptTable &T, int Argc,
+ const char *const *Argv, StringSaver &Saver,
+ function_ref<bool(const Arg &)> Apply,
+ SmallVectorImpl<StringRef> &Inputs);
+} // namespace detail
+
+/// Parses a tool's command line into options struct \p Opts, whose string
+/// members refer to \p Argv or \p Alloc.
+template <typename T>
+Error parseToolArgs(T &Opts, int Argc, const char *const *Argv,
+ BumpPtrAllocator &Alloc,
+ SmallVectorImpl<StringRef> &Inputs) {
+ StringSaver Saver(Alloc);
+ return detail::parseToolArgsImpl(
+ T::optTable(), Argc, Argv, Saver,
+ [&](const Arg &A) { return Opts.apply(A, Alloc); }, Inputs);
+}
+
+} // namespace opt
+} // namespace llvm
+
+#endif // LLVM_OPTION_OPTIONSSTRUCT_H
diff --git a/llvm/lib/Option/CMakeLists.txt b/llvm/lib/Option/CMakeLists.txt
index 3106bcfa3878a6..713e492d05cb13 100644
--- a/llvm/lib/Option/CMakeLists.txt
+++ b/llvm/lib/Option/CMakeLists.txt
@@ -2,6 +2,7 @@ add_llvm_component_library(LLVMOption
Arg.cpp
ArgList.cpp
LibraryOptions.cpp
+ OptionsStruct.cpp
Option.cpp
OptTable.cpp
diff --git a/llvm/lib/Option/LibraryOptions.cpp b/llvm/lib/Option/LibraryOptions.cpp
index c5e96503e459c3..85d68f8240a54f 100644
--- a/llvm/lib/Option/LibraryOptions.cpp
+++ b/llvm/lib/Option/LibraryOptions.cpp
@@ -15,8 +15,6 @@
using namespace llvm;
using namespace llvm::opt;
-LibraryOptTable::~LibraryOptTable() = default;
-
void LibraryOptionsParser::forEachOption(
function_ref<void(StringRef, StringRef, StringRef)> Fn) const {
const OptTable &T = Table();
diff --git a/llvm/lib/Option/OptionsStruct.cpp b/llvm/lib/Option/OptionsStruct.cpp
new file mode 100644
index 00000000000000..c3286eabe06ac8
--- /dev/null
+++ b/llvm/lib/Option/OptionsStruct.cpp
@@ -0,0 +1,41 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/Option/OptionsStruct.h"
+#include "llvm/Option/ArgList.h"
+
+using namespace llvm;
+using namespace llvm::opt;
+
+OptionsStructTable::~OptionsStructTable() = default;
+
+Error opt::detail::parseToolArgsImpl(const OptTable &T, int Argc,
+ const char *const *Argv,
+ StringSaver &Saver,
+ function_ref<bool(const Arg &)> Apply,
+ SmallVectorImpl<StringRef> &Inputs) {
+ unsigned Unknown = 1;
+ while (T.getOptionKind(Unknown) != Option::UnknownClass)
+ ++Unknown;
+ std::string Err;
+ InputArgList List = T.parseArgs(Argc, const_cast<char *const *>(Argv),
+ Unknown, Saver, [&](StringRef Msg) {
+ if (Err.empty())
+ Err = Msg;
+ });
+ if (!Err.empty())
+ return createStringError(Err);
+ for (const Arg *A : List) {
+ if (A->getOption().getKind() == Option::InputClass)
+ Inputs.push_back(A->getValue());
+ else if (!Apply(*A))
+ return createStringError("invalid value '" + Twine(A->getValue()) +
+ "' in '" + A->getAsString(List) + "'");
+ }
+ return Error::success();
+}
diff --git a/llvm/unittests/Option/LibraryOptionsTest.cpp b/llvm/unittests/Option/LibraryOptionsTest.cpp
index 90e3db8ec40cb1..2f03e468d296c6 100644
--- a/llvm/unittests/Option/LibraryOptionsTest.cpp
+++ b/llvm/unittests/Option/LibraryOptionsTest.cpp
@@ -88,6 +88,9 @@ TEST(LibraryOptionsTest, Apply) {
testing::Each(true));
EXPECT_THAT(O.modes, testing::ElementsAre(test::Mode::B, test::Mode::A,
test::Mode::B));
+ // A RepeatedField appends each whole value.
+ EXPECT_THAT(Apply({"-lib-arg=a,b", "-lib-arg", "c"}), testing::Each(true));
+ EXPECT_THAT(O.arg, testing::ElementsAre("a,b", "c"));
// A rejected value leaves the member unchanged.
EXPECT_THAT(
@@ -124,6 +127,7 @@ TEST(LibraryOptionsTest, Parser) {
});
EXPECT_THAT(Rows,
testing::ElementsAre(
+ "lib-arg|=<value>|A repeated string",
"lib-count|=<value>|An unsigned", "lib-disable||",
"lib-enable||A bool", "lib-in-build||Available",
"lib-limit|=<value>|An optional", "lib-list|=<value>|A list",
@@ -172,6 +176,26 @@ TEST(LibraryOptionsTest, Parser) {
"1 invalid value 'c' in '-lib-old-mode=c'");
}
+// A tool parses its whole command line into the struct.
+TEST(LibraryOptionsTest, ToolArgs) {
+ BumpPtrAllocator Alloc;
+ TestLibraryOptions O;
+ auto Parse = [&](std::vector<const char *> Argv) {
+ Argv.insert(Argv.begin(), "prog");
+ SmallVector<StringRef> Inputs;
+ std::string Err = toString(
+ opt::parseToolArgs(O, Argv.size(), Argv.data(), Alloc, Inputs));
+ return Err + "|" + join(Inputs, " ");
+ };
+ EXPECT_EQ(Parse({"a", "-lib-count", "5", "b", "--", "-lib-enable"}),
+ "|a b -lib-enable");
+ EXPECT_EQ(O.count, 5u);
+
+ EXPECT_EQ(Parse({"-lib-countt=1"}),
+ "unknown argument '-lib-countt=1', did you mean '-lib-count=1'?|");
+ EXPECT_EQ(Parse({"-lib-count=x"}), "invalid value 'x' in '-lib-count=x'|");
+}
+
// A static RegisterLibraryOptions connects the struct to
// cl::parseCommandLineOptions.
TEST(LibraryOptionsTest, Register) {
diff --git a/llvm/unittests/Option/LibraryOpts.td b/llvm/unittests/Option/LibraryOpts.td
index b0797074caca42..165ead33c2df3b 100644
--- a/llvm/unittests/Option/LibraryOpts.td
+++ b/llvm/unittests/Option/LibraryOpts.td
@@ -20,6 +20,7 @@ defm : BoolField<"lib-not-in-build", "false", "Unavailable">;
defm : ValueField<"lib-count", "unsigned", "3", "An unsigned">;
defm : OptionalValueField<"lib-limit", "unsigned", "An optional">;
defm : ListField<"lib-list", "unsigned", "A list">;
+defm : RepeatedField<"lib-arg", "StringRef", "A repeated string">;
defm : EnumField<"lib-mode", "test::Mode", "test::Mode::A", "a,b",
["test::Mode::A", "test::Mode::B"], "An enum">;
defm : EnumListField<"lib-modes", "test::Mode", "a,b",
diff --git a/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp b/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp
index a359f73398f24e..c1945efcad16ec 100644
--- a/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp
+++ b/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp
@@ -357,7 +357,8 @@ static void emitOptionsStruct(const Record &Struct,
OS << "namespace llvm {\nnamespace opt {\nclass Arg;\n";
OS << "class LibraryOptionsParser;\n";
OS << "class OptTable;\n} // namespace opt\n} // namespace llvm\n\n";
- OS << "namespace " << Namespace << " {\n";
+ // An empty namespace gives a tool's struct internal linkage.
+ OS << "namespace " << (Namespace.empty() ? "" : Namespace + " ") << "{\n";
OS << "struct " << Name << " {\n";
if (Namespace != "llvm")
OS << " using StringRef = llvm::StringRef;\n";
@@ -373,15 +374,19 @@ static void emitOptionsStruct(const Record &Struct,
OS << "\nprivate:\n friend class llvm::cl::LibraryOptionsContext;\n"
" friend class llvm::opt::LibraryOptionsParser;\n";
OS << "\n static const " << Name << " Default;\n";
- OS << "};\n} // namespace " << Namespace << "\n";
+ OS << "};\n} // namespace";
+ if (!Namespace.empty())
+ OS << " " << Namespace;
+ OS << "\n";
OS << "#endif // OPTIONS_STRUCT_DECL\n";
- std::string Qualified = (Namespace + "::" + Name).str();
+ std::string Qualified =
+ Namespace.empty() ? Name.str() : (Namespace + "::" + Name).str();
OS << "\n#ifdef OPTIONS_STRUCT_DEFS\n#undef OPTIONS_STRUCT_DEFS\n";
OS << "LLVM_REQUIRE_CONSTANT_INITIALIZATION const " << Qualified << " "
<< Qualified << "::Default;\n\n";
OS << "const llvm::opt::OptTable &" << Qualified << "::optTable() {\n";
- OS << " static const llvm::opt::LibraryOptTable T(optionTables());\n";
+ OS << " static const llvm::opt::OptionsStructTable T(optionTables());\n";
OS << " return T;\n}\n\n";
OS << "bool " << Qualified
<< "::apply(const llvm::opt::Arg &A, llvm::BumpPtrAllocator &Alloc) {\n";
@@ -416,7 +421,8 @@ static void emitOptionsStruct(const Record &Struct,
R->getValueAsDef("Kind")->getValueAsString("Name") == "FlagOrEq"
? "A.getNumValues() ? A.getValue() : \"true\""
: "A.getValue()";
- OS << " return llvm::opt::parseArgValue(" << Value << ", " << Member
+ StringRef Fn = R->getValue("Repeated") ? "appendArgValue" : "parseArgValue";
+ OS << " return llvm::opt::" << Fn << "(" << Value << ", " << Member
<< ", Alloc);\n";
}
OS << " }\n llvm_unreachable(\"option without a member\");\n}\n";
diff --git a/llvm/utils/gn/secondary/llvm/lib/Option/BUILD.gn b/llvm/utils/gn/secondary/llvm/lib/Option/BUILD.gn
index b193227d160e59..7b9fb0bc666f4e 100644
--- a/llvm/utils/gn/secondary/llvm/lib/Option/BUILD.gn
+++ b/llvm/utils/gn/secondary/llvm/lib/Option/BUILD.gn
@@ -6,6 +6,7 @@ static_library("Option") {
"ArgList.cpp",
"LibraryOptions.cpp",
"OptTable.cpp",
+ "OptionsStruct.cpp",
"Option.cpp",
]
}
>From 9b607b012400c2cd1ec82806aeab1690ae337d18 Mon Sep 17 00:00:00 2001
From: Fangrui Song <i at maskray.me>
Date: Sat, 28 Nov 2026 12:36:13 -0800
Subject: [PATCH 2/3] Store the unknown-option ID in OptionsStructTable and
make parseToolArgs its member; drop OptionsStruct.cpp
---
llvm/include/llvm/Option/LibraryOptions.h | 2 +-
llvm/include/llvm/Option/OptionsStruct.h | 31 +++++++-------
llvm/lib/Option/CMakeLists.txt | 1 -
llvm/lib/Option/LibraryOptions.cpp | 24 +++++++++++
llvm/lib/Option/OptionsStruct.cpp | 41 -------------------
.../TableGen/Basic/OptionParserEmitter.cpp | 11 +++--
.../gn/secondary/llvm/lib/Option/BUILD.gn | 1 -
7 files changed, 47 insertions(+), 64 deletions(-)
delete mode 100644 llvm/lib/Option/OptionsStruct.cpp
diff --git a/llvm/include/llvm/Option/LibraryOptions.h b/llvm/include/llvm/Option/LibraryOptions.h
index bbda8dea15703c..66068fb1b4d72b 100644
--- a/llvm/include/llvm/Option/LibraryOptions.h
+++ b/llvm/include/llvm/Option/LibraryOptions.h
@@ -48,7 +48,7 @@ class LLVM_ABI LibraryOptionsParser final : public cl::LibraryOptions {
}
private:
- const OptTable &(*Table)();
+ const OptionsStructTable &(*Table)();
const void *Default;
bool (*Apply)(void *Opts, const Arg &A, BumpPtrAllocator &Alloc);
void *(*Copy)(BumpPtrAllocator &Alloc);
diff --git a/llvm/include/llvm/Option/OptionsStruct.h b/llvm/include/llvm/Option/OptionsStruct.h
index 39ce8bdcd23189..043ae50b00b96a 100644
--- a/llvm/include/llvm/Option/OptionsStruct.h
+++ b/llvm/include/llvm/Option/OptionsStruct.h
@@ -129,35 +129,34 @@ bool appendArgValue(StringRef S, ArrayRef<T> &List, BumpPtrAllocator &Alloc) {
return true;
}
-/// An OptTable with a public constructor, shared by every options struct.
+/// The option table of an options struct.
class LLVM_ABI OptionsStructTable : public OptTable {
public:
- explicit OptionsStructTable(const Tables &T) : OptTable(T) {
+ OptionsStructTable(const Tables &T, unsigned UnknownID)
+ : OptTable(T), UnknownID(UnknownID) {
setDashDashParsing(true);
}
~OptionsStructTable() override;
+
+ Error parseToolArgs(int Argc, const char *const *Argv, StringSaver &Saver,
+ function_ref<bool(const Arg &)> Apply,
+ SmallVectorImpl<StringRef> &Inputs) const;
+
+private:
+ unsigned UnknownID;
};
-/// Parses a tool's command line, expanding response files, with the options
-/// table \p T. \p Apply sets the member an option names. Positional
+/// Parses a tool's command line, expanding response files, into options struct
+/// \p Opts, whose string members refer to \p Argv or \p Alloc. Positional
/// arguments, and every argument after "--", are appended to \p Inputs.
-namespace detail {
-LLVM_ABI Error parseToolArgsImpl(const OptTable &T, int Argc,
- const char *const *Argv, StringSaver &Saver,
- function_ref<bool(const Arg &)> Apply,
- SmallVectorImpl<StringRef> &Inputs);
-} // namespace detail
-
-/// Parses a tool's command line into options struct \p Opts, whose string
-/// members refer to \p Argv or \p Alloc.
template <typename T>
Error parseToolArgs(T &Opts, int Argc, const char *const *Argv,
BumpPtrAllocator &Alloc,
SmallVectorImpl<StringRef> &Inputs) {
StringSaver Saver(Alloc);
- return detail::parseToolArgsImpl(
- T::optTable(), Argc, Argv, Saver,
- [&](const Arg &A) { return Opts.apply(A, Alloc); }, Inputs);
+ return T::optTable().parseToolArgs(
+ Argc, Argv, Saver, [&](const Arg &A) { return Opts.apply(A, Alloc); },
+ Inputs);
}
} // namespace opt
diff --git a/llvm/lib/Option/CMakeLists.txt b/llvm/lib/Option/CMakeLists.txt
index 713e492d05cb13..3106bcfa3878a6 100644
--- a/llvm/lib/Option/CMakeLists.txt
+++ b/llvm/lib/Option/CMakeLists.txt
@@ -2,7 +2,6 @@ add_llvm_component_library(LLVMOption
Arg.cpp
ArgList.cpp
LibraryOptions.cpp
- OptionsStruct.cpp
Option.cpp
OptTable.cpp
diff --git a/llvm/lib/Option/LibraryOptions.cpp b/llvm/lib/Option/LibraryOptions.cpp
index 85d68f8240a54f..fe9db5cf5e8cf2 100644
--- a/llvm/lib/Option/LibraryOptions.cpp
+++ b/llvm/lib/Option/LibraryOptions.cpp
@@ -15,6 +15,30 @@
using namespace llvm;
using namespace llvm::opt;
+OptionsStructTable::~OptionsStructTable() = default;
+
+Error OptionsStructTable::parseToolArgs(
+ int Argc, const char *const *Argv, StringSaver &Saver,
+ function_ref<bool(const Arg &)> Apply,
+ SmallVectorImpl<StringRef> &Inputs) const {
+ std::string Err;
+ InputArgList List = parseArgs(Argc, const_cast<char *const *>(Argv),
+ UnknownID, Saver, [&](StringRef Msg) {
+ if (Err.empty())
+ Err = Msg;
+ });
+ if (!Err.empty())
+ return createStringError(Err);
+ for (const Arg *A : List) {
+ if (A->getOption().getKind() == Option::InputClass)
+ Inputs.push_back(A->getValue());
+ else if (!Apply(*A))
+ return createStringError("invalid value '" + Twine(A->getValue()) +
+ "' in '" + A->getAsString(List) + "'");
+ }
+ return Error::success();
+}
+
void LibraryOptionsParser::forEachOption(
function_ref<void(StringRef, StringRef, StringRef)> Fn) const {
const OptTable &T = Table();
diff --git a/llvm/lib/Option/OptionsStruct.cpp b/llvm/lib/Option/OptionsStruct.cpp
deleted file mode 100644
index c3286eabe06ac8..00000000000000
--- a/llvm/lib/Option/OptionsStruct.cpp
+++ /dev/null
@@ -1,41 +0,0 @@
-//===----------------------------------------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/Option/OptionsStruct.h"
-#include "llvm/Option/ArgList.h"
-
-using namespace llvm;
-using namespace llvm::opt;
-
-OptionsStructTable::~OptionsStructTable() = default;
-
-Error opt::detail::parseToolArgsImpl(const OptTable &T, int Argc,
- const char *const *Argv,
- StringSaver &Saver,
- function_ref<bool(const Arg &)> Apply,
- SmallVectorImpl<StringRef> &Inputs) {
- unsigned Unknown = 1;
- while (T.getOptionKind(Unknown) != Option::UnknownClass)
- ++Unknown;
- std::string Err;
- InputArgList List = T.parseArgs(Argc, const_cast<char *const *>(Argv),
- Unknown, Saver, [&](StringRef Msg) {
- if (Err.empty())
- Err = Msg;
- });
- if (!Err.empty())
- return createStringError(Err);
- for (const Arg *A : List) {
- if (A->getOption().getKind() == Option::InputClass)
- Inputs.push_back(A->getValue());
- else if (!Apply(*A))
- return createStringError("invalid value '" + Twine(A->getValue()) +
- "' in '" + A->getAsString(List) + "'");
- }
- return Error::success();
-}
diff --git a/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp b/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp
index c1945efcad16ec..7cd2da00eea138 100644
--- a/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp
+++ b/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp
@@ -356,7 +356,8 @@ static void emitOptionsStruct(const Record &Struct,
StringRef Namespace = Struct.getValueAsString("Namespace");
OS << "namespace llvm {\nnamespace opt {\nclass Arg;\n";
OS << "class LibraryOptionsParser;\n";
- OS << "class OptTable;\n} // namespace opt\n} // namespace llvm\n\n";
+ OS << "class OptionsStructTable;\n} // namespace opt\n} // namespace "
+ "llvm\n\n";
// An empty namespace gives a tool's struct internal linkage.
OS << "namespace " << (Namespace.empty() ? "" : Namespace + " ") << "{\n";
OS << "struct " << Name << " {\n";
@@ -366,7 +367,7 @@ static void emitOptionsStruct(const Record &Struct,
ConditionScope CS(OS, *R);
OS << " " << M.Type << " " << M.Name << "{" << M.Default << "};\n";
}
- OS << "\n static const llvm::opt::OptTable &optTable();\n";
+ OS << "\n static const llvm::opt::OptionsStructTable &optTable();\n";
OS << " /// Sets the member that \\p A names, allocating a list from \\p "
"Alloc.\n /// Returns false if the value is invalid.\n";
OS << " bool apply(const llvm::opt::Arg &A, llvm::BumpPtrAllocator "
@@ -385,8 +386,10 @@ static void emitOptionsStruct(const Record &Struct,
OS << "\n#ifdef OPTIONS_STRUCT_DEFS\n#undef OPTIONS_STRUCT_DEFS\n";
OS << "LLVM_REQUIRE_CONSTANT_INITIALIZATION const " << Qualified << " "
<< Qualified << "::Default;\n\n";
- OS << "const llvm::opt::OptTable &" << Qualified << "::optTable() {\n";
- OS << " static const llvm::opt::OptionsStructTable T(optionTables());\n";
+ OS << "const llvm::opt::OptionsStructTable &" << Qualified
+ << "::optTable() {\n";
+ OS << " static const llvm::opt::OptionsStructTable T(optionTables(), "
+ "OPT_UNKNOWN);\n";
OS << " return T;\n}\n\n";
OS << "bool " << Qualified
<< "::apply(const llvm::opt::Arg &A, llvm::BumpPtrAllocator &Alloc) {\n";
diff --git a/llvm/utils/gn/secondary/llvm/lib/Option/BUILD.gn b/llvm/utils/gn/secondary/llvm/lib/Option/BUILD.gn
index 7b9fb0bc666f4e..b193227d160e59 100644
--- a/llvm/utils/gn/secondary/llvm/lib/Option/BUILD.gn
+++ b/llvm/utils/gn/secondary/llvm/lib/Option/BUILD.gn
@@ -6,7 +6,6 @@ static_library("Option") {
"ArgList.cpp",
"LibraryOptions.cpp",
"OptTable.cpp",
- "OptionsStruct.cpp",
"Option.cpp",
]
}
>From ccd08a5075be5cb6cb71b3b6b569aeb09267a6b1 Mon Sep 17 00:00:00 2001
From: Fangrui Song <i at maskray.me>
Date: Sun, 29 Nov 2026 10:04:23 -0800
Subject: [PATCH 3/3] move OPTIONS_STRUCT_DECL
---
clang/tools/clang-diff/ClangDiff.cpp | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/clang/tools/clang-diff/ClangDiff.cpp b/clang/tools/clang-diff/ClangDiff.cpp
index 00701ee3c45ebf..cae63f49de238a 100644
--- a/clang/tools/clang-diff/ClangDiff.cpp
+++ b/clang/tools/clang-diff/ClangDiff.cpp
@@ -11,14 +11,12 @@
//
//===----------------------------------------------------------------------===//
-#define OPTIONS_STRUCT_DECL
-#include "Opts.inc"
-
#include "clang/Tooling/ASTDiff/ASTDiff.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Option/OptionsStruct.h"
+#define OPTIONS_STRUCT_DECL
#define OPTIONS_STRUCT_DEFS
#include "Opts.inc"
More information about the cfe-commits
mailing list