1//===- OptionParserEmitter.cpp - Table Driven Command Option Line Parsing -===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Common/OptEmitter.h"
10#include "llvm/ADT/STLExtras.h"
11#include "llvm/ADT/SmallString.h"
12#include "llvm/ADT/SmallVector.h"
13#include "llvm/ADT/StringExtras.h"
14#include "llvm/ADT/Twine.h"
15#include "llvm/Option/OptTable.h"
16#include "llvm/Support/InterleavedRange.h"
17#include "llvm/Support/raw_ostream.h"
18#include "llvm/TableGen/Record.h"
19#include "llvm/TableGen/StringToOffsetTable.h"
20#include "llvm/TableGen/TableGenBackend.h"
21#include <cstring>
22#include <map>
23
24using namespace llvm;
25
26static std::string getOptionName(const Record &R) {
27 // Use the record name unless EnumName is defined.
28 if (isa<UnsetInit>(Val: R.getValueInit(FieldName: "EnumName")))
29 return R.getName().str();
30
31 return R.getValueAsString(FieldName: "EnumName").str();
32}
33
34static raw_ostream &writeStrTableOffset(raw_ostream &OS,
35 const StringToOffsetTable &Table,
36 llvm::StringRef Str) {
37 OS << Table.GetStringOffset(Str) << " /* ";
38 OS.write_escaped(Str);
39 OS << " */";
40 return OS;
41}
42
43static raw_ostream &writeCstring(raw_ostream &OS, llvm::StringRef Str) {
44 OS << '"';
45 OS.write_escaped(Str);
46 OS << '"';
47 return OS;
48}
49
50static std::string getOptionPrefixedName(const Record &R) {
51 std::vector<StringRef> Prefixes = R.getValueAsListOfStrings(FieldName: "Prefixes");
52 StringRef Name = R.getValueAsString(FieldName: "Name");
53
54 if (Prefixes.empty())
55 return Name.str();
56
57 return (Prefixes[0] + Twine(Name)).str();
58}
59
60class MarshallingInfo {
61public:
62 static constexpr const char *MacroName = "OPTION_WITH_MARSHALLING";
63 const Record &R;
64 bool ShouldAlwaysEmit = false;
65 StringRef MacroPrefix;
66 StringRef KeyPath;
67 StringRef DefaultValue;
68 StringRef NormalizedValuesScope;
69 StringRef ImpliedCheck;
70 StringRef ImpliedValue;
71 StringRef ShouldParse;
72 StringRef Normalizer;
73 StringRef Denormalizer;
74 int TableIndex = -1;
75 std::vector<StringRef> Values;
76 std::vector<StringRef> NormalizedValues;
77 std::string ValueTableName;
78
79 static size_t NextTableIndex;
80
81 static constexpr const char *ValueTablePreamble = R"(
82struct SimpleEnumValue {
83 const char *Name;
84 unsigned Value;
85};
86
87struct SimpleEnumValueTable {
88 const SimpleEnumValue *Table;
89 unsigned Size;
90};
91)";
92
93 static constexpr const char *ValueTablesDecl =
94 "static const SimpleEnumValueTable SimpleEnumValueTables[] = ";
95
96 MarshallingInfo(const Record &R) : R(R) {}
97
98 std::string getMacroName() const {
99 return (MacroPrefix + MarshallingInfo::MacroName).str();
100 }
101
102 void emit(raw_ostream &OS) const {
103 OS << ShouldParse;
104 OS << ", ";
105 OS << ShouldAlwaysEmit;
106 OS << ", ";
107 OS << KeyPath;
108 OS << ", ";
109 emitScopedNormalizedValue(OS, NormalizedValue: DefaultValue);
110 OS << ", ";
111 OS << ImpliedCheck;
112 OS << ", ";
113 emitScopedNormalizedValue(OS, NormalizedValue: ImpliedValue);
114 OS << ", ";
115 OS << Normalizer;
116 OS << ", ";
117 OS << Denormalizer;
118 OS << ", ";
119 OS << TableIndex;
120 }
121
122 std::optional<StringRef> emitValueTable(raw_ostream &OS) const {
123 if (TableIndex == -1)
124 return {};
125 OS << "static const SimpleEnumValue " << ValueTableName << "[] = {\n";
126 for (unsigned I = 0, E = Values.size(); I != E; ++I) {
127 OS << "{";
128 writeCstring(OS, Str: Values[I]);
129 OS << ",";
130 OS << "static_cast<unsigned>(";
131 emitScopedNormalizedValue(OS, NormalizedValue: NormalizedValues[I]);
132 OS << ")},";
133 }
134 OS << "};\n";
135 return StringRef(ValueTableName);
136 }
137
138private:
139 void emitScopedNormalizedValue(raw_ostream &OS,
140 StringRef NormalizedValue) const {
141 if (!NormalizedValuesScope.empty())
142 OS << NormalizedValuesScope << "::";
143 OS << NormalizedValue;
144 }
145};
146
147size_t MarshallingInfo::NextTableIndex = 0;
148
149static MarshallingInfo createMarshallingInfo(const Record &R) {
150 assert(!isa<UnsetInit>(R.getValueInit("KeyPath")) &&
151 !isa<UnsetInit>(R.getValueInit("DefaultValue")) &&
152 "MarshallingInfo must have a provide a keypath, default value and a "
153 "value merger");
154
155 MarshallingInfo Ret(R);
156
157 Ret.ShouldAlwaysEmit = R.getValueAsBit(FieldName: "ShouldAlwaysEmit");
158 Ret.MacroPrefix = R.getValueAsString(FieldName: "MacroPrefix");
159 Ret.KeyPath = R.getValueAsString(FieldName: "KeyPath");
160 Ret.DefaultValue = R.getValueAsString(FieldName: "DefaultValue");
161 Ret.NormalizedValuesScope = R.getValueAsString(FieldName: "NormalizedValuesScope");
162 Ret.ImpliedCheck = R.getValueAsString(FieldName: "ImpliedCheck");
163 Ret.ImpliedValue =
164 R.getValueAsOptionalString(FieldName: "ImpliedValue").value_or(u&: Ret.DefaultValue);
165
166 Ret.ShouldParse = R.getValueAsString(FieldName: "ShouldParse");
167 Ret.Normalizer = R.getValueAsString(FieldName: "Normalizer");
168 Ret.Denormalizer = R.getValueAsString(FieldName: "Denormalizer");
169
170 if (!isa<UnsetInit>(Val: R.getValueInit(FieldName: "NormalizedValues"))) {
171 assert(!isa<UnsetInit>(R.getValueInit("Values")) &&
172 "Cannot provide normalized values for value-less options");
173 Ret.TableIndex = MarshallingInfo::NextTableIndex++;
174 Ret.NormalizedValues = R.getValueAsListOfStrings(FieldName: "NormalizedValues");
175 Ret.Values.reserve(n: Ret.NormalizedValues.size());
176 Ret.ValueTableName = getOptionName(R) + "ValueTable";
177
178 StringRef ValuesStr = R.getValueAsString(FieldName: "Values");
179 for (;;) {
180 size_t Idx = ValuesStr.find(C: ',');
181 if (Idx == StringRef::npos)
182 break;
183 if (Idx > 0)
184 Ret.Values.push_back(x: ValuesStr.slice(Start: 0, End: Idx));
185 ValuesStr = ValuesStr.substr(Start: Idx + 1);
186 }
187 if (!ValuesStr.empty())
188 Ret.Values.push_back(x: ValuesStr);
189
190 assert(Ret.Values.size() == Ret.NormalizedValues.size() &&
191 "The number of normalized values doesn't match the number of "
192 "values");
193 }
194
195 return Ret;
196}
197
198static void emitHelpTextsForVariants(
199 raw_ostream &OS, std::vector<std::pair<std::vector<std::string>, StringRef>>
200 HelpTextsForVariants) {
201 // OptTable must be constexpr so it uses std::arrays with these capacities.
202 const unsigned MaxVisibilityPerHelp = 2;
203 const unsigned MaxVisibilityHelp = 1;
204
205 assert(HelpTextsForVariants.size() <= MaxVisibilityHelp &&
206 "Too many help text variants to store in "
207 "OptTable::HelpTextsForVariants");
208
209 // This function must initialise any unused elements of those arrays.
210 for (auto [Visibilities, _] : HelpTextsForVariants)
211 while (Visibilities.size() < MaxVisibilityPerHelp)
212 Visibilities.push_back(x: "0");
213
214 while (HelpTextsForVariants.size() < MaxVisibilityHelp)
215 HelpTextsForVariants.push_back(
216 x: {std::vector<std::string>(MaxVisibilityPerHelp, "0"), ""});
217
218 OS << ", (std::array<std::pair<std::array<unsigned, " << MaxVisibilityPerHelp
219 << ">, const char*>, " << MaxVisibilityHelp << ">{{ ";
220
221 auto VisibilityHelpEnd = HelpTextsForVariants.cend();
222 for (auto VisibilityHelp = HelpTextsForVariants.cbegin();
223 VisibilityHelp != VisibilityHelpEnd; ++VisibilityHelp) {
224 auto [Visibilities, Help] = *VisibilityHelp;
225
226 assert(Visibilities.size() <= MaxVisibilityPerHelp &&
227 "Too many visibilities to store in an "
228 "OptTable::HelpTextsForVariants entry");
229 OS << "{std::array<unsigned, " << MaxVisibilityPerHelp << ">{{"
230 << llvm::interleaved(R: Visibilities) << "}}, ";
231
232 if (Help.size())
233 writeCstring(OS, Str: Help);
234 else
235 OS << "nullptr";
236 OS << "}";
237
238 if (std::next(x: VisibilityHelp) != VisibilityHelpEnd)
239 OS << ", ";
240 }
241 OS << " }})";
242}
243
244/// OptionParserEmitter - This tablegen backend takes an input .td file
245/// describing a list of options and emits a data structure for parsing and
246/// working with those options when given an input command line.
247static void emitOptionParser(const RecordKeeper &Records, raw_ostream &OS) {
248 // Get the option groups and options.
249 ArrayRef<const Record *> Groups =
250 Records.getAllDerivedDefinitions(ClassName: "OptionGroup");
251 std::vector<const Record *> Opts = Records.getAllDerivedDefinitions(ClassName: "Option");
252 llvm::sort(C&: Opts, Comp: IsOptionRecordsLess);
253
254 std::vector<const Record *> SubCommands =
255 Records.getAllDerivedDefinitions(ClassName: "SubCommand");
256
257 emitSourceFileHeader(Desc: "Option Parsing Definitions", OS);
258
259 // Generate prefix groups.
260 using PrefixKeyT = SmallVector<SmallString<2>, 2>;
261 using PrefixesT = std::map<PrefixKeyT, unsigned>;
262 PrefixesT Prefixes;
263 Prefixes.try_emplace(k: PrefixKeyT(), args: 0);
264 for (const Record &R : llvm::make_pointee_range(Range&: Opts)) {
265 std::vector<StringRef> RPrefixes = R.getValueAsListOfStrings(FieldName: "Prefixes");
266 PrefixKeyT PrefixKey(RPrefixes.begin(), RPrefixes.end());
267 Prefixes.try_emplace(k: PrefixKey, args: 0);
268 }
269
270 // Generate sub command groups.
271 using SubCommandKeyT = SmallVector<StringRef, 2>;
272 using SubCommandIDsT = std::map<SubCommandKeyT, unsigned>;
273 SubCommandIDsT SubCommandIDs;
274
275 auto PrintSubCommandIdsOffset = [&SubCommandIDs, &OS](const Record &R) {
276 if (R.getValue(Name: "SubCommands") != nullptr) {
277 std::vector<const Record *> SubCommands =
278 R.getValueAsListOfDefs(FieldName: "SubCommands");
279 SubCommandKeyT SubCommandKey;
280 for (const auto &SubCommand : SubCommands)
281 SubCommandKey.push_back(Elt: SubCommand->getName());
282 OS << SubCommandIDs[SubCommandKey];
283 } else {
284 // The option SubCommandIDsOffset (for default top level toolname is 0).
285 OS << " 0";
286 }
287 };
288
289 SubCommandIDs.try_emplace(k: SubCommandKeyT(), args: 0);
290 for (const Record &R : llvm::make_pointee_range(Range&: Opts)) {
291 std::vector<const Record *> RSubCommands =
292 R.getValueAsListOfDefs(FieldName: "SubCommands");
293 SubCommandKeyT SubCommandKey;
294 for (const auto &SubCommand : RSubCommands)
295 SubCommandKey.push_back(Elt: SubCommand->getName());
296 SubCommandIDs.try_emplace(k: SubCommandKey, args: 0);
297 }
298
299 DenseSet<StringRef> PrefixesUnionSet;
300 for (const auto &[Prefix, _] : Prefixes)
301 PrefixesUnionSet.insert_range(R: Prefix);
302 SmallVector<StringRef> PrefixesUnion(PrefixesUnionSet.begin(),
303 PrefixesUnionSet.end());
304 array_pod_sort(Start: PrefixesUnion.begin(), End: PrefixesUnion.end());
305
306 llvm::StringToOffsetTable Table;
307 // We can add all the prefixes via the union.
308 for (const auto &Prefix : PrefixesUnion)
309 Table.GetOrAddStringOffset(Str: Prefix);
310 for (const Record &R : llvm::make_pointee_range(Range&: Groups))
311 Table.GetOrAddStringOffset(Str: R.getValueAsString(FieldName: "Name"));
312 for (const Record &R : llvm::make_pointee_range(Range&: Opts))
313 Table.GetOrAddStringOffset(Str: getOptionPrefixedName(R));
314
315 // Dump string table.
316 OS << "/////////\n";
317 OS << "// String table\n\n";
318 OS << "#ifdef OPTTABLE_STR_TABLE_CODE\n";
319 Table.EmitStringTableDef(OS, Name: "OptionStrTable");
320 OS << "#endif // OPTTABLE_STR_TABLE_CODE\n\n";
321
322 // Dump prefixes.
323 OS << "/////////\n";
324 OS << "// Prefixes\n\n";
325 OS << "#ifdef OPTTABLE_PREFIXES_TABLE_CODE\n";
326 OS << "static constexpr llvm::StringTable::Offset OptionPrefixesTable[] = "
327 "{\n";
328 {
329 // Ensure the first prefix set is always empty.
330 assert(!Prefixes.empty() &&
331 "We should always emit an empty set of prefixes");
332 assert(Prefixes.begin()->first.empty() &&
333 "First prefix set should always be empty");
334 llvm::ListSeparator Sep(",\n");
335 unsigned CurIndex = 0;
336 for (auto &[Prefix, PrefixIndex] : Prefixes) {
337 // First emit the number of prefix strings in this list of prefixes.
338 OS << Sep << " " << Prefix.size() << " /* prefixes */";
339 PrefixIndex = CurIndex;
340 assert((CurIndex == 0 || !Prefix.empty()) &&
341 "Only first prefix set should be empty!");
342 for (const auto &PrefixKey : Prefix)
343 OS << ", " << *Table.GetStringOffset(Str: PrefixKey) << " /* '" << PrefixKey
344 << "' */";
345 CurIndex += Prefix.size() + 1;
346 }
347 }
348 OS << "\n};\n";
349 OS << "#endif // OPTTABLE_PREFIXES_TABLE_CODE\n\n";
350
351 // Dump subcommand IDs.
352 OS << "/////////";
353 OS << "// SubCommand IDs\n\n";
354 OS << "#ifdef OPTTABLE_SUBCOMMAND_IDS_TABLE_CODE\n";
355 OS << "static constexpr unsigned OptionSubCommandIDsTable[] = {\n";
356 {
357 // Ensure the first subcommand set is always empty.
358 assert(!SubCommandIDs.empty() &&
359 "We should always emit an empty set of subcommands");
360 assert(SubCommandIDs.begin()->first.empty() &&
361 "First subcommand set should always be empty");
362 llvm::ListSeparator Sep(",\n");
363 unsigned CurIndex = 0;
364 for (auto &[SubCommand, SubCommandIndex] : SubCommandIDs) {
365 // First emit the number of subcommand strings in this list of
366 // subcommands.
367 OS << Sep << " " << SubCommand.size() << " /* subcommands */";
368 SubCommandIndex = CurIndex;
369 assert((CurIndex == 0 || !SubCommand.empty()) &&
370 "Only first subcommand set should be empty!");
371 for (const auto &SubCommandKey : SubCommand) {
372 auto It = llvm::find_if(Range&: SubCommands, P: [&](const Record *R) {
373 return R->getName() == SubCommandKey;
374 });
375 assert(It != SubCommands.end() && "SubCommand not found");
376 OS << ", " << std::distance(first: SubCommands.begin(), last: It) << " /* '"
377 << SubCommandKey << "' */";
378 }
379 CurIndex += SubCommand.size() + 1;
380 }
381 }
382 OS << "\n};\n";
383 OS << "#endif // OPTTABLE_SUBCOMMAND_IDS_TABLE_CODE\n\n";
384
385 // Dump prefixes union.
386 OS << "/////////\n";
387 OS << "// Prefix Union\n\n";
388 OS << "#ifdef OPTTABLE_PREFIXES_UNION_CODE\n";
389 OS << "static constexpr llvm::StringTable::Offset OptionPrefixesUnion[] = "
390 "{\n";
391 {
392 llvm::ListSeparator Sep(", ");
393 for (auto Prefix : PrefixesUnion)
394 OS << Sep << " " << *Table.GetStringOffset(Str: Prefix) << " /* '" << Prefix
395 << "' */";
396 }
397 OS << "\n};\n";
398 OS << "#endif // OPTTABLE_PREFIXES_UNION_CODE\n\n";
399
400 // Dump groups.
401 OS << "/////////\n";
402 OS << "// ValuesCode\n\n";
403 OS << "#ifdef OPTTABLE_VALUES_CODE\n";
404 for (const Record &R : llvm::make_pointee_range(Range&: Opts)) {
405 // The option values, if any;
406 if (!isa<UnsetInit>(Val: R.getValueInit(FieldName: "ValuesCode"))) {
407 assert(isa<UnsetInit>(R.getValueInit("Values")) &&
408 "Cannot choose between Values and ValuesCode");
409 OS << "#define VALUES_CODE " << getOptionName(R) << "_Values\n";
410 OS << R.getValueAsString(FieldName: "ValuesCode") << "\n";
411 OS << "#undef VALUES_CODE\n";
412 }
413 }
414 OS << "#endif\n";
415
416 OS << "/////////\n";
417 OS << "// Groups\n\n";
418 OS << "#ifdef OPTION\n";
419 for (const Record &R : llvm::make_pointee_range(Range&: Groups)) {
420 // Start a single option entry.
421 OS << "OPTION(";
422
423 // A zero prefix offset corresponds to an empty set of prefixes.
424 OS << "0 /* no prefixes */";
425
426 // The option string offset.
427 OS << ", ";
428 writeStrTableOffset(OS, Table, Str: R.getValueAsString(FieldName: "Name"));
429
430 // The option identifier name.
431 OS << ", " << getOptionName(R);
432
433 // The option kind.
434 OS << ", Group";
435
436 // The containing option group (if any).
437 OS << ", ";
438 if (const DefInit *DI = dyn_cast<DefInit>(Val: R.getValueInit(FieldName: "Group")))
439 OS << getOptionName(R: *DI->getDef());
440 else
441 OS << "INVALID";
442
443 // The other option arguments (unused for groups).
444 OS << ", INVALID, nullptr, 0, 0, 0";
445
446 // The option help text.
447 if (!isa<UnsetInit>(Val: R.getValueInit(FieldName: "HelpText"))) {
448 OS << ",\n";
449 OS << " ";
450 writeCstring(OS, Str: R.getValueAsString(FieldName: "HelpText"));
451 } else {
452 OS << ", nullptr";
453 }
454
455 // Not using Visibility specific text for group help.
456 emitHelpTextsForVariants(OS, HelpTextsForVariants: {});
457
458 // The option meta-variable name (unused).
459 OS << ", nullptr";
460
461 // The option Values (unused for groups).
462 OS << ", nullptr";
463
464 // The option SubCommandIDsOffset.
465 OS << ", ";
466 PrintSubCommandIdsOffset(R);
467 OS << ")\n";
468 }
469 OS << "\n";
470
471 OS << "//////////\n";
472 OS << "// Options\n\n";
473
474 auto WriteOptRecordFields = [&](raw_ostream &OS, const Record &R) {
475 // The option prefix;
476 std::vector<StringRef> RPrefixes = R.getValueAsListOfStrings(FieldName: "Prefixes");
477 OS << Prefixes[PrefixKeyT(RPrefixes.begin(), RPrefixes.end())] << ", ";
478
479 // The option prefixed name.
480 writeStrTableOffset(OS, Table, Str: getOptionPrefixedName(R));
481
482 // The option identifier name.
483 OS << ", " << getOptionName(R);
484
485 // The option kind.
486 OS << ", " << R.getValueAsDef(FieldName: "Kind")->getValueAsString(FieldName: "Name");
487
488 // The containing option group (if any).
489 OS << ", ";
490 const ListInit *GroupFlags = nullptr;
491 const ListInit *GroupVis = nullptr;
492 if (const DefInit *DI = dyn_cast<DefInit>(Val: R.getValueInit(FieldName: "Group"))) {
493 GroupFlags = DI->getDef()->getValueAsListInit(FieldName: "Flags");
494 GroupVis = DI->getDef()->getValueAsListInit(FieldName: "Visibility");
495 OS << getOptionName(R: *DI->getDef());
496 } else {
497 OS << "INVALID";
498 }
499
500 // The option alias (if any).
501 OS << ", ";
502 if (const DefInit *DI = dyn_cast<DefInit>(Val: R.getValueInit(FieldName: "Alias")))
503 OS << getOptionName(R: *DI->getDef());
504 else
505 OS << "INVALID";
506
507 // The option alias arguments (if any).
508 // Emitted as a \0 separated list in a string, e.g. ["foo", "bar"]
509 // would become "foo\0bar\0". Note that the compiler adds an implicit
510 // terminating \0 at the end.
511 OS << ", ";
512 std::vector<StringRef> AliasArgs = R.getValueAsListOfStrings(FieldName: "AliasArgs");
513 if (AliasArgs.size() == 0) {
514 OS << "nullptr";
515 } else {
516 OS << "\"";
517 for (StringRef AliasArg : AliasArgs)
518 OS << AliasArg << "\\0";
519 OS << "\"";
520 }
521
522 // "Flags" for the option, such as HelpHidden and Render*
523 OS << ", ";
524 int NumFlags = 0;
525 const ListInit *LI = R.getValueAsListInit(FieldName: "Flags");
526 for (const Init *I : *LI)
527 OS << (NumFlags++ ? " | " : "") << cast<DefInit>(Val: I)->getDef()->getName();
528 if (GroupFlags) {
529 for (const Init *I : *GroupFlags)
530 OS << (NumFlags++ ? " | " : "")
531 << cast<DefInit>(Val: I)->getDef()->getName();
532 }
533 if (NumFlags == 0)
534 OS << '0';
535
536 // Option visibility, for sharing options between drivers.
537 OS << ", ";
538 int NumVisFlags = 0;
539 LI = R.getValueAsListInit(FieldName: "Visibility");
540 for (const Init *I : *LI)
541 OS << (NumVisFlags++ ? " | " : "")
542 << cast<DefInit>(Val: I)->getDef()->getName();
543 if (GroupVis) {
544 for (const Init *I : *GroupVis)
545 OS << (NumVisFlags++ ? " | " : "")
546 << cast<DefInit>(Val: I)->getDef()->getName();
547 }
548 if (NumVisFlags == 0)
549 OS << '0';
550
551 // The option parameter field.
552 OS << ", " << R.getValueAsInt(FieldName: "NumArgs");
553
554 // The option help text.
555 if (!isa<UnsetInit>(Val: R.getValueInit(FieldName: "HelpText"))) {
556 OS << ",\n";
557 OS << " ";
558 writeCstring(OS, Str: R.getValueAsString(FieldName: "HelpText"));
559 } else {
560 OS << ", nullptr";
561 }
562
563 std::vector<std::pair<std::vector<std::string>, StringRef>>
564 HelpTextsForVariants;
565 for (const Record *VisibilityHelp :
566 R.getValueAsListOfDefs(FieldName: "HelpTextsForVariants")) {
567 ArrayRef<const Init *> Visibilities =
568 VisibilityHelp->getValueAsListInit(FieldName: "Visibilities")->getElements();
569
570 std::vector<std::string> VisibilityNames;
571 for (const Init *Visibility : Visibilities)
572 VisibilityNames.push_back(x: Visibility->getAsUnquotedString());
573
574 HelpTextsForVariants.emplace_back(
575 args&: VisibilityNames, args: VisibilityHelp->getValueAsString(FieldName: "Text"));
576 }
577 emitHelpTextsForVariants(OS, HelpTextsForVariants: std::move(HelpTextsForVariants));
578
579 // The option meta-variable name.
580 OS << ", ";
581 if (!isa<UnsetInit>(Val: R.getValueInit(FieldName: "MetaVarName")))
582 writeCstring(OS, Str: R.getValueAsString(FieldName: "MetaVarName"));
583 else
584 OS << "nullptr";
585
586 // The option Values. Used for shell autocompletion.
587 OS << ", ";
588 if (!isa<UnsetInit>(Val: R.getValueInit(FieldName: "Values")))
589 writeCstring(OS, Str: R.getValueAsString(FieldName: "Values"));
590 else if (!isa<UnsetInit>(Val: R.getValueInit(FieldName: "ValuesCode")))
591 OS << getOptionName(R) << "_Values";
592 else
593 OS << "nullptr";
594
595 // The option SubCommandIDsOffset.
596 OS << ", ";
597 PrintSubCommandIdsOffset(R);
598 };
599
600 auto IsMarshallingOption = [](const Record &R) {
601 return !isa<UnsetInit>(Val: R.getValueInit(FieldName: "KeyPath")) &&
602 !R.getValueAsString(FieldName: "KeyPath").empty();
603 };
604
605 std::vector<const Record *> OptsWithMarshalling;
606 for (const Record &R : llvm::make_pointee_range(Range&: Opts)) {
607 // Start a single option entry.
608 OS << "OPTION(";
609 WriteOptRecordFields(OS, R);
610 OS << ")\n";
611 if (IsMarshallingOption(R))
612 OptsWithMarshalling.push_back(x: &R);
613 }
614 OS << "#endif // OPTION\n";
615
616 auto CmpMarshallingOpts = [](const Record *const *A, const Record *const *B) {
617 unsigned AID = (*A)->getID();
618 unsigned BID = (*B)->getID();
619
620 if (AID < BID)
621 return -1;
622 if (AID > BID)
623 return 1;
624 return 0;
625 };
626 // The RecordKeeper stores records (options) in lexicographical order, and we
627 // have reordered the options again when generating prefix groups. We need to
628 // restore the original definition order of options with marshalling to honor
629 // the topology of the dependency graph implied by `DefaultAnyOf`.
630 array_pod_sort(Start: OptsWithMarshalling.begin(), End: OptsWithMarshalling.end(),
631 Compare: CmpMarshallingOpts);
632
633 std::vector<MarshallingInfo> MarshallingInfos;
634 MarshallingInfos.reserve(n: OptsWithMarshalling.size());
635 for (const auto *R : OptsWithMarshalling)
636 MarshallingInfos.push_back(x: createMarshallingInfo(R: *R));
637
638 for (const auto &MI : MarshallingInfos) {
639 OS << "#ifdef " << MI.getMacroName() << "\n";
640 OS << MI.getMacroName() << "(";
641 WriteOptRecordFields(OS, MI.R);
642 OS << ", ";
643 MI.emit(OS);
644 OS << ")\n";
645 OS << "#endif // " << MI.getMacroName() << "\n";
646 }
647
648 OS << "\n";
649 OS << "#ifdef SIMPLE_ENUM_VALUE_TABLE";
650 OS << "\n";
651 OS << MarshallingInfo::ValueTablePreamble;
652 std::vector<StringRef> ValueTableNames;
653 for (const auto &MI : MarshallingInfos)
654 if (auto MaybeValueTableName = MI.emitValueTable(OS))
655 ValueTableNames.push_back(x: *MaybeValueTableName);
656
657 OS << MarshallingInfo::ValueTablesDecl << "{";
658 for (auto ValueTableName : ValueTableNames)
659 OS << "{" << ValueTableName << ", std::size(" << ValueTableName << ")},\n";
660 OS << "};\n";
661 OS << "static const unsigned SimpleEnumValueTablesSize = "
662 "std::size(SimpleEnumValueTables);\n";
663
664 OS << "#endif // SIMPLE_ENUM_VALUE_TABLE\n";
665 OS << "\n";
666 OS << "/////////\n";
667 OS << "\n// SubCommands\n\n";
668 OS << "#ifdef OPTTABLE_SUBCOMMANDS_CODE\n";
669 OS << "static constexpr llvm::opt::OptTable::SubCommand OptionSubCommands[] "
670 "= "
671 "{\n";
672 for (const Record *SubCommand : SubCommands) {
673 OS << " { \"" << SubCommand->getValueAsString(FieldName: "Name") << "\", ";
674 OS << "\"" << SubCommand->getValueAsString(FieldName: "HelpText") << "\", ";
675 OS << "\"" << SubCommand->getValueAsString(FieldName: "Usage") << "\" },\n";
676 }
677 OS << "};\n";
678 OS << "#endif // OPTTABLE_SUBCOMMANDS_CODE\n\n";
679
680 OS << "\n";
681}
682
683static TableGen::Emitter::Opt X("gen-opt-parser-defs", emitOptionParser,
684 "Generate option definitions");
685