[llvm] [Option] Add OptionalValueField, OptionalEnumField, and list fields (PR #230812)

Fangrui Song via llvm-commits llvm-commits at lists.llvm.org
Sat Oct 10 10:19:59 PDT 2026


https://github.com/MaskRay updated https://github.com/llvm/llvm-project/pull/230812

>From 7ca3852f5973fb6c67f5a9185cb9d0902b7be704 Mon Sep 17 00:00:00 2001
From: Fangrui Song <i at maskray.me>
Date: Sat, 10 Oct 2026 09:26:34 -0700
Subject: [PATCH 1/2] [Option] Add OptionalValueField, OptionalEnumField, and
 list fields

OptionalValueField and OptionalEnumField declare a std::optional member,
std::nullopt if unspecified.

ListField declares an ArrayRef member replacing a cl::list with
cl::CommaSeparated: each occurrence appends its comma-separated values,
keeping the struct trivially destructible. The elements in a static
BumpPtrAllocator for now. EnumListField maps the values to enumerators
as EnumField does.

Aided by Opus 5.5
---
 llvm/docs/CommandLine.md                      |  5 +-
 llvm/include/llvm/Option/LibraryOptions.h     | 37 +++++++++++++
 llvm/include/llvm/Option/LibraryOptions.td    | 26 +++++++++
 llvm/lib/Option/LibraryOptions.cpp            |  7 +++
 .../lib/Transforms/Scalar/LoopInterchange.cpp | 55 +++++++------------
 llvm/lib/Transforms/Scalar/ScalarOptions.h    |  6 ++
 llvm/lib/Transforms/Scalar/ScalarOptions.td   | 42 +++++++-------
 llvm/unittests/Option/LibraryOptionsTest.cpp  | 26 +++++++--
 llvm/unittests/Option/LibraryOpts.td          |  6 +-
 .../TableGen/Basic/OptionParserEmitter.cpp    | 12 ++--
 10 files changed, 156 insertions(+), 66 deletions(-)

diff --git a/llvm/docs/CommandLine.md b/llvm/docs/CommandLine.md
index 5e3941881f993..51a6528b62e81 100644
--- a/llvm/docs/CommandLine.md
+++ b/llvm/docs/CommandLine.md
@@ -1586,15 +1586,18 @@ A member is named after its option, `enable_foo` for `-enable-foo`; a named `def
 
 The `BoolField` is set by `-enable-foo` or `-enable-foo=true|false|1|0`.
 A `ValueField`, of an integer type, `float`, `double`, or `StringRef`, is set by `-foo-threshold=8` or `-foo-threshold 8`.
+A `ListField<"foo-ids", "unsigned", ...>` is an `ArrayRef<unsigned>`, replacing a `cl::list` with `cl::CommaSeparated`: each `-foo-ids=1,2` or `-foo-ids 1,2` appends its values.
+A reader applies a `cl::list_init` default to an empty list, since a given option never leaves it empty.
 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 `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 `-`.
 Only `-help-hidden` lists the options, like `cl::Hidden`.
 
 A default is the member's C++ initializer, so `"\"-\""` initializes `foo_path` to `"-"`.
-A `std::optional` member defaulting to `std::nullopt` tells whether the option was given, which a `cl::opt` asks with `getNumOccurrences()`.
+An `OptionalValueField` or `OptionalEnumField` takes no default; its `std::optional` member stays `std::nullopt` unless the option is given, replacing `getNumOccurrences()`.
 The header declares the struct after including what the member defaults need, and one source file defines it and registers it with `cl::`.
 
 The library then lists `FooOptionsTableGen` under `DEPENDS` and `Option` under `LINK_COMPONENTS`.
diff --git a/llvm/include/llvm/Option/LibraryOptions.h b/llvm/include/llvm/Option/LibraryOptions.h
index 5164267b21611..be0fce2ead305 100644
--- a/llvm/include/llvm/Option/LibraryOptions.h
+++ b/llvm/include/llvm/Option/LibraryOptions.h
@@ -15,7 +15,9 @@
 #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"
@@ -70,6 +72,39 @@ template <typename T> bool parseArgValue(StringRef S, std::optional<T> &V) {
   return true;
 }
 
+// An enum member is set by Parse, the generated value-to-enumerator mapping.
+template <typename T, typename F>
+bool parseArgValue(StringRef S, T &V, F Parse) {
+  return Parse(S, V);
+}
+
+// Allocates storage that lives until the process exits.
+LLVM_ABI void *allocateListStorage(size_t Size, size_t Alignment);
+
+// A list member appends the comma-separated values of each occurrence. It is
+// an ArrayRef so that an options struct stays trivially destructible.
+template <typename T, typename F>
+bool parseArgValue(StringRef S, ArrayRef<T> &V, F Parse) {
+  static_assert(std::is_trivially_copyable_v<T>);
+  SmallVector<T, 4> L(V.begin(), V.end());
+  for (StringRef Part : split(S, ',')) {
+    T X{};
+    if (!Parse(Part, X))
+      return false;
+    L.push_back(X);
+  }
+  T *P =
+      static_cast<T *>(allocateListStorage(L.size() * sizeof(T), alignof(T)));
+  llvm::copy(L, P);
+  V = ArrayRef(P, L.size());
+  return true;
+}
+
+template <typename T> bool parseArgValue(StringRef S, ArrayRef<T> &V) {
+  return parseArgValue(S, V,
+                       [](StringRef S, T &X) { return parseArgValue(S, X); });
+}
+
 /// An OptTable with a public constructor, shared by every options struct.
 class LLVM_ABI LibraryOptTable : public OptTable {
 public:
@@ -100,6 +135,8 @@ class LLVM_ABI LibraryOptionsParser final : public cl::LibraryOptions {
 /// defines one static instance in the file that includes the struct's
 /// definitions.
 template <typename T> class RegisterLibraryOptions {
+  static_assert(std::is_trivially_destructible_v<T>,
+                "an options struct must not need an exit-time destructor");
   LibraryOptionsParser Parser{T::optTable,
                               [](const Arg &A) { return T::Global.apply(A); },
                               [] { T::Global = T(); }};
diff --git a/llvm/include/llvm/Option/LibraryOptions.td b/llvm/include/llvm/Option/LibraryOptions.td
index 54e0b540152a7..60dcb23166928 100644
--- a/llvm/include/llvm/Option/LibraryOptions.td
+++ b/llvm/include/llvm/Option/LibraryOptions.td
@@ -61,6 +61,13 @@ multiclass EnumField<string name, string type, code default, string values,
     EnumValues<values, enumerators>, HelpText<help>;
 }
 
+// An EnumField whose std::optional<<type>> member defaults to std::nullopt.
+multiclass OptionalEnumField<string name, string type, string values,
+                             list<code> enumerators, string help> {
+  defm NAME : EnumField<name, "std::optional<"#type#">", "", values,
+    enumerators, help>;
+}
+
 // An EnumField that -<name> alone sets to <bare>; <default> applies when the
 // option is absent. -<name> doesn't consume the next argument.
 multiclass FlagOrEnumField<string name, string type, code default,
@@ -84,3 +91,22 @@ multiclass ValueField<string name, string type, code default, string help> {
   def NAME : SeparateOrEq<["-", "--"], name>, Field<NAME, type, default>,
     HelpText<help>;
 }
+
+// A ValueField whose std::optional<<type>> member defaults to std::nullopt.
+multiclass OptionalValueField<string name, string type, string help> {
+  defm NAME : ValueField<name, "std::optional<"#type#">", "", help>;
+}
+
+// An llvm::ArrayRef<<type>> member. Each -<name>=<values> or -<name> <values>
+// appends its comma-separated values.
+multiclass ListField<string name, string type, string help> {
+  def NAME : SeparateOrEq<["-", "--"], name>,
+    Field<NAME, "llvm::ArrayRef<"#type#">", "">, HelpText<help>;
+}
+
+// A ListField of the enumeration <type>, with <values> mapping to <enumerators>
+// as in EnumField.
+multiclass EnumListField<string name, string type, string values,
+                         list<code> enumerators, string help> {
+  defm NAME : ListField<name, type, help>, EnumValues<values, enumerators>;
+}
diff --git a/llvm/lib/Option/LibraryOptions.cpp b/llvm/lib/Option/LibraryOptions.cpp
index 6bba23a66262f..c3b3bd01f96db 100644
--- a/llvm/lib/Option/LibraryOptions.cpp
+++ b/llvm/lib/Option/LibraryOptions.cpp
@@ -10,6 +10,7 @@
 #include "llvm/Option/ArgList.h"
 #include "llvm/Option/OptTable.h"
 #include "llvm/Option/Option.h"
+#include "llvm/Support/Allocator.h"
 #include "llvm/Support/Error.h"
 
 using namespace llvm;
@@ -17,6 +18,12 @@ using namespace llvm::opt;
 
 LibraryOptTable::~LibraryOptTable() = default;
 
+void *llvm::opt::allocateListStorage(size_t Size, size_t Alignment) {
+  // Never destroyed: list members refer to it until exit.
+  static BumpPtrAllocator &Alloc = *new BumpPtrAllocator;
+  return Alloc.Allocate(Size, Align(Alignment));
+}
+
 void LibraryOptionsParser::forEachOption(
     function_ref<void(StringRef, StringRef, StringRef)> Fn) const {
   const OptTable &T = Table();
diff --git a/llvm/lib/Transforms/Scalar/LoopInterchange.cpp b/llvm/lib/Transforms/Scalar/LoopInterchange.cpp
index fc2830be032f3..53196b5b579e1 100644
--- a/llvm/lib/Transforms/Scalar/LoopInterchange.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopInterchange.cpp
@@ -40,7 +40,6 @@
 #include "llvm/IR/Value.h"
 #include "llvm/IR/Verifier.h"
 #include "llvm/Support/Casting.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
@@ -73,41 +72,19 @@ using LoopVector = SmallVector<Loop *, 8>;
 // TODO: Check if we can use a sparse matrix here.
 using CharMatrix = std::vector<std::vector<char>>;
 
-/// Types of rules used in profitability check.
-enum class RuleTy {
-  PerLoopCacheAnalysis,
-  PerInstrOrderCost,
-  ForVectorization,
-  Ignore
-};
-
 } // end anonymous namespace
 
-// We prefer cache cost to vectorization by default.
-static cl::list<RuleTy> Profitabilities(
-    "loop-interchange-profitabilities", cl::MiscFlags::CommaSeparated,
-    cl::Hidden,
-    cl::desc("List of profitability heuristics to be used. They are applied in "
-             "the given order"),
-    cl::list_init<RuleTy>({RuleTy::PerInstrOrderCost,
-                           RuleTy::ForVectorization}),
-    cl::values(clEnumValN(RuleTy::PerLoopCacheAnalysis, "cache",
-                          "Prioritize loop cache cost"),
-               clEnumValN(RuleTy::PerInstrOrderCost, "instorder",
-                          "Prioritize the IVs order of each instruction"),
-               clEnumValN(RuleTy::ForVectorization, "vectorize",
-                          "Prioritize vectorization"),
-               clEnumValN(RuleTy::Ignore, "ignore",
-                          "Ignore profitability, force interchange (does not "
-                          "work with other options)")));
+constexpr LoopInterchangeRule DefaultProfitabilities[] = {
+    LoopInterchangeRule::PerInstrOrderCost,
+    LoopInterchangeRule::ForVectorization};
 
 #ifndef NDEBUG
-static bool noDuplicateRulesAndIgnore(ArrayRef<RuleTy> Rules) {
-  SmallSet<RuleTy, 4> Set;
-  for (RuleTy Rule : Rules) {
+static bool noDuplicateRulesAndIgnore(ArrayRef<LoopInterchangeRule> Rules) {
+  SmallSet<LoopInterchangeRule, 4> Set;
+  for (LoopInterchangeRule Rule : Rules) {
     if (!Set.insert(Rule).second)
       return false;
-    if (Rule == RuleTy::Ignore)
+    if (Rule == LoopInterchangeRule::Ignore)
       return false;
   }
   return true;
@@ -2016,8 +1993,14 @@ bool LoopInterchangeProfitability::isProfitable(
     return false;
   }
 
+  ArrayRef<LoopInterchangeRule> Profitabilities =
+      Opts.loop_interchange_profitabilities;
+  if (Profitabilities.empty())
+    Profitabilities = DefaultProfitabilities;
+
   // Return true if interchange is forced and the cost-model ignored.
-  if (Profitabilities.size() == 1 && Profitabilities[0] == RuleTy::Ignore)
+  if (Profitabilities.size() == 1 &&
+      Profitabilities[0] == LoopInterchangeRule::Ignore)
     return true;
   assert(noDuplicateRulesAndIgnore(Profitabilities) &&
          "Duplicate rules and option 'ignore' are not allowed");
@@ -2031,22 +2014,22 @@ bool LoopInterchangeProfitability::isProfitable(
   // Likewise, if it failed to analysis the profitability then only, the last
   // rule (isProfitableForVectorization by default) will decide.
   std::optional<bool> shouldInterchange;
-  for (RuleTy RT : Profitabilities) {
+  for (LoopInterchangeRule RT : Profitabilities) {
     switch (RT) {
-    case RuleTy::PerLoopCacheAnalysis: {
+    case LoopInterchangeRule::PerLoopCacheAnalysis: {
       CacheCost *CC = CCM.getCacheCost();
       const DenseMap<const Loop *, unsigned> &CostMap = CCM.getCostMap();
       shouldInterchange = isProfitablePerLoopCacheAnalysis(CostMap, CC);
       break;
     }
-    case RuleTy::PerInstrOrderCost:
+    case LoopInterchangeRule::PerInstrOrderCost:
       shouldInterchange = isProfitablePerInstrOrderCost();
       break;
-    case RuleTy::ForVectorization:
+    case LoopInterchangeRule::ForVectorization:
       shouldInterchange =
           isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix);
       break;
-    case RuleTy::Ignore:
+    case LoopInterchangeRule::Ignore:
       llvm_unreachable("Option 'ignore' is not supported with other options");
       break;
     }
diff --git a/llvm/lib/Transforms/Scalar/ScalarOptions.h b/llvm/lib/Transforms/Scalar/ScalarOptions.h
index e62cff397c9b1..61c02184650cc 100644
--- a/llvm/lib/Transforms/Scalar/ScalarOptions.h
+++ b/llvm/lib/Transforms/Scalar/ScalarOptions.h
@@ -16,6 +16,12 @@
 
 namespace llvm {
 enum class CRCStrategyKind { Disable, Auto, Table, Clmul };
+enum class LoopInterchangeRule {
+  PerLoopCacheAnalysis,
+  PerInstrOrderCost,
+  ForVectorization,
+  Ignore
+};
 enum class MatrixLayoutTy { ColumnMajor, RowMajor };
 } // namespace llvm
 
diff --git a/llvm/lib/Transforms/Scalar/ScalarOptions.td b/llvm/lib/Transforms/Scalar/ScalarOptions.td
index 6d1718ed68409..1d6275cac7afc 100644
--- a/llvm/lib/Transforms/Scalar/ScalarOptions.td
+++ b/llvm/lib/Transforms/Scalar/ScalarOptions.td
@@ -97,11 +97,11 @@ defm : ValueField<"earlycse-mssa-optimization-cap", "unsigned", "500",
   "Enable imprecision in EarlyCSE in pathological cases, in exchange for faster compile. Caps the MemorySSA clobbering calls">;
 
 // ExpandMemCmp.cpp
-defm : ValueField<"max-loads-per-memcmp", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"max-loads-per-memcmp", "unsigned",
   "Set maximum number of loads used in expanded memcmp">;
-defm : ValueField<"max-loads-per-memcmp-opt-size", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"max-loads-per-memcmp-opt-size", "unsigned",
   "Set maximum number of loads used in expanded memcmp for -Os/Oz">;
-defm : ValueField<"memcmp-num-loads-per-block", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"memcmp-num-loads-per-block", "unsigned",
   "The number of loads per basic block for inline expansion of memcmp">;
 
 // Float2Int.cpp
@@ -189,7 +189,7 @@ defm : ValueField<"jump-threading-implication-search-threshold", "unsigned", "3"
   "The number of predecessors to search for a stronger condition to use to thread over a weaker condition">;
 defm : ValueField<"jump-threading-phi-threshold", "unsigned", "76",
   "Max PHIs in BB to duplicate for jump threading">;
-defm : ValueField<"jump-threading-threshold", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"jump-threading-threshold", "unsigned",
   "Max block size to duplicate for jump threading">;
 
 // LICM.cpp
@@ -223,11 +223,11 @@ defm : ValueField<"licm-mssa-optimization-cap", "unsigned", "100",
 // the allocatable register set).
 defm : OptionalBoolField<"loop-prefetch-writes",
   "Prefetch write addresses">;
-defm : ValueField<"max-prefetch-iters-ahead", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"max-prefetch-iters-ahead", "unsigned",
   "Max number of iterations to prefetch ahead">;
-defm : ValueField<"min-prefetch-stride", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"min-prefetch-stride", "unsigned",
   "Min stride to add prefetches">;
-defm : ValueField<"prefetch-distance", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"prefetch-distance", "unsigned",
   "Number of instructions to prefetch ahead">;
 
 // LoopDeletion.cpp
@@ -279,6 +279,10 @@ defm : ValueField<"loop-interchange-max-mem-instr-ratio", "unsigned", "4",
 // Minimum loop depth supported.
 defm : ValueField<"loop-interchange-min-loop-nest-depth", "unsigned", "2",
   "Minimum depth of loop nest considered for the transform">;
+defm : EnumListField<"loop-interchange-profitabilities", "LoopInterchangeRule",
+  "cache,instorder,vectorize,ignore",
+  ["LoopInterchangeRule::PerLoopCacheAnalysis", "LoopInterchangeRule::PerInstrOrderCost", "LoopInterchangeRule::ForVectorization", "LoopInterchangeRule::Ignore"],
+  "List of profitability heuristics to be used. They are applied in the given order">;
 // Support for the inner-loop reduction pattern.
 defm : BoolField<"loop-interchange-reduction-to-mem", "false",
   "Support for the inner-loop reduction pattern">;
@@ -350,7 +354,7 @@ defm : BoolField<"lsr-filter-same-scaled-reg", "true",
 // The flag adds instruction count to solutions cost comparison.
 defm : OptionalBoolField<"lsr-insns-cost",
   "Add instruction count to a LSR cost model">;
-defm : EnumField<"lsr-preferred-addressing-mode", "std::optional<TargetTransformInfo::AddressingModeKind>", "std::nullopt",
+defm : OptionalEnumField<"lsr-preferred-addressing-mode", "TargetTransformInfo::AddressingModeKind",
   "none,preindexed,postindexed,all",
   ["TargetTransformInfo::AMK_None", "TargetTransformInfo::AMK_PreIndexed", "TargetTransformInfo::AMK_PostIndexed", "TargetTransformInfo::AMK_All"],
   "A flag that overrides the target's preferred addressing mode">;
@@ -362,9 +366,9 @@ defm : OptionalBoolField<"allow-unroll-and-jam",
   "Allows loops to be unroll-and-jammed">;
 defm : ValueField<"pragma-unroll-and-jam-threshold", "unsigned", "1024",
   "Unrolled size limit for loops with an unroll_and_jam(full) or unroll_count pragma">;
-defm : ValueField<"unroll-and-jam-count", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"unroll-and-jam-count", "unsigned",
   "Use this unroll count for all loops including those with unroll_and_jam_count pragma values, for testing purposes">;
-defm : ValueField<"unroll-and-jam-threshold", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"unroll-and-jam-threshold", "unsigned",
   "Threshold to use for inner loop when doing unroll and jam">;
 
 // LoopUnrollPass.cpp
@@ -380,21 +384,21 @@ defm : OptionalBoolField<"unroll-allow-partial",
   "Allows loops to be partially unrolled until -unroll-threshold loop size is reached">;
 defm : OptionalBoolField<"unroll-allow-remainder",
   "Allow generation of a loop remainder (extra iterations) when unrolling a loop">;
-defm : ValueField<"unroll-count", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"unroll-count", "unsigned",
   "Use this unroll count for all loops including those with unroll_count pragma values, for testing purposes">;
-defm : ValueField<"unroll-full-max-count", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"unroll-full-max-count", "unsigned",
   "Set the max unroll count for full unrolling, for testing purposes">;
-defm : ValueField<"unroll-max-count", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"unroll-max-count", "unsigned",
   "Set the max unroll count for partial and runtime unrolling, fortesting purposes">;
-defm : ValueField<"unroll-max-iteration-count-to-analyze", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"unroll-max-iteration-count-to-analyze", "unsigned",
   "Don't allow loop unrolling to simulate more than this number of iterations when checking full unroll profitability">;
-defm : ValueField<"unroll-max-percent-threshold-boost", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"unroll-max-percent-threshold-boost", "unsigned",
   "The maximum 'boost' (represented as a percentage >= 100) applied to the threshold when aggressively unrolling a loop due to the dynamic cost savings. If completely unrolling a loop will reduce the total runtime from X to Y, we boost the loop unroll threshold to DefaultThreshold*std::min(MaxPercentThresholdBoost, X/Y). This limit avoids excessive code bloat">;
-defm : ValueField<"unroll-max-upperbound", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"unroll-max-upperbound", "unsigned",
   "The max of trip count upper bound that is considered in unrolling">;
 defm : ValueField<"unroll-optsize-threshold", "unsigned", "0",
   "The cost threshold for loop unrolling when optimizing for size">;
-defm : ValueField<"unroll-partial-threshold", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"unroll-partial-threshold", "unsigned",
   "The cost threshold for partial loop unrolling">;
 defm : OptionalBoolField<"unroll-remainder",
   "Allow the loop remainder to be unrolled">;
@@ -404,7 +408,7 @@ defm : BoolField<"unroll-revisit-child-loops", "false",
   "Enqueue and re-visit child loops in the loop PM after unrolling. This shouldn't typically be needed as child loops (or their clones) were already visited">;
 defm : OptionalBoolField<"unroll-runtime",
   "Unroll loops with run-time trip counts">;
-defm : ValueField<"unroll-threshold", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"unroll-threshold", "unsigned",
   "The cost threshold for loop unrolling">;
 defm : ValueField<"unroll-threshold-aggressive", "unsigned", "300",
   "Threshold (max size of unrolled loop) to use in aggressive (O3) optimizations">;
@@ -528,7 +532,7 @@ defm : ValueField<"unswitch-threshold", "int", "50",
   "The cost threshold for unswitching a loop">;
 
 // SimplifyCFGPass.cpp
-defm : ValueField<"bonus-inst-threshold", "std::optional<unsigned>", "std::nullopt",
+defm : OptionalValueField<"bonus-inst-threshold", "unsigned",
   "Control the number of bonus instructions">;
 defm : OptionalBoolField<"forward-switch-cond",
   "Forward switch condition to phi ops">;
diff --git a/llvm/unittests/Option/LibraryOptionsTest.cpp b/llvm/unittests/Option/LibraryOptionsTest.cpp
index 46d638fa58309..026ff36426d84 100644
--- a/llvm/unittests/Option/LibraryOptionsTest.cpp
+++ b/llvm/unittests/Option/LibraryOptionsTest.cpp
@@ -34,7 +34,9 @@ TEST(LibraryOptionsTest, Apply) {
   EXPECT_FALSE(O.enable);
   EXPECT_EQ(O.count, 3u);
   EXPECT_EQ(O.limit, std::nullopt);
+  EXPECT_THAT(O.list, testing::IsEmpty());
   EXPECT_EQ(O.mode, test::Mode::A);
+  EXPECT_THAT(O.modes, testing::IsEmpty());
   EXPECT_EQ(O.override, BoolOrDefault::Default);
   EXPECT_EQ(O.print, std::nullopt);
   EXPECT_EQ(O.ratio, 0.5);
@@ -77,15 +79,27 @@ TEST(LibraryOptionsTest, Apply) {
   EXPECT_THAT(Apply({"-lib-print"}), testing::Each(true));
   EXPECT_EQ(O.print, test::Mode::B);
 
+  // Each occurrence of a list appends its comma-separated values.
+  EXPECT_THAT(Apply({"-lib-list=1,2", "-lib-list", "3"}), testing::Each(true));
+  EXPECT_THAT(O.list, testing::ElementsAre(1u, 2u, 3u));
+  EXPECT_THAT(Apply({"-lib-modes=b,a", "-lib-modes", "b"}),
+              testing::Each(true));
+  EXPECT_THAT(O.modes, testing::ElementsAre(test::Mode::B, test::Mode::A,
+                                            test::Mode::B));
+
   // A rejected value leaves the member unchanged.
   EXPECT_THAT(
-      Apply({"-lib-enable=2", "-lib-count=-1", "-lib-limit=x", "-lib-mode=c",
-             "-lib-override=y", "-lib-print=c", "-lib-ratio=y"}),
+      Apply({"-lib-enable=2", "-lib-count=-1", "-lib-limit=x", "-lib-list=4,x",
+             "-lib-list=", "-lib-mode=c", "-lib-modes=a,c", "-lib-override=y",
+             "-lib-print=c", "-lib-ratio=y"}),
       testing::Each(false));
   EXPECT_TRUE(O.enable);
   EXPECT_EQ(O.count, 7u);
   EXPECT_EQ(O.limit, 0u);
+  EXPECT_THAT(O.list, testing::ElementsAre(1u, 2u, 3u));
   EXPECT_EQ(O.mode, test::Mode::B);
+  EXPECT_THAT(O.modes, testing::ElementsAre(test::Mode::B, test::Mode::A,
+                                            test::Mode::B));
   EXPECT_EQ(O.override, BoolOrDefault::False);
   EXPECT_EQ(O.print, test::Mode::B);
   EXPECT_EQ(O.ratio, 0.25);
@@ -113,7 +127,8 @@ TEST(LibraryOptionsTest, Parser) {
       Rows,
       testing::ElementsAre(
           "lib-count|=<value>|An unsigned", "lib-enable||A bool",
-          "lib-limit|=<value>|An optional", "lib-mode|=<a|b>|An enum",
+          "lib-limit|=<value>|An optional", "lib-list|=<value>|A list",
+          "lib-modes|=<a|b>|An enum list", "lib-mode|=<a|b>|An enum",
           "lib-override||An optional bool", "lib-path|=<value>|A string",
           "lib-print|[=<a|b>]|A flag or enum", "lib-ratio|=<value>|A double",
           "lib-tristate|=<Default|Enable|Disable>|A tri-state"));
@@ -146,10 +161,12 @@ TEST(LibraryOptionsTest, Register) {
   opt::RegisterLibraryOptions<TestLibraryOptions> Registration;
   const TestLibraryOptions &G = TestLibraryOptions::Global;
   std::string Path = "-lib-path=q";
-  const char *Args[] = {"prog", "-lib-count", "5", "-lib-enable", Path.c_str()};
+  const char *Args[] = {"prog",        "-lib-count", "5",
+                        "-lib-enable", Path.c_str(), "-lib-list=1,2"};
   EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(Args), Args, "", &nulls()));
   EXPECT_EQ(G.count, 5u);
   EXPECT_TRUE(G.enable);
+  EXPECT_THAT(G.list, testing::ElementsAre(1u, 2u));
   // A StringRef member does not refer to the caller's argument.
   Path.assign(Path.size(), 'x');
   EXPECT_EQ(G.Path, "q");
@@ -157,6 +174,7 @@ TEST(LibraryOptionsTest, Register) {
   EXPECT_EQ(G.count, 3u);
   EXPECT_FALSE(G.enable);
   EXPECT_EQ(G.Path, "p");
+  EXPECT_THAT(G.list, testing::IsEmpty());
   cl::ResetCommandLineParser();
 }
 
diff --git a/llvm/unittests/Option/LibraryOpts.td b/llvm/unittests/Option/LibraryOpts.td
index 5fabf7718cfc5..e39ca46a684e4 100644
--- a/llvm/unittests/Option/LibraryOpts.td
+++ b/llvm/unittests/Option/LibraryOpts.td
@@ -12,10 +12,12 @@ def TestLibraryOptions : OptionsStruct<"test", prefix = "lib-">;
 
 defm : BoolField<"lib-enable", "false", "A bool">;
 defm : ValueField<"lib-count", "unsigned", "3", "An unsigned">;
-defm : ValueField<"lib-limit", "std::optional<unsigned>", "std::nullopt",
-  "An optional">;
+defm : OptionalValueField<"lib-limit", "unsigned", "An optional">;
+defm : ListField<"lib-list", "unsigned", "A list">;
 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",
+  ["test::Mode::A", "test::Mode::B"], "An enum list">;
 defm : OptionalBoolField<"lib-override", "An optional bool">;
 defm : FlagOrEnumField<"lib-print", "std::optional<test::Mode>", "std::nullopt",
   "a,b", ["test::Mode::A", "test::Mode::B"], "test::Mode::B",
diff --git a/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp b/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp
index 23b73ee3d9f2f..c972013bc9015 100644
--- a/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp
+++ b/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp
@@ -308,6 +308,7 @@ static void emitOptionsStruct(const Record &Struct,
 
   StringRef Name = Struct.getName();
   OS << "\n#ifdef OPTIONS_STRUCT_DECL\n#undef OPTIONS_STRUCT_DECL\n";
+  OS << "#include \"llvm/ADT/ArrayRef.h\"\n";
   OS << "#include \"llvm/ADT/BoolOrDefault.h\"\n";
   OS << "#include \"llvm/ADT/StringRef.h\"\n\n";
   StringRef Namespace = Struct.getValueAsString("Namespace");
@@ -356,11 +357,14 @@ static void emitOptionsStruct(const Record &Struct,
       if (Values.size() != Enumerators.size())
         PrintFatalError(R->getLoc(), "an EnumField needs one enumerator per "
                                      "value");
-      OS << "    {\n      llvm::StringRef V = A.getValue();\n";
+      // The generic lambda sets a scalar, a std::optional, or a list element.
+      OS << "    return llvm::opt::parseArgValue(A.getValue(), " << Member
+         << ", [](llvm::StringRef V, auto &X) {\n";
       for (auto [Value, Enumerator] : llvm::zip_equal(Values, Enumerators))
-        OS << "      if (V == \"" << Value << "\") {\n        " << Member
-           << " = " << Enumerator << ";\n        return true;\n      }\n";
-      OS << "      return false;\n    }\n";
+        OS << "      if (V == \"" << Value
+           << "\") {\n        X = " << Enumerator
+           << ";\n        return true;\n      }\n";
+      OS << "      return false;\n    });\n";
       continue;
     }
     // A FlagOrEq without a value means =true.

>From b21aa008a367bf7512179288c8ed25f57797a459 Mon Sep 17 00:00:00 2001
From: Fangrui Song <i at maskray.me>
Date: Sat, 10 Oct 2026 10:19:48 -0700
Subject: [PATCH 2/2] Save ListField members in bump allocator

---
 llvm/include/llvm/Option/LibraryOptions.h     | 36 +++++++++++--------
 llvm/include/llvm/Support/CommandLine.h       |  6 ++--
 llvm/lib/Option/LibraryOptions.cpp            | 11 ++----
 llvm/lib/Support/CommandLine.cpp              |  7 ++--
 llvm/unittests/Option/LibraryOptionsTest.cpp  | 16 +++++++--
 llvm/unittests/Support/CommandLineTest.cpp    |  3 +-
 .../TableGen/Basic/OptionParserEmitter.cpp    | 17 +++++----
 7 files changed, 57 insertions(+), 39 deletions(-)

diff --git a/llvm/include/llvm/Option/LibraryOptions.h b/llvm/include/llvm/Option/LibraryOptions.h
index be0fce2ead305..de257216d2e40 100644
--- a/llvm/include/llvm/Option/LibraryOptions.h
+++ b/llvm/include/llvm/Option/LibraryOptions.h
@@ -22,6 +22,7 @@
 #include "llvm/Option/Arg.h"
 #include "llvm/Option/OptTable.h"
 #include "llvm/Option/Option.h"
+#include "llvm/Support/Allocator.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Compiler.h"
 #include <optional>
@@ -72,19 +73,23 @@ template <typename T> bool parseArgValue(StringRef S, std::optional<T> &V) {
   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, F Parse) {
+bool parseArgValue(StringRef S, T &V, BumpPtrAllocator &, F Parse) {
   return Parse(S, V);
 }
 
-// Allocates storage that lives until the process exits.
-LLVM_ABI void *allocateListStorage(size_t Size, size_t Alignment);
-
-// A list member appends the comma-separated values of each occurrence. It is
-// an ArrayRef so that an options struct stays trivially destructible.
+// 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> &V, F Parse) {
+bool parseArgValue(StringRef S, ArrayRef<T> &V, BumpPtrAllocator &Alloc,
+                   F Parse) {
   static_assert(std::is_trivially_copyable_v<T>);
   SmallVector<T, 4> L(V.begin(), V.end());
   for (StringRef Part : split(S, ',')) {
@@ -93,15 +98,15 @@ bool parseArgValue(StringRef S, ArrayRef<T> &V, F Parse) {
       return false;
     L.push_back(X);
   }
-  T *P =
-      static_cast<T *>(allocateListStorage(L.size() * sizeof(T), alignof(T)));
+  T *P = Alloc.Allocate<T>(L.size());
   llvm::copy(L, P);
   V = ArrayRef(P, L.size());
   return true;
 }
 
-template <typename T> bool parseArgValue(StringRef S, ArrayRef<T> &V) {
-  return parseArgValue(S, V,
+template <typename T>
+bool parseArgValue(StringRef S, ArrayRef<T> &V, BumpPtrAllocator &Alloc) {
+  return parseArgValue(S, V, Alloc,
                        [](StringRef S, T &X) { return parseArgValue(S, X); });
 }
 
@@ -115,14 +120,15 @@ class LLVM_ABI LibraryOptTable : public OptTable {
 /// Connects an options struct to cl::ParseCommandLineOptions.
 class LLVM_ABI LibraryOptionsParser final : public cl::LibraryOptions {
 public:
-  using ApplyFn = bool (*)(const Arg &);
+  using ApplyFn = bool (*)(const Arg &, BumpPtrAllocator &);
   using TableFn = const OptTable &(*)();
   LibraryOptionsParser(TableFn Table, ApplyFn Apply, void (*Reset)())
       : Table(Table), Apply(Apply), Reset(Reset) {}
 
   void forEachOption(
       function_ref<void(StringRef, StringRef, StringRef)> Fn) const override;
-  Error parse(ArrayRef<const char *> Args, unsigned &Consumed) override;
+  Error parse(ArrayRef<const char *> Args, unsigned &Consumed,
+              BumpPtrAllocator &Alloc) override;
   void reset() override { Reset(); }
 
 private:
@@ -138,7 +144,9 @@ template <typename T> class RegisterLibraryOptions {
   static_assert(std::is_trivially_destructible_v<T>,
                 "an options struct must not need an exit-time destructor");
   LibraryOptionsParser Parser{T::optTable,
-                              [](const Arg &A) { return T::Global.apply(A); },
+                              [](const Arg &A, BumpPtrAllocator &Alloc) {
+                                return T::Global.apply(A, Alloc);
+                              },
                               [] { T::Global = T(); }};
 
 public:
diff --git a/llvm/include/llvm/Support/CommandLine.h b/llvm/include/llvm/Support/CommandLine.h
index 8d3dc5be1e481..bc7059244461e 100644
--- a/llvm/include/llvm/Support/CommandLine.h
+++ b/llvm/include/llvm/Support/CommandLine.h
@@ -2177,8 +2177,10 @@ class LLVM_ABI LibraryOptions {
 
   /// Parses the option spelled by Args[0], which may take Args[1] as its
   /// value, and sets \p Consumed to the number of arguments it spans. The
-  /// strings in \p Args remain valid until reset().
-  virtual Error parse(ArrayRef<const char *> Args, unsigned &Consumed) = 0;
+  /// strings in \p Args and the memory from \p Alloc remain valid until
+  /// reset().
+  virtual Error parse(ArrayRef<const char *> Args, unsigned &Consumed,
+                      BumpPtrAllocator &Alloc) = 0;
 
   /// Restores the default values.
   virtual void reset() = 0;
diff --git a/llvm/lib/Option/LibraryOptions.cpp b/llvm/lib/Option/LibraryOptions.cpp
index c3b3bd01f96db..cfcb82273eb6d 100644
--- a/llvm/lib/Option/LibraryOptions.cpp
+++ b/llvm/lib/Option/LibraryOptions.cpp
@@ -10,7 +10,6 @@
 #include "llvm/Option/ArgList.h"
 #include "llvm/Option/OptTable.h"
 #include "llvm/Option/Option.h"
-#include "llvm/Support/Allocator.h"
 #include "llvm/Support/Error.h"
 
 using namespace llvm;
@@ -18,12 +17,6 @@ using namespace llvm::opt;
 
 LibraryOptTable::~LibraryOptTable() = default;
 
-void *llvm::opt::allocateListStorage(size_t Size, size_t Alignment) {
-  // Never destroyed: list members refer to it until exit.
-  static BumpPtrAllocator &Alloc = *new BumpPtrAllocator;
-  return Alloc.Allocate(Size, Align(Alignment));
-}
-
 void LibraryOptionsParser::forEachOption(
     function_ref<void(StringRef, StringRef, StringRef)> Fn) const {
   const OptTable &T = Table();
@@ -42,7 +35,7 @@ void LibraryOptionsParser::forEachOption(
 }
 
 Error LibraryOptionsParser::parse(ArrayRef<const char *> Args,
-                                  unsigned &Consumed) {
+                                  unsigned &Consumed, BumpPtrAllocator &Alloc) {
   InputArgList List(Args.begin(), Args.end());
   Consumed = 0;
   std::unique_ptr<Arg> A = Table().ParseOneArg(List, Consumed);
@@ -52,7 +45,7 @@ Error LibraryOptionsParser::parse(ArrayRef<const char *> Args,
                              "' requires an argument");
   if (A->getOption().getKind() == Option::UnknownClass)
     return createStringError("unknown argument '" + Twine(Args[0]) + "'");
-  if (!Apply(*A))
+  if (!Apply(*A, Alloc))
     return createStringError("invalid value '" + Twine(A->getValue()) +
                              "' in '" + A->getAsString(List) + "'");
   return Error::success();
diff --git a/llvm/lib/Support/CommandLine.cpp b/llvm/lib/Support/CommandLine.cpp
index c2ac06dd6232b..1cb5fccb07a1b 100644
--- a/llvm/lib/Support/CommandLine.cpp
+++ b/llvm/lib/Support/CommandLine.cpp
@@ -178,8 +178,9 @@ class CommandLineParser {
   SmallVector<LibraryOptions *, 0> Libraries;
   DenseMap<StringRef, LibraryOptions *> LibraryIndex;
   size_t NumIndexedLibraries = 0;
-  // Copies of the arguments passed to LibraryOptions::parse, whose members may
-  // refer to them. Response file expansions do not outlive parsing.
+  // Storage that library options refer to: copies of the arguments passed to
+  // LibraryOptions::parse and what it allocates. Response file expansions do
+  // not outlive parsing.
   BumpPtrAllocator LibraryArgAlloc;
 
   CommandLineParser() { registerSubCommand(&SubCommand::getTopLevel()); }
@@ -1660,7 +1661,7 @@ bool CommandLineParser::ParseCommandLineOptions(int argc,
           for (unsigned J = 0; J != NumArgs; ++J)
             Args[J] = Saver.save(argv[i + J]).data();
           unsigned N = 1;
-          if (Error E = L->parse(ArrayRef(Args, NumArgs), N)) {
+          if (Error E = L->parse(ArrayRef(Args, NumArgs), N, LibraryArgAlloc)) {
             *Errs << ProgramName << ": " << toString(std::move(E)) << '\n';
             ErrorParsing = true;
           }
diff --git a/llvm/unittests/Option/LibraryOptionsTest.cpp b/llvm/unittests/Option/LibraryOptionsTest.cpp
index 026ff36426d84..0c94a172dfc88 100644
--- a/llvm/unittests/Option/LibraryOptionsTest.cpp
+++ b/llvm/unittests/Option/LibraryOptionsTest.cpp
@@ -30,6 +30,7 @@ namespace {
 
 // The struct -gen-opt-parser-defs generates: every spelling sets its member.
 TEST(LibraryOptionsTest, Apply) {
+  BumpPtrAllocator Alloc;
   TestLibraryOptions O;
   EXPECT_FALSE(O.enable);
   EXPECT_EQ(O.count, 3u);
@@ -49,7 +50,7 @@ TEST(LibraryOptionsTest, Apply) {
         Argv, MissingIndex, MissingCount);
     std::vector<bool> Applied;
     for (const opt::Arg *A : Args)
-      Applied.push_back(O.apply(*A));
+      Applied.push_back(O.apply(*A, Alloc));
     return Applied;
   };
   EXPECT_THAT(Apply({"-lib-enable", "--lib-count=7", "-lib-limit=0",
@@ -116,7 +117,9 @@ TEST(LibraryOptionsTest, BoolOrDefault) {
 TEST(LibraryOptionsTest, Parser) {
   opt::LibraryOptionsParser P(
       TestLibraryOptions::optTable,
-      [](const opt::Arg &A) { return TestLibraryOptions::Global.apply(A); },
+      [](const opt::Arg &A, BumpPtrAllocator &Alloc) {
+        return TestLibraryOptions::Global.apply(A, Alloc);
+      },
       [] { TestLibraryOptions::Global = TestLibraryOptions(); });
 
   std::vector<std::string> Rows;
@@ -133,9 +136,10 @@ TEST(LibraryOptionsTest, Parser) {
           "lib-print|[=<a|b>]|A flag or enum", "lib-ratio|=<value>|A double",
           "lib-tristate|=<Default|Enable|Disable>|A tri-state"));
 
+  BumpPtrAllocator Alloc;
   auto Parse = [&](std::initializer_list<const char *> Argv) {
     unsigned Consumed = 0;
-    std::string Err = toString(P.parse(Argv, Consumed));
+    std::string Err = toString(P.parse(Argv, Consumed, Alloc));
     return std::to_string(Consumed) + " " + Err;
   };
   EXPECT_EQ(Parse({"-lib-count", "5"}), "2 ");
@@ -175,6 +179,12 @@ TEST(LibraryOptionsTest, Register) {
   EXPECT_FALSE(G.enable);
   EXPECT_EQ(G.Path, "p");
   EXPECT_THAT(G.list, testing::IsEmpty());
+  // Options parse again after a reset frees their storage.
+  const char *Again[] = {"prog", "-lib-path=r", "-lib-list=3", "-lib-list=4"};
+  EXPECT_TRUE(
+      cl::ParseCommandLineOptions(std::size(Again), Again, "", &nulls()));
+  EXPECT_EQ(G.Path, "r");
+  EXPECT_THAT(G.list, testing::ElementsAre(3u, 4u));
   cl::ResetCommandLineParser();
 }
 
diff --git a/llvm/unittests/Support/CommandLineTest.cpp b/llvm/unittests/Support/CommandLineTest.cpp
index fc5d93acf87b8..ccf45962ba04f 100644
--- a/llvm/unittests/Support/CommandLineTest.cpp
+++ b/llvm/unittests/Support/CommandLineTest.cpp
@@ -2346,7 +2346,8 @@ struct TestLibrary final : cl::LibraryOptions {
     Fn("library-flag", "", "A flag");
     Fn("library-int", " <int>", "");
   }
-  Error parse(ArrayRef<const char *> Argv, unsigned &Consumed) override {
+  Error parse(ArrayRef<const char *> Argv, unsigned &Consumed,
+              BumpPtrAllocator &) override {
     Consumed = 1;
     Args.push_back(Argv[0]);
     if (StringRef(Argv[0]).ltrim('-') != "library-int")
diff --git a/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp b/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp
index c972013bc9015..09baae4d80c6e 100644
--- a/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp
+++ b/llvm/utils/TableGen/Basic/OptionParserEmitter.cpp
@@ -310,7 +310,8 @@ static void emitOptionsStruct(const Record &Struct,
   OS << "\n#ifdef OPTIONS_STRUCT_DECL\n#undef OPTIONS_STRUCT_DECL\n";
   OS << "#include \"llvm/ADT/ArrayRef.h\"\n";
   OS << "#include \"llvm/ADT/BoolOrDefault.h\"\n";
-  OS << "#include \"llvm/ADT/StringRef.h\"\n\n";
+  OS << "#include \"llvm/ADT/StringRef.h\"\n";
+  OS << "#include \"llvm/Support/Allocator.h\"\n\n";
   StringRef Namespace = Struct.getValueAsString("Namespace");
   OS << "namespace llvm {\nnamespace opt {\nclass Arg;\n"
         "class OptTable;\n} // namespace opt\n} // namespace llvm\n\n";
@@ -323,9 +324,10 @@ static void emitOptionsStruct(const Record &Struct,
   OS << "\n  /// The instance cl::ParseCommandLineOptions sets.\n";
   OS << "  static " << Name << " Global;\n\n";
   OS << "  static const llvm::opt::OptTable &optTable();\n";
-  OS << "  /// Sets the member that \\p A names. Returns false if the value is "
-        "invalid.\n";
-  OS << "  bool apply(const llvm::opt::Arg &A);\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 "
+        "&Alloc);\n";
   OS << "};\n} // namespace " << Namespace << "\n";
   OS << "#endif // OPTIONS_STRUCT_DECL\n";
 
@@ -341,7 +343,8 @@ static void emitOptionsStruct(const Record &Struct,
   OS << "const llvm::opt::OptTable &" << Qualified << "::optTable() {\n";
   OS << "  static const llvm::opt::LibraryOptTable T(optionTables());\n";
   OS << "  return T;\n}\n\n";
-  OS << "bool " << Qualified << "::apply(const llvm::opt::Arg &A) {\n";
+  OS << "bool " << Qualified
+     << "::apply(const llvm::opt::Arg &A, llvm::BumpPtrAllocator &Alloc) {\n";
   OS << "  switch (A.getOption().getID()) {\n";
   for (const Record *R : Fields) {
     OS << "  case OPT_" << getStructOptionID(*R) << ":\n";
@@ -359,7 +362,7 @@ static void emitOptionsStruct(const Record &Struct,
                                      "value");
       // The generic lambda sets a scalar, a std::optional, or a list element.
       OS << "    return llvm::opt::parseArgValue(A.getValue(), " << Member
-         << ", [](llvm::StringRef V, auto &X) {\n";
+         << ", Alloc, [](llvm::StringRef V, auto &X) {\n";
       for (auto [Value, Enumerator] : llvm::zip_equal(Values, Enumerators))
         OS << "      if (V == \"" << Value
            << "\") {\n        X = " << Enumerator
@@ -373,7 +376,7 @@ static void emitOptionsStruct(const Record &Struct,
             ? "A.getNumValues() ? A.getValue() : \"true\""
             : "A.getValue()";
     OS << "    return llvm::opt::parseArgValue(" << Value << ", " << Member
-       << ");\n";
+       << ", Alloc);\n";
   }
   OS << "  }\n  llvm_unreachable(\"option without a member\");\n}\n";
   OS << "#endif // OPTIONS_STRUCT_DEFS\n";



More information about the llvm-commits mailing list