xref: /freebsd/contrib/llvm-project/llvm/lib/Option/OptTable.cpp (revision 0ad011ececb978e22a9bff2acf76633b094f1ff6)
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 
9 #include "llvm/Option/OptTable.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/StringRef.h"
12 #include "llvm/Option/Arg.h"
13 #include "llvm/Option/ArgList.h"
14 #include "llvm/Option/OptSpecifier.h"
15 #include "llvm/Option/Option.h"
16 #include "llvm/Support/CommandLine.h" // for expandResponseFiles
17 #include "llvm/Support/Compiler.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include <algorithm>
21 #include <cassert>
22 #include <cctype>
23 #include <cstring>
24 #include <map>
25 #include <set>
26 #include <string>
27 #include <utility>
28 #include <vector>
29 
30 using namespace llvm;
31 using namespace llvm::opt;
32 
33 namespace llvm {
34 namespace opt {
35 
36 // Ordering on Info. The ordering is *almost* case-insensitive lexicographic,
37 // with an exception. '\0' comes at the end of the alphabet instead of the
38 // beginning (thus options precede any other options which prefix them).
39 static int StrCmpOptionNameIgnoreCase(StringRef A, StringRef B) {
40   size_t MinSize = std::min(A.size(), B.size());
41   if (int Res = A.substr(0, MinSize).compare_insensitive(B.substr(0, MinSize)))
42     return Res;
43 
44   if (A.size() == B.size())
45     return 0;
46 
47   return (A.size() == MinSize) ? 1 /* A is a prefix of B. */
48                                : -1 /* B is a prefix of A */;
49 }
50 
51 #ifndef NDEBUG
52 static int StrCmpOptionName(StringRef A, StringRef B) {
53   if (int N = StrCmpOptionNameIgnoreCase(A, B))
54     return N;
55   return A.compare(B);
56 }
57 
58 static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
59   if (&A == &B)
60     return false;
61 
62   if (int N = StrCmpOptionName(A.Name, B.Name))
63     return N < 0;
64 
65   for (size_t I = 0, K = std::min(A.Prefixes.size(), B.Prefixes.size()); I != K;
66        ++I)
67     if (int N = StrCmpOptionName(A.Prefixes[I], B.Prefixes[I]))
68       return N < 0;
69 
70   // Names are the same, check that classes are in order; exactly one
71   // should be joined, and it should succeed the other.
72   assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
73          "Unexpected classes for options with same name.");
74   return B.Kind == Option::JoinedClass;
75 }
76 #endif
77 
78 // Support lower_bound between info and an option name.
79 static inline bool operator<(const OptTable::Info &I, StringRef Name) {
80   return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
81 }
82 
83 } // end namespace opt
84 } // end namespace llvm
85 
86 OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
87 
88 OptTable::OptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase)
89     : OptionInfos(OptionInfos), IgnoreCase(IgnoreCase) {
90   // Explicitly zero initialize the error to work around a bug in array
91   // value-initialization on MinGW with gcc 4.3.5.
92 
93   // Find start of normal options.
94   for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
95     unsigned Kind = getInfo(i + 1).Kind;
96     if (Kind == Option::InputClass) {
97       assert(!InputOptionID && "Cannot have multiple input options!");
98       InputOptionID = getInfo(i + 1).ID;
99     } else if (Kind == Option::UnknownClass) {
100       assert(!UnknownOptionID && "Cannot have multiple unknown options!");
101       UnknownOptionID = getInfo(i + 1).ID;
102     } else if (Kind != Option::GroupClass) {
103       FirstSearchableIndex = i;
104       break;
105     }
106   }
107   assert(FirstSearchableIndex != 0 && "No searchable options?");
108 
109 #ifndef NDEBUG
110   // Check that everything after the first searchable option is a
111   // regular option class.
112   for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
113     Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
114     assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
115             Kind != Option::GroupClass) &&
116            "Special options should be defined first!");
117   }
118 
119   // Check that options are in order.
120   for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
121     if (!(getInfo(i) < getInfo(i + 1))) {
122       getOption(i).dump();
123       getOption(i + 1).dump();
124       llvm_unreachable("Options are not in order!");
125     }
126   }
127 #endif
128 }
129 
130 void OptTable::buildPrefixChars() {
131   assert(PrefixChars.empty() && "rebuilding a non-empty prefix char");
132 
133   // Build prefix chars.
134   for (const StringLiteral &Prefix : getPrefixesUnion()) {
135     for (char C : Prefix)
136       if (!is_contained(PrefixChars, C))
137         PrefixChars.push_back(C);
138   }
139 }
140 
141 OptTable::~OptTable() = default;
142 
143 const Option OptTable::getOption(OptSpecifier Opt) const {
144   unsigned id = Opt.getID();
145   if (id == 0)
146     return Option(nullptr, nullptr);
147   assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
148   return Option(&getInfo(id), this);
149 }
150 
151 static bool isInput(const ArrayRef<StringLiteral> &Prefixes, StringRef Arg) {
152   if (Arg == "-")
153     return true;
154   for (const StringRef &Prefix : Prefixes)
155     if (Arg.startswith(Prefix))
156       return false;
157   return true;
158 }
159 
160 /// \returns Matched size. 0 means no match.
161 static unsigned matchOption(const OptTable::Info *I, StringRef Str,
162                             bool IgnoreCase) {
163   for (auto Prefix : I->Prefixes) {
164     if (Str.startswith(Prefix)) {
165       StringRef Rest = Str.substr(Prefix.size());
166       bool Matched = IgnoreCase ? Rest.starts_with_insensitive(I->Name)
167                                 : Rest.startswith(I->Name);
168       if (Matched)
169         return Prefix.size() + StringRef(I->Name).size();
170     }
171   }
172   return 0;
173 }
174 
175 // Returns true if one of the Prefixes + In.Names matches Option
176 static bool optionMatches(const OptTable::Info &In, StringRef Option) {
177   for (auto Prefix : In.Prefixes)
178     if (Option.endswith(In.Name))
179       if (Option.slice(0, Option.size() - In.Name.size()) == Prefix)
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.
187 std::vector<std::string>
188 OptTable::suggestValueCompletions(StringRef Option, StringRef Arg) const {
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(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.startswith(Arg) && Arg.compare(Val))
201         Result.push_back(std::string(Val));
202     return Result;
203   }
204   return {};
205 }
206 
207 std::vector<std::string>
208 OptTable::findByPrefix(StringRef Cur, unsigned int DisableFlags) const {
209   std::vector<std::string> Ret;
210   for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
211     const Info &In = OptionInfos[I];
212     if (In.Prefixes.empty() || (!In.HelpText && !In.GroupID))
213       continue;
214     if (In.Flags & DisableFlags)
215       continue;
216 
217     for (auto Prefix : In.Prefixes) {
218       std::string S = (Prefix + In.Name + "\t").str();
219       if (In.HelpText)
220         S += In.HelpText;
221       if (StringRef(S).startswith(Cur) && S != std::string(Cur) + "\t")
222         Ret.push_back(S);
223     }
224   }
225   return Ret;
226 }
227 
228 unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
229                                unsigned FlagsToInclude, unsigned FlagsToExclude,
230                                unsigned MinimumLength,
231                                unsigned MaximumDistance) const {
232   assert(!Option.empty());
233 
234   // Consider each [option prefix + option name] pair as a candidate, finding
235   // the closest match.
236   unsigned BestDistance =
237       MaximumDistance == UINT_MAX ? UINT_MAX : MaximumDistance + 1;
238   SmallString<16> Candidate;
239   SmallString<16> NormalizedName;
240 
241   for (const Info &CandidateInfo :
242        ArrayRef<Info>(OptionInfos).drop_front(FirstSearchableIndex)) {
243     StringRef CandidateName = CandidateInfo.Name;
244 
245     // We can eliminate some option prefix/name pairs as candidates right away:
246     // * Ignore option candidates with empty names, such as "--", or names
247     //   that do not meet the minimum length.
248     if (CandidateName.size() < MinimumLength)
249       continue;
250 
251     // * If FlagsToInclude were specified, ignore options that don't include
252     //   those flags.
253     if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
254       continue;
255     // * Ignore options that contain the FlagsToExclude.
256     if (CandidateInfo.Flags & FlagsToExclude)
257       continue;
258 
259     // * Ignore positional argument option candidates (which do not
260     //   have prefixes).
261     if (CandidateInfo.Prefixes.empty())
262       continue;
263 
264     // Now check if the candidate ends with a character commonly used when
265     // delimiting an option from its value, such as '=' or ':'. If it does,
266     // attempt to split the given option based on that delimiter.
267     char Last = CandidateName.back();
268     bool CandidateHasDelimiter = Last == '=' || Last == ':';
269     StringRef RHS;
270     if (CandidateHasDelimiter) {
271       std::tie(NormalizedName, RHS) = Option.split(Last);
272       if (Option.find(Last) == NormalizedName.size())
273         NormalizedName += Last;
274     } else
275       NormalizedName = Option;
276 
277     // Consider each possible prefix for each candidate to find the most
278     // appropriate one. For example, if a user asks for "--helm", suggest
279     // "--help" over "-help".
280     for (auto CandidatePrefix : CandidateInfo.Prefixes) {
281       // If Candidate and NormalizedName have more than 'BestDistance'
282       // characters of difference, no need to compute the edit distance, it's
283       // going to be greater than BestDistance. Don't bother computing Candidate
284       // at all.
285       size_t CandidateSize = CandidatePrefix.size() + CandidateName.size(),
286              NormalizedSize = NormalizedName.size();
287       size_t AbsDiff = CandidateSize > NormalizedSize
288                            ? CandidateSize - NormalizedSize
289                            : NormalizedSize - CandidateSize;
290       if (AbsDiff > BestDistance) {
291         continue;
292       }
293       Candidate = CandidatePrefix;
294       Candidate += CandidateName;
295       unsigned Distance = StringRef(Candidate).edit_distance(
296           NormalizedName, /*AllowReplacements=*/true,
297           /*MaxEditDistance=*/BestDistance);
298       if (RHS.empty() && CandidateHasDelimiter) {
299         // The Candidate ends with a = or : delimiter, but the option passed in
300         // didn't contain the delimiter (or doesn't have anything after it).
301         // In that case, penalize the correction: `-nodefaultlibs` is more
302         // likely to be a spello for `-nodefaultlib` than `-nodefaultlib:` even
303         // though both have an unmodified editing distance of 1, since the
304         // latter would need an argument.
305         ++Distance;
306       }
307       if (Distance < BestDistance) {
308         BestDistance = Distance;
309         NearestString = (Candidate + RHS).str();
310       }
311     }
312   }
313   return BestDistance;
314 }
315 
316 // Parse a single argument, return the new argument, and update Index. If
317 // GroupedShortOptions is true, -a matches "-abc" and the argument in Args will
318 // be updated to "-bc". This overload does not support
319 // FlagsToInclude/FlagsToExclude or case insensitive options.
320 std::unique_ptr<Arg> OptTable::parseOneArgGrouped(InputArgList &Args,
321                                                   unsigned &Index) const {
322   // Anything that doesn't start with PrefixesUnion is an input, as is '-'
323   // itself.
324   const char *CStr = Args.getArgString(Index);
325   StringRef Str(CStr);
326   if (isInput(getPrefixesUnion(), Str))
327     return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++, CStr);
328 
329   const Info *End = OptionInfos.data() + OptionInfos.size();
330   StringRef Name = Str.ltrim(PrefixChars);
331   const Info *Start =
332       std::lower_bound(OptionInfos.data() + FirstSearchableIndex, End, Name);
333   const Info *Fallback = nullptr;
334   unsigned Prev = Index;
335 
336   // Search for the option which matches Str.
337   for (; Start != End; ++Start) {
338     unsigned ArgSize = matchOption(Start, Str, IgnoreCase);
339     if (!ArgSize)
340       continue;
341 
342     Option Opt(Start, this);
343     if (std::unique_ptr<Arg> A =
344             Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
345                        /*GroupedShortOption=*/false, Index))
346       return A;
347 
348     // If Opt is a Flag of length 2 (e.g. "-a"), we know it is a prefix of
349     // the current argument (e.g. "-abc"). Match it as a fallback if no longer
350     // option (e.g. "-ab") exists.
351     if (ArgSize == 2 && Opt.getKind() == Option::FlagClass)
352       Fallback = Start;
353 
354     // Otherwise, see if the argument is missing.
355     if (Prev != Index)
356       return nullptr;
357   }
358   if (Fallback) {
359     Option Opt(Fallback, this);
360     // Check that the last option isn't a flag wrongly given an argument.
361     if (Str[2] == '=')
362       return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
363                                    CStr);
364 
365     if (std::unique_ptr<Arg> A = Opt.accept(
366             Args, Str.substr(0, 2), /*GroupedShortOption=*/true, Index)) {
367       Args.replaceArgString(Index, Twine('-') + Str.substr(2));
368       return A;
369     }
370   }
371 
372   // In the case of an incorrect short option extract the character and move to
373   // the next one.
374   if (Str[1] != '-') {
375     CStr = Args.MakeArgString(Str.substr(0, 2));
376     Args.replaceArgString(Index, Twine('-') + Str.substr(2));
377     return std::make_unique<Arg>(getOption(UnknownOptionID), CStr, Index, CStr);
378   }
379 
380   return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++, CStr);
381 }
382 
383 std::unique_ptr<Arg> OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
384                                            unsigned FlagsToInclude,
385                                            unsigned FlagsToExclude) const {
386   unsigned Prev = Index;
387   StringRef Str = Args.getArgString(Index);
388 
389   // Anything that doesn't start with PrefixesUnion is an input, as is '-'
390   // itself.
391   if (isInput(getPrefixesUnion(), Str))
392     return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++,
393                                  Str.data());
394 
395   const Info *Start = OptionInfos.data() + FirstSearchableIndex;
396   const Info *End = OptionInfos.data() + OptionInfos.size();
397   StringRef Name = Str.ltrim(PrefixChars);
398 
399   // Search for the first next option which could be a prefix.
400   Start = std::lower_bound(Start, End, Name);
401 
402   // Options are stored in sorted order, with '\0' at the end of the
403   // alphabet. Since the only options which can accept a string must
404   // prefix it, we iteratively search for the next option which could
405   // be a prefix.
406   //
407   // FIXME: This is searching much more than necessary, but I am
408   // blanking on the simplest way to make it fast. We can solve this
409   // problem when we move to TableGen.
410   for (; Start != End; ++Start) {
411     unsigned ArgSize = 0;
412     // Scan for first option which is a proper prefix.
413     for (; Start != End; ++Start)
414       if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
415         break;
416     if (Start == End)
417       break;
418 
419     Option Opt(Start, this);
420 
421     if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
422       continue;
423     if (Opt.hasFlag(FlagsToExclude))
424       continue;
425 
426     // See if this option matches.
427     if (std::unique_ptr<Arg> A =
428             Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
429                        /*GroupedShortOption=*/false, Index))
430       return A;
431 
432     // Otherwise, see if this argument was missing values.
433     if (Prev != Index)
434       return nullptr;
435   }
436 
437   // If we failed to find an option and this arg started with /, then it's
438   // probably an input path.
439   if (Str[0] == '/')
440     return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++,
441                                  Str.data());
442 
443   return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
444                                Str.data());
445 }
446 
447 InputArgList OptTable::ParseArgs(ArrayRef<const char *> ArgArr,
448                                  unsigned &MissingArgIndex,
449                                  unsigned &MissingArgCount,
450                                  unsigned FlagsToInclude,
451                                  unsigned FlagsToExclude) const {
452   InputArgList Args(ArgArr.begin(), ArgArr.end());
453 
454   // FIXME: Handle '@' args (or at least error on them).
455 
456   MissingArgIndex = MissingArgCount = 0;
457   unsigned Index = 0, End = ArgArr.size();
458   while (Index < End) {
459     // Ingore nullptrs, they are response file's EOL markers
460     if (Args.getArgString(Index) == nullptr) {
461       ++Index;
462       continue;
463     }
464     // Ignore empty arguments (other things may still take them as arguments).
465     StringRef Str = Args.getArgString(Index);
466     if (Str == "") {
467       ++Index;
468       continue;
469     }
470 
471     // In DashDashParsing mode, the first "--" stops option scanning and treats
472     // all subsequent arguments as positional.
473     if (DashDashParsing && Str == "--") {
474       while (++Index < End) {
475         Args.append(new Arg(getOption(InputOptionID), Str, Index,
476                             Args.getArgString(Index)));
477       }
478       break;
479     }
480 
481     unsigned Prev = Index;
482     std::unique_ptr<Arg> A = GroupedShortOptions
483                  ? parseOneArgGrouped(Args, Index)
484                  : ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude);
485     assert((Index > Prev || GroupedShortOptions) &&
486            "Parser failed to consume argument.");
487 
488     // Check for missing argument error.
489     if (!A) {
490       assert(Index >= End && "Unexpected parser error.");
491       assert(Index - Prev - 1 && "No missing arguments!");
492       MissingArgIndex = Prev;
493       MissingArgCount = Index - Prev - 1;
494       break;
495     }
496 
497     Args.append(A.release());
498   }
499 
500   return Args;
501 }
502 
503 InputArgList OptTable::parseArgs(int Argc, char *const *Argv,
504                                  OptSpecifier Unknown, StringSaver &Saver,
505                                  function_ref<void(StringRef)> ErrorFn) const {
506   SmallVector<const char *, 0> NewArgv;
507   // The environment variable specifies initial options which can be overridden
508   // by commnad line options.
509   cl::expandResponseFiles(Argc, Argv, EnvVar, Saver, NewArgv);
510 
511   unsigned MAI, MAC;
512   opt::InputArgList Args = ParseArgs(ArrayRef(NewArgv), MAI, MAC);
513   if (MAC)
514     ErrorFn((Twine(Args.getArgString(MAI)) + ": missing argument").str());
515 
516   // For each unknwon option, call ErrorFn with a formatted error message. The
517   // message includes a suggested alternative option spelling if available.
518   std::string Nearest;
519   for (const opt::Arg *A : Args.filtered(Unknown)) {
520     std::string Spelling = A->getAsString(Args);
521     if (findNearest(Spelling, Nearest) > 1)
522       ErrorFn("unknown argument '" + Spelling + "'");
523     else
524       ErrorFn("unknown argument '" + Spelling + "', did you mean '" + Nearest +
525               "'?");
526   }
527   return Args;
528 }
529 
530 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
531   const Option O = Opts.getOption(Id);
532   std::string Name = O.getPrefixedName();
533 
534   // Add metavar, if used.
535   switch (O.getKind()) {
536   case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
537     llvm_unreachable("Invalid option with help text.");
538 
539   case Option::MultiArgClass:
540     if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
541       // For MultiArgs, metavar is full list of all argument names.
542       Name += ' ';
543       Name += MetaVarName;
544     }
545     else {
546       // For MultiArgs<N>, if metavar not supplied, print <value> N times.
547       for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
548         Name += " <value>";
549       }
550     }
551     break;
552 
553   case Option::FlagClass:
554     break;
555 
556   case Option::ValuesClass:
557     break;
558 
559   case Option::SeparateClass: case Option::JoinedOrSeparateClass:
560   case Option::RemainingArgsClass: case Option::RemainingArgsJoinedClass:
561     Name += ' ';
562     [[fallthrough]];
563   case Option::JoinedClass: case Option::CommaJoinedClass:
564   case Option::JoinedAndSeparateClass:
565     if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
566       Name += MetaVarName;
567     else
568       Name += "<value>";
569     break;
570   }
571 
572   return Name;
573 }
574 
575 namespace {
576 struct OptionInfo {
577   std::string Name;
578   StringRef HelpText;
579 };
580 } // namespace
581 
582 static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
583                                 std::vector<OptionInfo> &OptionHelp) {
584   OS << Title << ":\n";
585 
586   // Find the maximum option length.
587   unsigned OptionFieldWidth = 0;
588   for (const OptionInfo &Opt : OptionHelp) {
589     // Limit the amount of padding we are willing to give up for alignment.
590     unsigned Length = Opt.Name.size();
591     if (Length <= 23)
592       OptionFieldWidth = std::max(OptionFieldWidth, Length);
593   }
594 
595   const unsigned InitialPad = 2;
596   for (const OptionInfo &Opt : OptionHelp) {
597     const std::string &Option = Opt.Name;
598     int Pad = OptionFieldWidth - int(Option.size());
599     OS.indent(InitialPad) << Option;
600 
601     // Break on long option names.
602     if (Pad < 0) {
603       OS << "\n";
604       Pad = OptionFieldWidth + InitialPad;
605     }
606     OS.indent(Pad + 1) << Opt.HelpText << '\n';
607   }
608 }
609 
610 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
611   unsigned GroupID = Opts.getOptionGroupID(Id);
612 
613   // If not in a group, return the default help group.
614   if (!GroupID)
615     return "OPTIONS";
616 
617   // Abuse the help text of the option groups to store the "help group"
618   // name.
619   //
620   // FIXME: Split out option groups.
621   if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
622     return GroupHelp;
623 
624   // Otherwise keep looking.
625   return getOptionHelpGroup(Opts, GroupID);
626 }
627 
628 void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
629                          bool ShowHidden, bool ShowAllAliases) const {
630   printHelp(OS, Usage, Title, /*Include*/ 0, /*Exclude*/
631             (ShowHidden ? 0 : HelpHidden), ShowAllAliases);
632 }
633 
634 void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
635                          unsigned FlagsToInclude, unsigned FlagsToExclude,
636                          bool ShowAllAliases) const {
637   OS << "OVERVIEW: " << Title << "\n\n";
638   OS << "USAGE: " << Usage << "\n\n";
639 
640   // Render help text into a map of group-name to a list of (option, help)
641   // pairs.
642   std::map<std::string, std::vector<OptionInfo>> GroupedOptionHelp;
643 
644   for (unsigned Id = 1, e = getNumOptions() + 1; Id != e; ++Id) {
645     // FIXME: Split out option groups.
646     if (getOptionKind(Id) == Option::GroupClass)
647       continue;
648 
649     unsigned Flags = getInfo(Id).Flags;
650     if (FlagsToInclude && !(Flags & FlagsToInclude))
651       continue;
652     if (Flags & FlagsToExclude)
653       continue;
654 
655     // If an alias doesn't have a help text, show a help text for the aliased
656     // option instead.
657     const char *HelpText = getOptionHelpText(Id);
658     if (!HelpText && ShowAllAliases) {
659       const Option Alias = getOption(Id).getAlias();
660       if (Alias.isValid())
661         HelpText = getOptionHelpText(Alias.getID());
662     }
663 
664     if (HelpText && (strlen(HelpText) != 0)) {
665       const char *HelpGroup = getOptionHelpGroup(*this, Id);
666       const std::string &OptName = getOptionHelpName(*this, Id);
667       GroupedOptionHelp[HelpGroup].push_back({OptName, HelpText});
668     }
669   }
670 
671   for (auto& OptionGroup : GroupedOptionHelp) {
672     if (OptionGroup.first != GroupedOptionHelp.begin()->first)
673       OS << "\n";
674     PrintHelpOptionList(OS, OptionGroup.first, OptionGroup.second);
675   }
676 
677   OS.flush();
678 }
679 
680 GenericOptTable::GenericOptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase)
681     : OptTable(OptionInfos, IgnoreCase) {
682 
683   std::set<StringLiteral> TmpPrefixesUnion;
684   for (auto const &Info : OptionInfos.drop_front(FirstSearchableIndex))
685     TmpPrefixesUnion.insert(Info.Prefixes.begin(), Info.Prefixes.end());
686   PrefixesUnionBuffer.append(TmpPrefixesUnion.begin(), TmpPrefixesUnion.end());
687   buildPrefixChars();
688 }
689