LLVM 20.0.0git
OptTable.cpp
Go to the documentation of this file.
1//===- OptTable.cpp - Option Table Implementation -------------------------===//
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
10#include "llvm/ADT/STLExtras.h"
11#include "llvm/ADT/StringRef.h"
12#include "llvm/Option/Arg.h"
13#include "llvm/Option/ArgList.h"
15#include "llvm/Option/Option.h"
16#include "llvm/Support/CommandLine.h" // for expandResponseFiles
21#include <algorithm>
22#include <cassert>
23#include <cctype>
24#include <cstring>
25#include <map>
26#include <set>
27#include <string>
28#include <utility>
29#include <vector>
30
31using namespace llvm;
32using namespace llvm::opt;
33
34namespace {
35struct OptNameLess {
36 const char *StrTable;
37 ArrayRef<unsigned> PrefixesTable;
38
39 explicit OptNameLess(const char *StrTable, ArrayRef<unsigned> PrefixesTable)
40 : StrTable(StrTable), PrefixesTable(PrefixesTable) {}
41
42#ifndef NDEBUG
43 inline bool operator()(const OptTable::Info &A,
44 const OptTable::Info &B) const {
45 if (&A == &B)
46 return false;
47
48 if (int Cmp = StrCmpOptionName(A.getName(StrTable, PrefixesTable),
49 B.getName(StrTable, PrefixesTable)))
50 return Cmp < 0;
51
52 SmallVector<StringRef, 8> APrefixes, BPrefixes;
53 A.appendPrefixes(StrTable, PrefixesTable, APrefixes);
54 B.appendPrefixes(StrTable, PrefixesTable, BPrefixes);
55
56 if (int Cmp = StrCmpOptionPrefixes(APrefixes, BPrefixes))
57 return Cmp < 0;
58
59 // Names are the same, check that classes are in order; exactly one
60 // should be joined, and it should succeed the other.
61 assert(
62 ((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
63 "Unexpected classes for options with same name.");
64 return B.Kind == Option::JoinedClass;
65 }
66#endif
67
68 // Support lower_bound between info and an option name.
69 inline bool operator()(const OptTable::Info &I, StringRef Name) const {
70 // Do not fallback to case sensitive comparison.
71 return StrCmpOptionName(I.getName(StrTable, PrefixesTable), Name, false) <
72 0;
73 }
74};
75} // namespace
76
77OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
78
79OptTable::OptTable(const char *StrTable, ArrayRef<unsigned> PrefixesTable,
80 ArrayRef<Info> OptionInfos, bool IgnoreCase)
81 : StrTable(StrTable), PrefixesTable(PrefixesTable),
82 OptionInfos(OptionInfos), IgnoreCase(IgnoreCase) {
83 // Explicitly zero initialize the error to work around a bug in array
84 // value-initialization on MinGW with gcc 4.3.5.
85
86 // Find start of normal options.
87 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
88 unsigned Kind = getInfo(i + 1).Kind;
89 if (Kind == Option::InputClass) {
90 assert(!InputOptionID && "Cannot have multiple input options!");
91 InputOptionID = getInfo(i + 1).ID;
92 } else if (Kind == Option::UnknownClass) {
93 assert(!UnknownOptionID && "Cannot have multiple unknown options!");
94 UnknownOptionID = getInfo(i + 1).ID;
95 } else if (Kind != Option::GroupClass) {
97 break;
98 }
99 }
100 assert(FirstSearchableIndex != 0 && "No searchable options?");
101
102#ifndef NDEBUG
103 // Check that everything after the first searchable option is a
104 // regular option class.
105 for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
106 Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
107 assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
108 Kind != Option::GroupClass) &&
109 "Special options should be defined first!");
110 }
111
112 // Check that options are in order.
113 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
114 if (!(OptNameLess(StrTable, PrefixesTable)(getInfo(i), getInfo(i + 1)))) {
115 getOption(i).dump();
116 getOption(i + 1).dump();
117 llvm_unreachable("Options are not in order!");
118 }
119 }
120#endif
121}
122
124 assert(PrefixChars.empty() && "rebuilding a non-empty prefix char");
125
126 // Build prefix chars.
127 for (StringRef Prefix : PrefixesUnion) {
128 for (char C : Prefix)
131 }
132}
133
134OptTable::~OptTable() = default;
135
137 unsigned id = Opt.getID();
138 if (id == 0)
139 return Option(nullptr, nullptr);
140 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
141 return Option(&getInfo(id), this);
142}
143
144static bool isInput(const ArrayRef<StringRef> &Prefixes, StringRef Arg) {
145 if (Arg == "-")
146 return true;
147 for (const StringRef &Prefix : Prefixes)
148 if (Arg.starts_with(Prefix))
149 return false;
150 return true;
151}
152
153/// \returns Matched size. 0 means no match.
154static unsigned matchOption(const char *StrTable,
155 ArrayRef<unsigned> PrefixesTable,
156 const OptTable::Info *I, StringRef Str,
157 bool IgnoreCase) {
158 StringRef Name = I->getName(StrTable, PrefixesTable);
159 for (unsigned PrefixOffset : I->getPrefixOffsets(PrefixesTable)) {
160 StringRef Prefix = &StrTable[PrefixOffset];
161 if (Str.starts_with(Prefix)) {
162 StringRef Rest = Str.substr(Prefix.size());
163 bool Matched = IgnoreCase ? Rest.starts_with_insensitive(Name)
164 : Rest.starts_with(Name);
165 if (Matched)
166 return Prefix.size() + Name.size();
167 }
168 }
169 return 0;
170}
171
172// Returns true if one of the Prefixes + In.Names matches Option
173static bool optionMatches(const char *StrTable,
174 ArrayRef<unsigned> PrefixesTable,
175 const OptTable::Info &In, StringRef Option) {
176 StringRef Name = In.getName(StrTable, PrefixesTable);
177 if (Option.consume_back(Name))
178 for (unsigned PrefixOffset : In.getPrefixOffsets(PrefixesTable))
179 if (Option == &StrTable[PrefixOffset])
180 return true;
181 return false;
182}
183
184// This function is for flag value completion.
185// Eg. When "-stdlib=" and "l" was passed to this function, it will return
186// appropiriate values for stdlib, which starts with l.
187std::vector<std::string>
189 // Search all options and return possible values.
190 for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
191 const Info &In = OptionInfos[I];
192 if (!In.Values || !optionMatches(StrTable, PrefixesTable, In, Option))
193 continue;
194
195 SmallVector<StringRef, 8> Candidates;
196 StringRef(In.Values).split(Candidates, ",", -1, false);
197
198 std::vector<std::string> Result;
199 for (StringRef Val : Candidates)
200 if (Val.starts_with(Arg) && Arg != Val)
201 Result.push_back(std::string(Val));
202 return Result;
203 }
204 return {};
205}
206
207std::vector<std::string>
209 unsigned int DisableFlags) const {
210 std::vector<std::string> Ret;
211 for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
212 const Info &In = OptionInfos[I];
213 if (In.hasNoPrefix() || (!In.HelpText && !In.GroupID))
214 continue;
215 if (!(In.Visibility & VisibilityMask))
216 continue;
217 if (In.Flags & DisableFlags)
218 continue;
219
220 StringRef Name = In.getName(StrTable, PrefixesTable);
221 for (unsigned PrefixOffset : In.getPrefixOffsets(PrefixesTable)) {
222 StringRef Prefix = &StrTable[PrefixOffset];
223 std::string S = (Twine(Prefix) + Name + "\t").str();
224 if (In.HelpText)
225 S += In.HelpText;
226 if (StringRef(S).starts_with(Cur) && S != std::string(Cur) + "\t")
227 Ret.push_back(S);
228 }
229 }
230 return Ret;
231}
232
233unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
234 Visibility VisibilityMask,
235 unsigned MinimumLength,
236 unsigned MaximumDistance) const {
237 return internalFindNearest(
238 Option, NearestString, MinimumLength, MaximumDistance,
239 [VisibilityMask](const Info &CandidateInfo) {
240 return (CandidateInfo.Visibility & VisibilityMask) == 0;
241 });
242}
243
244unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
245 unsigned FlagsToInclude, unsigned FlagsToExclude,
246 unsigned MinimumLength,
247 unsigned MaximumDistance) const {
248 return internalFindNearest(
249 Option, NearestString, MinimumLength, MaximumDistance,
250 [FlagsToInclude, FlagsToExclude](const Info &CandidateInfo) {
251 if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
252 return true;
253 if (CandidateInfo.Flags & FlagsToExclude)
254 return true;
255 return false;
256 });
257}
258
259unsigned OptTable::internalFindNearest(
260 StringRef Option, std::string &NearestString, unsigned MinimumLength,
261 unsigned MaximumDistance,
262 std::function<bool(const Info &)> ExcludeOption) const {
263 assert(!Option.empty());
264
265 // Consider each [option prefix + option name] pair as a candidate, finding
266 // the closest match.
267 unsigned BestDistance =
268 MaximumDistance == UINT_MAX ? UINT_MAX : MaximumDistance + 1;
269 SmallString<16> Candidate;
270 SmallString<16> NormalizedName;
271
272 for (const Info &CandidateInfo :
273 ArrayRef<Info>(OptionInfos).drop_front(FirstSearchableIndex)) {
274 StringRef CandidateName = CandidateInfo.getName(StrTable, PrefixesTable);
275
276 // We can eliminate some option prefix/name pairs as candidates right away:
277 // * Ignore option candidates with empty names, such as "--", or names
278 // that do not meet the minimum length.
279 if (CandidateName.size() < MinimumLength)
280 continue;
281
282 // Ignore options that are excluded via masks
283 if (ExcludeOption(CandidateInfo))
284 continue;
285
286 // * Ignore positional argument option candidates (which do not
287 // have prefixes).
288 if (CandidateInfo.hasNoPrefix())
289 continue;
290
291 // Now check if the candidate ends with a character commonly used when
292 // delimiting an option from its value, such as '=' or ':'. If it does,
293 // attempt to split the given option based on that delimiter.
294 char Last = CandidateName.back();
295 bool CandidateHasDelimiter = Last == '=' || Last == ':';
297 if (CandidateHasDelimiter) {
298 std::tie(NormalizedName, RHS) = Option.split(Last);
299 if (Option.find(Last) == NormalizedName.size())
300 NormalizedName += Last;
301 } else
302 NormalizedName = Option;
303
304 // Consider each possible prefix for each candidate to find the most
305 // appropriate one. For example, if a user asks for "--helm", suggest
306 // "--help" over "-help".
307 for (unsigned CandidatePrefixOffset :
308 CandidateInfo.getPrefixOffsets(PrefixesTable)) {
309 StringRef CandidatePrefix = &StrTable[CandidatePrefixOffset];
310 // If Candidate and NormalizedName have more than 'BestDistance'
311 // characters of difference, no need to compute the edit distance, it's
312 // going to be greater than BestDistance. Don't bother computing Candidate
313 // at all.
314 size_t CandidateSize = CandidatePrefix.size() + CandidateName.size(),
315 NormalizedSize = NormalizedName.size();
316 size_t AbsDiff = CandidateSize > NormalizedSize
317 ? CandidateSize - NormalizedSize
318 : NormalizedSize - CandidateSize;
319 if (AbsDiff > BestDistance) {
320 continue;
321 }
322 Candidate = CandidatePrefix;
323 Candidate += CandidateName;
324 unsigned Distance = StringRef(Candidate).edit_distance(
325 NormalizedName, /*AllowReplacements=*/true,
326 /*MaxEditDistance=*/BestDistance);
327 if (RHS.empty() && CandidateHasDelimiter) {
328 // The Candidate ends with a = or : delimiter, but the option passed in
329 // didn't contain the delimiter (or doesn't have anything after it).
330 // In that case, penalize the correction: `-nodefaultlibs` is more
331 // likely to be a spello for `-nodefaultlib` than `-nodefaultlib:` even
332 // though both have an unmodified editing distance of 1, since the
333 // latter would need an argument.
334 ++Distance;
335 }
336 if (Distance < BestDistance) {
337 BestDistance = Distance;
338 NearestString = (Candidate + RHS).str();
339 }
340 }
341 }
342 return BestDistance;
343}
344
345// Parse a single argument, return the new argument, and update Index. If
346// GroupedShortOptions is true, -a matches "-abc" and the argument in Args will
347// be updated to "-bc". This overload does not support VisibilityMask or case
348// insensitive options.
349std::unique_ptr<Arg> OptTable::parseOneArgGrouped(InputArgList &Args,
350 unsigned &Index) const {
351 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
352 // itself.
353 const char *CStr = Args.getArgString(Index);
354 StringRef Str(CStr);
355 if (isInput(PrefixesUnion, Str))
356 return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++, CStr);
357
358 const Info *End = OptionInfos.data() + OptionInfos.size();
359 StringRef Name = Str.ltrim(PrefixChars);
360 const Info *Start =
361 std::lower_bound(OptionInfos.data() + FirstSearchableIndex, End, Name,
362 OptNameLess(StrTable, PrefixesTable));
363 const Info *Fallback = nullptr;
364 unsigned Prev = Index;
365
366 // Search for the option which matches Str.
367 for (; Start != End; ++Start) {
368 unsigned ArgSize =
369 matchOption(StrTable, PrefixesTable, Start, Str, IgnoreCase);
370 if (!ArgSize)
371 continue;
372
373 Option Opt(Start, this);
374 if (std::unique_ptr<Arg> A =
375 Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
376 /*GroupedShortOption=*/false, Index))
377 return A;
378
379 // If Opt is a Flag of length 2 (e.g. "-a"), we know it is a prefix of
380 // the current argument (e.g. "-abc"). Match it as a fallback if no longer
381 // option (e.g. "-ab") exists.
382 if (ArgSize == 2 && Opt.getKind() == Option::FlagClass)
383 Fallback = Start;
384
385 // Otherwise, see if the argument is missing.
386 if (Prev != Index)
387 return nullptr;
388 }
389 if (Fallback) {
390 Option Opt(Fallback, this);
391 // Check that the last option isn't a flag wrongly given an argument.
392 if (Str[2] == '=')
393 return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
394 CStr);
395
396 if (std::unique_ptr<Arg> A = Opt.accept(
397 Args, Str.substr(0, 2), /*GroupedShortOption=*/true, Index)) {
398 Args.replaceArgString(Index, Twine('-') + Str.substr(2));
399 return A;
400 }
401 }
402
403 // In the case of an incorrect short option extract the character and move to
404 // the next one.
405 if (Str[1] != '-') {
406 CStr = Args.MakeArgString(Str.substr(0, 2));
407 Args.replaceArgString(Index, Twine('-') + Str.substr(2));
408 return std::make_unique<Arg>(getOption(UnknownOptionID), CStr, Index, CStr);
409 }
410
411 return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++, CStr);
412}
413
414std::unique_ptr<Arg> OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
415 Visibility VisibilityMask) const {
416 return internalParseOneArg(Args, Index, [VisibilityMask](const Option &Opt) {
417 return !Opt.hasVisibilityFlag(VisibilityMask);
418 });
419}
420
421std::unique_ptr<Arg> OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
422 unsigned FlagsToInclude,
423 unsigned FlagsToExclude) const {
424 return internalParseOneArg(
425 Args, Index, [FlagsToInclude, FlagsToExclude](const Option &Opt) {
426 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
427 return true;
428 if (Opt.hasFlag(FlagsToExclude))
429 return true;
430 return false;
431 });
432}
433
434std::unique_ptr<Arg> OptTable::internalParseOneArg(
435 const ArgList &Args, unsigned &Index,
436 std::function<bool(const Option &)> ExcludeOption) const {
437 unsigned Prev = Index;
438 StringRef Str = Args.getArgString(Index);
439
440 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
441 // itself.
442 if (isInput(PrefixesUnion, Str))
443 return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++,
444 Str.data());
445
446 const Info *Start = OptionInfos.data() + FirstSearchableIndex;
447 const Info *End = OptionInfos.data() + OptionInfos.size();
448 StringRef Name = Str.ltrim(PrefixChars);
449
450 // Search for the first next option which could be a prefix.
451 Start =
452 std::lower_bound(Start, End, Name, OptNameLess(StrTable, PrefixesTable));
453
454 // Options are stored in sorted order, with '\0' at the end of the
455 // alphabet. Since the only options which can accept a string must
456 // prefix it, we iteratively search for the next option which could
457 // be a prefix.
458 //
459 // FIXME: This is searching much more than necessary, but I am
460 // blanking on the simplest way to make it fast. We can solve this
461 // problem when we move to TableGen.
462 for (; Start != End; ++Start) {
463 unsigned ArgSize = 0;
464 // Scan for first option which is a proper prefix.
465 for (; Start != End; ++Start)
466 if ((ArgSize =
467 matchOption(StrTable, PrefixesTable, Start, Str, IgnoreCase)))
468 break;
469 if (Start == End)
470 break;
471
472 Option Opt(Start, this);
473
474 if (ExcludeOption(Opt))
475 continue;
476
477 // See if this option matches.
478 if (std::unique_ptr<Arg> A =
479 Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
480 /*GroupedShortOption=*/false, Index))
481 return A;
482
483 // Otherwise, see if this argument was missing values.
484 if (Prev != Index)
485 return nullptr;
486 }
487
488 // If we failed to find an option and this arg started with /, then it's
489 // probably an input path.
490 if (Str[0] == '/')
491 return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++,
492 Str.data());
493
494 return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
495 Str.data());
496}
497
499 unsigned &MissingArgIndex,
500 unsigned &MissingArgCount,
501 Visibility VisibilityMask) const {
502 return internalParseArgs(
503 Args, MissingArgIndex, MissingArgCount,
504 [VisibilityMask](const Option &Opt) {
505 return !Opt.hasVisibilityFlag(VisibilityMask);
506 });
507}
508
510 unsigned &MissingArgIndex,
511 unsigned &MissingArgCount,
512 unsigned FlagsToInclude,
513 unsigned FlagsToExclude) const {
514 return internalParseArgs(
515 Args, MissingArgIndex, MissingArgCount,
516 [FlagsToInclude, FlagsToExclude](const Option &Opt) {
517 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
518 return true;
519 if (Opt.hasFlag(FlagsToExclude))
520 return true;
521 return false;
522 });
523}
524
525InputArgList OptTable::internalParseArgs(
526 ArrayRef<const char *> ArgArr, unsigned &MissingArgIndex,
527 unsigned &MissingArgCount,
528 std::function<bool(const Option &)> ExcludeOption) const {
529 InputArgList Args(ArgArr.begin(), ArgArr.end());
530
531 // FIXME: Handle '@' args (or at least error on them).
532
533 MissingArgIndex = MissingArgCount = 0;
534 unsigned Index = 0, End = ArgArr.size();
535 while (Index < End) {
536 // Ingore nullptrs, they are response file's EOL markers
537 if (Args.getArgString(Index) == nullptr) {
538 ++Index;
539 continue;
540 }
541 // Ignore empty arguments (other things may still take them as arguments).
542 StringRef Str = Args.getArgString(Index);
543 if (Str == "") {
544 ++Index;
545 continue;
546 }
547
548 // In DashDashParsing mode, the first "--" stops option scanning and treats
549 // all subsequent arguments as positional.
550 if (DashDashParsing && Str == "--") {
551 while (++Index < End) {
552 Args.append(new Arg(getOption(InputOptionID), Str, Index,
553 Args.getArgString(Index)));
554 }
555 break;
556 }
557
558 unsigned Prev = Index;
559 std::unique_ptr<Arg> A = GroupedShortOptions
560 ? parseOneArgGrouped(Args, Index)
561 : internalParseOneArg(Args, Index, ExcludeOption);
562 assert((Index > Prev || GroupedShortOptions) &&
563 "Parser failed to consume argument.");
564
565 // Check for missing argument error.
566 if (!A) {
567 assert(Index >= End && "Unexpected parser error.");
568 assert(Index - Prev - 1 && "No missing arguments!");
569 MissingArgIndex = Prev;
570 MissingArgCount = Index - Prev - 1;
571 break;
572 }
573
574 Args.append(A.release());
575 }
576
577 return Args;
578}
579
580InputArgList OptTable::parseArgs(int Argc, char *const *Argv,
582 std::function<void(StringRef)> ErrorFn) const {
584 // The environment variable specifies initial options which can be overridden
585 // by commnad line options.
586 cl::expandResponseFiles(Argc, Argv, EnvVar, Saver, NewArgv);
587
588 unsigned MAI, MAC;
589 opt::InputArgList Args = ParseArgs(ArrayRef(NewArgv), MAI, MAC);
590 if (MAC)
591 ErrorFn((Twine(Args.getArgString(MAI)) + ": missing argument").str());
592
593 // For each unknwon option, call ErrorFn with a formatted error message. The
594 // message includes a suggested alternative option spelling if available.
595 std::string Nearest;
596 for (const opt::Arg *A : Args.filtered(Unknown)) {
597 std::string Spelling = A->getAsString(Args);
598 if (findNearest(Spelling, Nearest) > 1)
599 ErrorFn("unknown argument '" + Spelling + "'");
600 else
601 ErrorFn("unknown argument '" + Spelling + "', did you mean '" + Nearest +
602 "'?");
603 }
604 return Args;
605}
606
607static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
608 const Option O = Opts.getOption(Id);
609 std::string Name = O.getPrefixedName().str();
610
611 // Add metavar, if used.
612 switch (O.getKind()) {
614 llvm_unreachable("Invalid option with help text.");
615
617 if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
618 // For MultiArgs, metavar is full list of all argument names.
619 Name += ' ';
620 Name += MetaVarName;
621 }
622 else {
623 // For MultiArgs<N>, if metavar not supplied, print <value> N times.
624 for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
625 Name += " <value>";
626 }
627 }
628 break;
629
631 break;
632
634 break;
635
638 Name += ' ';
639 [[fallthrough]];
642 if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
643 Name += MetaVarName;
644 else
645 Name += "<value>";
646 break;
647 }
648
649 return Name;
650}
651
652namespace {
653struct OptionInfo {
654 std::string Name;
655 StringRef HelpText;
656};
657} // namespace
658
660 std::vector<OptionInfo> &OptionHelp) {
661 OS << Title << ":\n";
662
663 // Find the maximum option length.
664 unsigned OptionFieldWidth = 0;
665 for (const OptionInfo &Opt : OptionHelp) {
666 // Limit the amount of padding we are willing to give up for alignment.
667 unsigned Length = Opt.Name.size();
668 if (Length <= 23)
669 OptionFieldWidth = std::max(OptionFieldWidth, Length);
670 }
671
672 const unsigned InitialPad = 2;
673 for (const OptionInfo &Opt : OptionHelp) {
674 const std::string &Option = Opt.Name;
675 int Pad = OptionFieldWidth + InitialPad;
676 int FirstLinePad = OptionFieldWidth - int(Option.size());
677 OS.indent(InitialPad) << Option;
678
679 // Break on long option names.
680 if (FirstLinePad < 0) {
681 OS << "\n";
682 FirstLinePad = OptionFieldWidth + InitialPad;
683 Pad = FirstLinePad;
684 }
685
687 Opt.HelpText.split(Lines, '\n');
688 assert(Lines.size() && "Expected at least the first line in the help text");
689 auto *LinesIt = Lines.begin();
690 OS.indent(FirstLinePad + 1) << *LinesIt << '\n';
691 while (Lines.end() != ++LinesIt)
692 OS.indent(Pad + 1) << *LinesIt << '\n';
693 }
694}
695
696static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
697 unsigned GroupID = Opts.getOptionGroupID(Id);
698
699 // If not in a group, return the default help group.
700 if (!GroupID)
701 return "OPTIONS";
702
703 // Abuse the help text of the option groups to store the "help group"
704 // name.
705 //
706 // FIXME: Split out option groups.
707 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
708 return GroupHelp;
709
710 // Otherwise keep looking.
711 return getOptionHelpGroup(Opts, GroupID);
712}
713
714void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
715 bool ShowHidden, bool ShowAllAliases,
716 Visibility VisibilityMask) const {
717 return internalPrintHelp(
718 OS, Usage, Title, ShowHidden, ShowAllAliases,
719 [VisibilityMask](const Info &CandidateInfo) -> bool {
720 return (CandidateInfo.Visibility & VisibilityMask) == 0;
721 },
722 VisibilityMask);
723}
724
725void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
726 unsigned FlagsToInclude, unsigned FlagsToExclude,
727 bool ShowAllAliases) const {
728 bool ShowHidden = !(FlagsToExclude & HelpHidden);
729 FlagsToExclude &= ~HelpHidden;
730 return internalPrintHelp(
731 OS, Usage, Title, ShowHidden, ShowAllAliases,
732 [FlagsToInclude, FlagsToExclude](const Info &CandidateInfo) {
733 if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
734 return true;
735 if (CandidateInfo.Flags & FlagsToExclude)
736 return true;
737 return false;
738 },
739 Visibility(0));
740}
741
742void OptTable::internalPrintHelp(
743 raw_ostream &OS, const char *Usage, const char *Title, bool ShowHidden,
744 bool ShowAllAliases, std::function<bool(const Info &)> ExcludeOption,
745 Visibility VisibilityMask) const {
746 OS << "OVERVIEW: " << Title << "\n\n";
747 OS << "USAGE: " << Usage << "\n\n";
748
749 // Render help text into a map of group-name to a list of (option, help)
750 // pairs.
751 std::map<std::string, std::vector<OptionInfo>> GroupedOptionHelp;
752
753 for (unsigned Id = 1, e = getNumOptions() + 1; Id != e; ++Id) {
754 // FIXME: Split out option groups.
756 continue;
757
758 const Info &CandidateInfo = getInfo(Id);
759 if (!ShowHidden && (CandidateInfo.Flags & opt::HelpHidden))
760 continue;
761
762 if (ExcludeOption(CandidateInfo))
763 continue;
764
765 // If an alias doesn't have a help text, show a help text for the aliased
766 // option instead.
767 const char *HelpText = getOptionHelpText(Id, VisibilityMask);
768 if (!HelpText && ShowAllAliases) {
769 const Option Alias = getOption(Id).getAlias();
770 if (Alias.isValid())
771 HelpText = getOptionHelpText(Alias.getID(), VisibilityMask);
772 }
773
774 if (HelpText && (strlen(HelpText) != 0)) {
775 const char *HelpGroup = getOptionHelpGroup(*this, Id);
776 const std::string &OptName = getOptionHelpName(*this, Id);
777 GroupedOptionHelp[HelpGroup].push_back({OptName, HelpText});
778 }
779 }
780
781 for (auto& OptionGroup : GroupedOptionHelp) {
782 if (OptionGroup.first != GroupedOptionHelp.begin()->first)
783 OS << "\n";
784 PrintHelpOptionList(OS, OptionGroup.first, OptionGroup.second);
785 }
786
787 OS.flush();
788}
789
791 ArrayRef<unsigned> PrefixesTable,
792 ArrayRef<Info> OptionInfos, bool IgnoreCase)
793 : OptTable(StrTable, PrefixesTable, OptionInfos, IgnoreCase) {
794
795 std::set<StringRef> TmpPrefixesUnion;
796 for (auto const &Info : OptionInfos.drop_front(FirstSearchableIndex))
797 for (unsigned PrefixOffset : Info.getPrefixOffsets(PrefixesTable))
798 TmpPrefixesUnion.insert(StringRef(&StrTable[PrefixOffset]));
799 PrefixesUnion.append(TmpPrefixesUnion.begin(), TmpPrefixesUnion.end());
801}
Defines the llvm::Arg class for parsed arguments.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
std::string Name
bool End
Definition: ELF_riscv.cpp:480
#define I(x, y, z)
Definition: MD5.cpp:58
static const char * getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id)
Definition: OptTable.cpp:696
static bool optionMatches(const char *StrTable, ArrayRef< unsigned > PrefixesTable, const OptTable::Info &In, StringRef Option)
Definition: OptTable.cpp:173
static unsigned matchOption(const char *StrTable, ArrayRef< unsigned > PrefixesTable, const OptTable::Info *I, StringRef Str, bool IgnoreCase)
Definition: OptTable.cpp:154
static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id)
Definition: OptTable.cpp:607
static bool isInput(const ArrayRef< StringRef > &Prefixes, StringRef Arg)
Definition: OptTable.cpp:144
static void PrintHelpOptionList(raw_ostream &OS, StringRef Title, std::vector< OptionInfo > &OptionHelp)
Definition: OptTable.cpp:659
if(PassOpts->AAPipeline)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
Value * RHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition: ArrayRef.h:207
iterator end() const
Definition: ArrayRef.h:157
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:168
iterator begin() const
Definition: ArrayRef.h:156
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:700
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:265
bool starts_with_insensitive(StringRef Prefix) const
Check if this string starts with the given Prefix, ignoring case.
Definition: StringRef.cpp:46
unsigned edit_distance(StringRef Other, bool AllowReplacements=true, unsigned MaxEditDistance=0) const
Determine the edit distance between this string and another string.
Definition: StringRef.cpp:94
char back() const
back - Get the last character in the string.
Definition: StringRef.h:159
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:150
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition: StringSaver.h:21
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
ArgList - Ordered collection of driver arguments.
Definition: ArgList.h:116
A concrete instance of a particular driver option.
Definition: Arg.h:34
GenericOptTable(const char *StrTable, ArrayRef< unsigned > PrefixesTable, ArrayRef< Info > OptionInfos, bool IgnoreCase=false)
Definition: OptTable.cpp:790
OptSpecifier - Wrapper class for abstracting references to option IDs.
Definition: OptSpecifier.h:18
unsigned getID() const
Definition: OptSpecifier.h:29
Provide access to the Option info table.
Definition: OptTable.h:52
void buildPrefixChars()
Build (or rebuild) the PrefixChars member.
Definition: OptTable.cpp:123
InputArgList parseArgs(int Argc, char *const *Argv, OptSpecifier Unknown, StringSaver &Saver, std::function< void(StringRef)> ErrorFn) const
A convenience helper which handles optional initial options populated from an environment variable,...
Definition: OptTable.cpp:580
unsigned getOptionKind(OptSpecifier id) const
Get the kind of the given option.
Definition: OptTable.h:212
unsigned FirstSearchableIndex
The index of the first option which can be parsed (i.e., is not a special option like 'input' or 'unk...
Definition: OptTable.h:142
void printHelp(raw_ostream &OS, const char *Usage, const char *Title, bool ShowHidden=false, bool ShowAllAliases=false, Visibility VisibilityMask=Visibility()) const
Render the help text for an option table.
Definition: OptTable.cpp:714
const char * getOptionMetaVar(OptSpecifier id) const
Get the meta-variable name to use when describing this options values in the help text.
Definition: OptTable.h:241
std::unique_ptr< Arg > ParseOneArg(const ArgList &Args, unsigned &Index, Visibility VisibilityMask=Visibility()) const
Parse a single argument; returning the new argument and updating Index.
Definition: OptTable.cpp:414
unsigned findNearest(StringRef Option, std::string &NearestString, Visibility VisibilityMask=Visibility(), unsigned MinimumLength=4, unsigned MaximumDistance=UINT_MAX) const
Find the OptTable option that most closely matches the given string.
Definition: OptTable.cpp:233
SmallVector< StringRef > PrefixesUnion
The union of all option prefixes.
Definition: OptTable.h:146
const Option getOption(OptSpecifier Opt) const
Get the given Opt's Option instance, lazily creating it if necessary.
Definition: OptTable.cpp:136
const char * getOptionHelpText(OptSpecifier id) const
Get the help text to use to describe this option.
Definition: OptTable.h:222
OptTable(const char *StrTable, ArrayRef< unsigned > PrefixesTable, ArrayRef< Info > OptionInfos, bool IgnoreCase=false)
Initialize OptTable using Tablegen'ed OptionInfos.
Definition: OptTable.cpp:79
unsigned getOptionGroupID(OptSpecifier id) const
Get the group id for the given option.
Definition: OptTable.h:217
std::vector< std::string > suggestValueCompletions(StringRef Option, StringRef Arg) const
Find possible value for given flags.
Definition: OptTable.cpp:188
InputArgList ParseArgs(ArrayRef< const char * > Args, unsigned &MissingArgIndex, unsigned &MissingArgCount, Visibility VisibilityMask=Visibility()) const
Parse an list of arguments into an InputArgList.
Definition: OptTable.cpp:498
SmallString< 8 > PrefixChars
The union of the first element of all option prefixes.
Definition: OptTable.h:149
unsigned getNumOptions() const
Return the total number of option classes.
Definition: OptTable.h:180
std::vector< std::string > findByPrefix(StringRef Cur, Visibility VisibilityMask, unsigned int DisableFlags) const
Find flags from OptTable which starts with Cur.
Definition: OptTable.cpp:208
Option - Abstract representation for a single form of driver argument.
Definition: Option.h:54
const Option getAlias() const
Definition: Option.h:113
void dump() const
Definition: Option.cpp:93
bool hasFlag(unsigned Val) const
Test if this option has the flag Val.
Definition: Option.h:187
@ JoinedOrSeparateClass
Definition: Option.h:68
@ RemainingArgsClass
Definition: Option.h:64
@ JoinedAndSeparateClass
Definition: Option.h:69
@ RemainingArgsJoinedClass
Definition: Option.h:65
bool hasVisibilityFlag(unsigned Val) const
Test if this option has the visibility flag Val.
Definition: Option.h:192
bool isValid() const
Definition: Option.h:86
unsigned getID() const
Definition: Option.h:90
Helper for overload resolution while transitioning from FlagsToInclude/FlagsToExclude APIs to Visibil...
Definition: OptTable.h:35
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
bool expandResponseFiles(int Argc, const char *const *Argv, const char *EnvVar, SmallVectorImpl< const char * > &NewArgv)
A convenience helper which concatenates the options specified by the environment variable EnvVar and ...
Definition: Arg.h:26
@ HelpHidden
Definition: Option.h:33
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Length
Definition: DWP.cpp:480
int StrCmpOptionName(StringRef A, StringRef B, bool FallbackCaseSensitive=true)
int StrCmpOptionPrefixes(ArrayRef< StringRef > APrefixes, ArrayRef< StringRef > BPrefixes)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1903
Entry for a single option instance in the option data table.
Definition: OptTable.h:55
unsigned int Visibility
Definition: OptTable.h:75
unsigned int Flags
Definition: OptTable.h:74
ArrayRef< unsigned > getPrefixOffsets(ArrayRef< unsigned > PrefixesTable) const
Definition: OptTable.h:88
unsigned char Kind
Definition: OptTable.h:72