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