xref: /freebsd/contrib/llvm-project/llvm/lib/Support/CommandLine.cpp (revision fe75646a0234a261c0013bf1840fdac4acaf0cec)
1 //===-- CommandLine.cpp - Command line parser 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 // This class implements a command line argument processor that is useful when
10 // creating a tool.  It provides a simple, minimalistic interface that is easily
11 // extensible and supports nonlocal (library) command line options.
12 //
13 // Note that rather than trying to figure out what this code does, you could try
14 // reading the library documentation located in docs/CommandLine.html
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/Support/CommandLine.h"
19 
20 #include "DebugOptions.h"
21 
22 #include "llvm-c/Support.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/STLFunctionalExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/Config/config.h"
32 #include "llvm/Support/ConvertUTF.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Error.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Process.h"
41 #include "llvm/Support/StringSaver.h"
42 #include "llvm/Support/VirtualFileSystem.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include <cstdlib>
45 #include <optional>
46 #include <string>
47 using namespace llvm;
48 using namespace cl;
49 
50 #define DEBUG_TYPE "commandline"
51 
52 //===----------------------------------------------------------------------===//
53 // Template instantiations and anchors.
54 //
55 namespace llvm {
56 namespace cl {
57 template class basic_parser<bool>;
58 template class basic_parser<boolOrDefault>;
59 template class basic_parser<int>;
60 template class basic_parser<long>;
61 template class basic_parser<long long>;
62 template class basic_parser<unsigned>;
63 template class basic_parser<unsigned long>;
64 template class basic_parser<unsigned long long>;
65 template class basic_parser<double>;
66 template class basic_parser<float>;
67 template class basic_parser<std::string>;
68 template class basic_parser<char>;
69 
70 template class opt<unsigned>;
71 template class opt<int>;
72 template class opt<std::string>;
73 template class opt<char>;
74 template class opt<bool>;
75 } // namespace cl
76 } // namespace llvm
77 
78 // Pin the vtables to this file.
79 void GenericOptionValue::anchor() {}
80 void OptionValue<boolOrDefault>::anchor() {}
81 void OptionValue<std::string>::anchor() {}
82 void Option::anchor() {}
83 void basic_parser_impl::anchor() {}
84 void parser<bool>::anchor() {}
85 void parser<boolOrDefault>::anchor() {}
86 void parser<int>::anchor() {}
87 void parser<long>::anchor() {}
88 void parser<long long>::anchor() {}
89 void parser<unsigned>::anchor() {}
90 void parser<unsigned long>::anchor() {}
91 void parser<unsigned long long>::anchor() {}
92 void parser<double>::anchor() {}
93 void parser<float>::anchor() {}
94 void parser<std::string>::anchor() {}
95 void parser<char>::anchor() {}
96 
97 //===----------------------------------------------------------------------===//
98 
99 const static size_t DefaultPad = 2;
100 
101 static StringRef ArgPrefix = "-";
102 static StringRef ArgPrefixLong = "--";
103 static StringRef ArgHelpPrefix = " - ";
104 
105 static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad = DefaultPad) {
106   size_t Len = ArgName.size();
107   if (Len == 1)
108     return Len + Pad + ArgPrefix.size() + ArgHelpPrefix.size();
109   return Len + Pad + ArgPrefixLong.size() + ArgHelpPrefix.size();
110 }
111 
112 static SmallString<8> argPrefix(StringRef ArgName, size_t Pad = DefaultPad) {
113   SmallString<8> Prefix;
114   for (size_t I = 0; I < Pad; ++I) {
115     Prefix.push_back(' ');
116   }
117   Prefix.append(ArgName.size() > 1 ? ArgPrefixLong : ArgPrefix);
118   return Prefix;
119 }
120 
121 // Option predicates...
122 static inline bool isGrouping(const Option *O) {
123   return O->getMiscFlags() & cl::Grouping;
124 }
125 static inline bool isPrefixedOrGrouping(const Option *O) {
126   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
127          O->getFormattingFlag() == cl::AlwaysPrefix;
128 }
129 
130 
131 namespace {
132 
133 class PrintArg {
134   StringRef ArgName;
135   size_t Pad;
136 public:
137   PrintArg(StringRef ArgName, size_t Pad = DefaultPad) : ArgName(ArgName), Pad(Pad) {}
138   friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg &);
139 };
140 
141 raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
142   OS << argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
143   return OS;
144 }
145 
146 class CommandLineParser {
147 public:
148   // Globals for name and overview of program.  Program name is not a string to
149   // avoid static ctor/dtor issues.
150   std::string ProgramName;
151   StringRef ProgramOverview;
152 
153   // This collects additional help to be printed.
154   std::vector<StringRef> MoreHelp;
155 
156   // This collects Options added with the cl::DefaultOption flag. Since they can
157   // be overridden, they are not added to the appropriate SubCommands until
158   // ParseCommandLineOptions actually runs.
159   SmallVector<Option*, 4> DefaultOptions;
160 
161   // This collects the different option categories that have been registered.
162   SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
163 
164   // This collects the different subcommands that have been registered.
165   SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
166 
167   CommandLineParser() {
168     registerSubCommand(&SubCommand::getTopLevel());
169     registerSubCommand(&SubCommand::getAll());
170   }
171 
172   void ResetAllOptionOccurrences();
173 
174   bool ParseCommandLineOptions(int argc, const char *const *argv,
175                                StringRef Overview, raw_ostream *Errs = nullptr,
176                                bool LongOptionsUseDoubleDash = false);
177 
178   void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
179     if (Opt.hasArgStr())
180       return;
181     if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
182       errs() << ProgramName << ": CommandLine Error: Option '" << Name
183              << "' registered more than once!\n";
184       report_fatal_error("inconsistency in registered CommandLine options");
185     }
186 
187     // If we're adding this to all sub-commands, add it to the ones that have
188     // already been registered.
189     if (SC == &SubCommand::getAll()) {
190       for (auto *Sub : RegisteredSubCommands) {
191         if (SC == Sub)
192           continue;
193         addLiteralOption(Opt, Sub, Name);
194       }
195     }
196   }
197 
198   void addLiteralOption(Option &Opt, StringRef Name) {
199     if (Opt.Subs.empty())
200       addLiteralOption(Opt, &SubCommand::getTopLevel(), Name);
201     else {
202       for (auto *SC : Opt.Subs)
203         addLiteralOption(Opt, SC, Name);
204     }
205   }
206 
207   void addOption(Option *O, SubCommand *SC) {
208     bool HadErrors = false;
209     if (O->hasArgStr()) {
210       // If it's a DefaultOption, check to make sure it isn't already there.
211       if (O->isDefaultOption() && SC->OptionsMap.contains(O->ArgStr))
212         return;
213 
214       // Add argument to the argument map!
215       if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
216         errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
217                << "' registered more than once!\n";
218         HadErrors = true;
219       }
220     }
221 
222     // Remember information about positional options.
223     if (O->getFormattingFlag() == cl::Positional)
224       SC->PositionalOpts.push_back(O);
225     else if (O->getMiscFlags() & cl::Sink) // Remember sink options
226       SC->SinkOpts.push_back(O);
227     else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
228       if (SC->ConsumeAfterOpt) {
229         O->error("Cannot specify more than one option with cl::ConsumeAfter!");
230         HadErrors = true;
231       }
232       SC->ConsumeAfterOpt = O;
233     }
234 
235     // Fail hard if there were errors. These are strictly unrecoverable and
236     // indicate serious issues such as conflicting option names or an
237     // incorrectly
238     // linked LLVM distribution.
239     if (HadErrors)
240       report_fatal_error("inconsistency in registered CommandLine options");
241 
242     // If we're adding this to all sub-commands, add it to the ones that have
243     // already been registered.
244     if (SC == &SubCommand::getAll()) {
245       for (auto *Sub : RegisteredSubCommands) {
246         if (SC == Sub)
247           continue;
248         addOption(O, Sub);
249       }
250     }
251   }
252 
253   void addOption(Option *O, bool ProcessDefaultOption = false) {
254     if (!ProcessDefaultOption && O->isDefaultOption()) {
255       DefaultOptions.push_back(O);
256       return;
257     }
258 
259     if (O->Subs.empty()) {
260       addOption(O, &SubCommand::getTopLevel());
261     } else {
262       for (auto *SC : O->Subs)
263         addOption(O, SC);
264     }
265   }
266 
267   void removeOption(Option *O, SubCommand *SC) {
268     SmallVector<StringRef, 16> OptionNames;
269     O->getExtraOptionNames(OptionNames);
270     if (O->hasArgStr())
271       OptionNames.push_back(O->ArgStr);
272 
273     SubCommand &Sub = *SC;
274     auto End = Sub.OptionsMap.end();
275     for (auto Name : OptionNames) {
276       auto I = Sub.OptionsMap.find(Name);
277       if (I != End && I->getValue() == O)
278         Sub.OptionsMap.erase(I);
279     }
280 
281     if (O->getFormattingFlag() == cl::Positional)
282       for (auto *Opt = Sub.PositionalOpts.begin();
283            Opt != Sub.PositionalOpts.end(); ++Opt) {
284         if (*Opt == O) {
285           Sub.PositionalOpts.erase(Opt);
286           break;
287         }
288       }
289     else if (O->getMiscFlags() & cl::Sink)
290       for (auto *Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
291         if (*Opt == O) {
292           Sub.SinkOpts.erase(Opt);
293           break;
294         }
295       }
296     else if (O == Sub.ConsumeAfterOpt)
297       Sub.ConsumeAfterOpt = nullptr;
298   }
299 
300   void removeOption(Option *O) {
301     if (O->Subs.empty())
302       removeOption(O, &SubCommand::getTopLevel());
303     else {
304       if (O->isInAllSubCommands()) {
305         for (auto *SC : RegisteredSubCommands)
306           removeOption(O, SC);
307       } else {
308         for (auto *SC : O->Subs)
309           removeOption(O, SC);
310       }
311     }
312   }
313 
314   bool hasOptions(const SubCommand &Sub) const {
315     return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
316             nullptr != Sub.ConsumeAfterOpt);
317   }
318 
319   bool hasOptions() const {
320     for (const auto *S : RegisteredSubCommands) {
321       if (hasOptions(*S))
322         return true;
323     }
324     return false;
325   }
326 
327   SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
328 
329   void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
330     SubCommand &Sub = *SC;
331     if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
332       errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
333              << "' registered more than once!\n";
334       report_fatal_error("inconsistency in registered CommandLine options");
335     }
336     Sub.OptionsMap.erase(O->ArgStr);
337   }
338 
339   void updateArgStr(Option *O, StringRef NewName) {
340     if (O->Subs.empty())
341       updateArgStr(O, NewName, &SubCommand::getTopLevel());
342     else {
343       if (O->isInAllSubCommands()) {
344         for (auto *SC : RegisteredSubCommands)
345           updateArgStr(O, NewName, SC);
346       } else {
347         for (auto *SC : O->Subs)
348           updateArgStr(O, NewName, SC);
349       }
350     }
351   }
352 
353   void printOptionValues();
354 
355   void registerCategory(OptionCategory *cat) {
356     assert(count_if(RegisteredOptionCategories,
357                     [cat](const OptionCategory *Category) {
358              return cat->getName() == Category->getName();
359            }) == 0 &&
360            "Duplicate option categories");
361 
362     RegisteredOptionCategories.insert(cat);
363   }
364 
365   void registerSubCommand(SubCommand *sub) {
366     assert(count_if(RegisteredSubCommands,
367                     [sub](const SubCommand *Sub) {
368                       return (!sub->getName().empty()) &&
369                              (Sub->getName() == sub->getName());
370                     }) == 0 &&
371            "Duplicate subcommands");
372     RegisteredSubCommands.insert(sub);
373 
374     // For all options that have been registered for all subcommands, add the
375     // option to this subcommand now.
376     if (sub != &SubCommand::getAll()) {
377       for (auto &E : SubCommand::getAll().OptionsMap) {
378         Option *O = E.second;
379         if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
380             O->hasArgStr())
381           addOption(O, sub);
382         else
383           addLiteralOption(*O, sub, E.first());
384       }
385     }
386   }
387 
388   void unregisterSubCommand(SubCommand *sub) {
389     RegisteredSubCommands.erase(sub);
390   }
391 
392   iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
393   getRegisteredSubcommands() {
394     return make_range(RegisteredSubCommands.begin(),
395                       RegisteredSubCommands.end());
396   }
397 
398   void reset() {
399     ActiveSubCommand = nullptr;
400     ProgramName.clear();
401     ProgramOverview = StringRef();
402 
403     MoreHelp.clear();
404     RegisteredOptionCategories.clear();
405 
406     ResetAllOptionOccurrences();
407     RegisteredSubCommands.clear();
408 
409     SubCommand::getTopLevel().reset();
410     SubCommand::getAll().reset();
411     registerSubCommand(&SubCommand::getTopLevel());
412     registerSubCommand(&SubCommand::getAll());
413 
414     DefaultOptions.clear();
415   }
416 
417 private:
418   SubCommand *ActiveSubCommand = nullptr;
419 
420   Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
421   Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,
422                            bool LongOptionsUseDoubleDash, bool HaveDoubleDash) {
423     Option *Opt = LookupOption(Sub, Arg, Value);
424     if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !isGrouping(Opt))
425       return nullptr;
426     return Opt;
427   }
428   SubCommand *LookupSubCommand(StringRef Name);
429 };
430 
431 } // namespace
432 
433 static ManagedStatic<CommandLineParser> GlobalParser;
434 
435 void cl::AddLiteralOption(Option &O, StringRef Name) {
436   GlobalParser->addLiteralOption(O, Name);
437 }
438 
439 extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
440   GlobalParser->MoreHelp.push_back(Help);
441 }
442 
443 void Option::addArgument() {
444   GlobalParser->addOption(this);
445   FullyInitialized = true;
446 }
447 
448 void Option::removeArgument() { GlobalParser->removeOption(this); }
449 
450 void Option::setArgStr(StringRef S) {
451   if (FullyInitialized)
452     GlobalParser->updateArgStr(this, S);
453   assert((S.empty() || S[0] != '-') && "Option can't start with '-");
454   ArgStr = S;
455   if (ArgStr.size() == 1)
456     setMiscFlag(Grouping);
457 }
458 
459 void Option::addCategory(OptionCategory &C) {
460   assert(!Categories.empty() && "Categories cannot be empty.");
461   // Maintain backward compatibility by replacing the default GeneralCategory
462   // if it's still set.  Otherwise, just add the new one.  The GeneralCategory
463   // must be explicitly added if you want multiple categories that include it.
464   if (&C != &getGeneralCategory() && Categories[0] == &getGeneralCategory())
465     Categories[0] = &C;
466   else if (!is_contained(Categories, &C))
467     Categories.push_back(&C);
468 }
469 
470 void Option::reset() {
471   NumOccurrences = 0;
472   setDefault();
473   if (isDefaultOption())
474     removeArgument();
475 }
476 
477 void OptionCategory::registerCategory() {
478   GlobalParser->registerCategory(this);
479 }
480 
481 // A special subcommand representing no subcommand. It is particularly important
482 // that this ManagedStatic uses constant initailization and not dynamic
483 // initialization because it is referenced from cl::opt constructors, which run
484 // dynamically in an arbitrary order.
485 LLVM_REQUIRE_CONSTANT_INITIALIZATION
486 ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
487 
488 // A special subcommand that can be used to put an option into all subcommands.
489 ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
490 
491 SubCommand &SubCommand::getTopLevel() { return *TopLevelSubCommand; }
492 
493 SubCommand &SubCommand::getAll() { return *AllSubCommands; }
494 
495 void SubCommand::registerSubCommand() {
496   GlobalParser->registerSubCommand(this);
497 }
498 
499 void SubCommand::unregisterSubCommand() {
500   GlobalParser->unregisterSubCommand(this);
501 }
502 
503 void SubCommand::reset() {
504   PositionalOpts.clear();
505   SinkOpts.clear();
506   OptionsMap.clear();
507 
508   ConsumeAfterOpt = nullptr;
509 }
510 
511 SubCommand::operator bool() const {
512   return (GlobalParser->getActiveSubCommand() == this);
513 }
514 
515 //===----------------------------------------------------------------------===//
516 // Basic, shared command line option processing machinery.
517 //
518 
519 /// LookupOption - Lookup the option specified by the specified option on the
520 /// command line.  If there is a value specified (after an equal sign) return
521 /// that as well.  This assumes that leading dashes have already been stripped.
522 Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
523                                         StringRef &Value) {
524   // Reject all dashes.
525   if (Arg.empty())
526     return nullptr;
527   assert(&Sub != &SubCommand::getAll());
528 
529   size_t EqualPos = Arg.find('=');
530 
531   // If we have an equals sign, remember the value.
532   if (EqualPos == StringRef::npos) {
533     // Look up the option.
534     return Sub.OptionsMap.lookup(Arg);
535   }
536 
537   // If the argument before the = is a valid option name and the option allows
538   // non-prefix form (ie is not AlwaysPrefix), we match.  If not, signal match
539   // failure by returning nullptr.
540   auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
541   if (I == Sub.OptionsMap.end())
542     return nullptr;
543 
544   auto *O = I->second;
545   if (O->getFormattingFlag() == cl::AlwaysPrefix)
546     return nullptr;
547 
548   Value = Arg.substr(EqualPos + 1);
549   Arg = Arg.substr(0, EqualPos);
550   return I->second;
551 }
552 
553 SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
554   if (Name.empty())
555     return &SubCommand::getTopLevel();
556   for (auto *S : RegisteredSubCommands) {
557     if (S == &SubCommand::getAll())
558       continue;
559     if (S->getName().empty())
560       continue;
561 
562     if (StringRef(S->getName()) == StringRef(Name))
563       return S;
564   }
565   return &SubCommand::getTopLevel();
566 }
567 
568 /// LookupNearestOption - Lookup the closest match to the option specified by
569 /// the specified option on the command line.  If there is a value specified
570 /// (after an equal sign) return that as well.  This assumes that leading dashes
571 /// have already been stripped.
572 static Option *LookupNearestOption(StringRef Arg,
573                                    const StringMap<Option *> &OptionsMap,
574                                    std::string &NearestString) {
575   // Reject all dashes.
576   if (Arg.empty())
577     return nullptr;
578 
579   // Split on any equal sign.
580   std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
581   StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
582   StringRef &RHS = SplitArg.second;
583 
584   // Find the closest match.
585   Option *Best = nullptr;
586   unsigned BestDistance = 0;
587   for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
588                                            ie = OptionsMap.end();
589        it != ie; ++it) {
590     Option *O = it->second;
591     // Do not suggest really hidden options (not shown in any help).
592     if (O->getOptionHiddenFlag() == ReallyHidden)
593       continue;
594 
595     SmallVector<StringRef, 16> OptionNames;
596     O->getExtraOptionNames(OptionNames);
597     if (O->hasArgStr())
598       OptionNames.push_back(O->ArgStr);
599 
600     bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
601     StringRef Flag = PermitValue ? LHS : Arg;
602     for (const auto &Name : OptionNames) {
603       unsigned Distance = StringRef(Name).edit_distance(
604           Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
605       if (!Best || Distance < BestDistance) {
606         Best = O;
607         BestDistance = Distance;
608         if (RHS.empty() || !PermitValue)
609           NearestString = std::string(Name);
610         else
611           NearestString = (Twine(Name) + "=" + RHS).str();
612       }
613     }
614   }
615 
616   return Best;
617 }
618 
619 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
620 /// that does special handling of cl::CommaSeparated options.
621 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
622                                           StringRef ArgName, StringRef Value,
623                                           bool MultiArg = false) {
624   // Check to see if this option accepts a comma separated list of values.  If
625   // it does, we have to split up the value into multiple values.
626   if (Handler->getMiscFlags() & CommaSeparated) {
627     StringRef Val(Value);
628     StringRef::size_type Pos = Val.find(',');
629 
630     while (Pos != StringRef::npos) {
631       // Process the portion before the comma.
632       if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
633         return true;
634       // Erase the portion before the comma, AND the comma.
635       Val = Val.substr(Pos + 1);
636       // Check for another comma.
637       Pos = Val.find(',');
638     }
639 
640     Value = Val;
641   }
642 
643   return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
644 }
645 
646 /// ProvideOption - For Value, this differentiates between an empty value ("")
647 /// and a null value (StringRef()).  The later is accepted for arguments that
648 /// don't allow a value (-foo) the former is rejected (-foo=).
649 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
650                                  StringRef Value, int argc,
651                                  const char *const *argv, int &i) {
652   // Is this a multi-argument option?
653   unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
654 
655   // Enforce value requirements
656   switch (Handler->getValueExpectedFlag()) {
657   case ValueRequired:
658     if (!Value.data()) { // No value specified?
659       // If no other argument or the option only supports prefix form, we
660       // cannot look at the next argument.
661       if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
662         return Handler->error("requires a value!");
663       // Steal the next argument, like for '-o filename'
664       assert(argv && "null check");
665       Value = StringRef(argv[++i]);
666     }
667     break;
668   case ValueDisallowed:
669     if (NumAdditionalVals > 0)
670       return Handler->error("multi-valued option specified"
671                             " with ValueDisallowed modifier!");
672 
673     if (Value.data())
674       return Handler->error("does not allow a value! '" + Twine(Value) +
675                             "' specified.");
676     break;
677   case ValueOptional:
678     break;
679   }
680 
681   // If this isn't a multi-arg option, just run the handler.
682   if (NumAdditionalVals == 0)
683     return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
684 
685   // If it is, run the handle several times.
686   bool MultiArg = false;
687 
688   if (Value.data()) {
689     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
690       return true;
691     --NumAdditionalVals;
692     MultiArg = true;
693   }
694 
695   while (NumAdditionalVals > 0) {
696     if (i + 1 >= argc)
697       return Handler->error("not enough values!");
698     assert(argv && "null check");
699     Value = StringRef(argv[++i]);
700 
701     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
702       return true;
703     MultiArg = true;
704     --NumAdditionalVals;
705   }
706   return false;
707 }
708 
709 bool llvm::cl::ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
710   int Dummy = i;
711   return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
712 }
713 
714 // getOptionPred - Check to see if there are any options that satisfy the
715 // specified predicate with names that are the prefixes in Name.  This is
716 // checked by progressively stripping characters off of the name, checking to
717 // see if there options that satisfy the predicate.  If we find one, return it,
718 // otherwise return null.
719 //
720 static Option *getOptionPred(StringRef Name, size_t &Length,
721                              bool (*Pred)(const Option *),
722                              const StringMap<Option *> &OptionsMap) {
723   StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
724   if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
725     OMI = OptionsMap.end();
726 
727   // Loop while we haven't found an option and Name still has at least two
728   // characters in it (so that the next iteration will not be the empty
729   // string.
730   while (OMI == OptionsMap.end() && Name.size() > 1) {
731     Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
732     OMI = OptionsMap.find(Name);
733     if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
734       OMI = OptionsMap.end();
735   }
736 
737   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
738     Length = Name.size();
739     return OMI->second; // Found one!
740   }
741   return nullptr; // No option found!
742 }
743 
744 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
745 /// with at least one '-') does not fully match an available option.  Check to
746 /// see if this is a prefix or grouped option.  If so, split arg into output an
747 /// Arg/Value pair and return the Option to parse it with.
748 static Option *
749 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
750                               bool &ErrorParsing,
751                               const StringMap<Option *> &OptionsMap) {
752   if (Arg.size() == 1)
753     return nullptr;
754 
755   // Do the lookup!
756   size_t Length = 0;
757   Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
758   if (!PGOpt)
759     return nullptr;
760 
761   do {
762     StringRef MaybeValue =
763         (Length < Arg.size()) ? Arg.substr(Length) : StringRef();
764     Arg = Arg.substr(0, Length);
765     assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
766 
767     // cl::Prefix options do not preserve '=' when used separately.
768     // The behavior for them with grouped options should be the same.
769     if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
770         (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
771       Value = MaybeValue;
772       return PGOpt;
773     }
774 
775     if (MaybeValue[0] == '=') {
776       Value = MaybeValue.substr(1);
777       return PGOpt;
778     }
779 
780     // This must be a grouped option.
781     assert(isGrouping(PGOpt) && "Broken getOptionPred!");
782 
783     // Grouping options inside a group can't have values.
784     if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
785       ErrorParsing |= PGOpt->error("may not occur within a group!");
786       return nullptr;
787     }
788 
789     // Because the value for the option is not required, we don't need to pass
790     // argc/argv in.
791     int Dummy = 0;
792     ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
793 
794     // Get the next grouping option.
795     Arg = MaybeValue;
796     PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
797   } while (PGOpt);
798 
799   // We could not find a grouping option in the remainder of Arg.
800   return nullptr;
801 }
802 
803 static bool RequiresValue(const Option *O) {
804   return O->getNumOccurrencesFlag() == cl::Required ||
805          O->getNumOccurrencesFlag() == cl::OneOrMore;
806 }
807 
808 static bool EatsUnboundedNumberOfValues(const Option *O) {
809   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
810          O->getNumOccurrencesFlag() == cl::OneOrMore;
811 }
812 
813 static bool isWhitespace(char C) {
814   return C == ' ' || C == '\t' || C == '\r' || C == '\n';
815 }
816 
817 static bool isWhitespaceOrNull(char C) {
818   return isWhitespace(C) || C == '\0';
819 }
820 
821 static bool isQuote(char C) { return C == '\"' || C == '\''; }
822 
823 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
824                                 SmallVectorImpl<const char *> &NewArgv,
825                                 bool MarkEOLs) {
826   SmallString<128> Token;
827   for (size_t I = 0, E = Src.size(); I != E; ++I) {
828     // Consume runs of whitespace.
829     if (Token.empty()) {
830       while (I != E && isWhitespace(Src[I])) {
831         // Mark the end of lines in response files.
832         if (MarkEOLs && Src[I] == '\n')
833           NewArgv.push_back(nullptr);
834         ++I;
835       }
836       if (I == E)
837         break;
838     }
839 
840     char C = Src[I];
841 
842     // Backslash escapes the next character.
843     if (I + 1 < E && C == '\\') {
844       ++I; // Skip the escape.
845       Token.push_back(Src[I]);
846       continue;
847     }
848 
849     // Consume a quoted string.
850     if (isQuote(C)) {
851       ++I;
852       while (I != E && Src[I] != C) {
853         // Backslash escapes the next character.
854         if (Src[I] == '\\' && I + 1 != E)
855           ++I;
856         Token.push_back(Src[I]);
857         ++I;
858       }
859       if (I == E)
860         break;
861       continue;
862     }
863 
864     // End the token if this is whitespace.
865     if (isWhitespace(C)) {
866       if (!Token.empty())
867         NewArgv.push_back(Saver.save(Token.str()).data());
868       // Mark the end of lines in response files.
869       if (MarkEOLs && C == '\n')
870         NewArgv.push_back(nullptr);
871       Token.clear();
872       continue;
873     }
874 
875     // This is a normal character.  Append it.
876     Token.push_back(C);
877   }
878 
879   // Append the last token after hitting EOF with no whitespace.
880   if (!Token.empty())
881     NewArgv.push_back(Saver.save(Token.str()).data());
882 }
883 
884 /// Backslashes are interpreted in a rather complicated way in the Windows-style
885 /// command line, because backslashes are used both to separate path and to
886 /// escape double quote. This method consumes runs of backslashes as well as the
887 /// following double quote if it's escaped.
888 ///
889 ///  * If an even number of backslashes is followed by a double quote, one
890 ///    backslash is output for every pair of backslashes, and the last double
891 ///    quote remains unconsumed. The double quote will later be interpreted as
892 ///    the start or end of a quoted string in the main loop outside of this
893 ///    function.
894 ///
895 ///  * If an odd number of backslashes is followed by a double quote, one
896 ///    backslash is output for every pair of backslashes, and a double quote is
897 ///    output for the last pair of backslash-double quote. The double quote is
898 ///    consumed in this case.
899 ///
900 ///  * Otherwise, backslashes are interpreted literally.
901 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
902   size_t E = Src.size();
903   int BackslashCount = 0;
904   // Skip the backslashes.
905   do {
906     ++I;
907     ++BackslashCount;
908   } while (I != E && Src[I] == '\\');
909 
910   bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
911   if (FollowedByDoubleQuote) {
912     Token.append(BackslashCount / 2, '\\');
913     if (BackslashCount % 2 == 0)
914       return I - 1;
915     Token.push_back('"');
916     return I;
917   }
918   Token.append(BackslashCount, '\\');
919   return I - 1;
920 }
921 
922 // Windows treats whitespace, double quotes, and backslashes specially, except
923 // when parsing the first token of a full command line, in which case
924 // backslashes are not special.
925 static bool isWindowsSpecialChar(char C) {
926   return isWhitespaceOrNull(C) || C == '\\' || C == '\"';
927 }
928 static bool isWindowsSpecialCharInCommandName(char C) {
929   return isWhitespaceOrNull(C) || C == '\"';
930 }
931 
932 // Windows tokenization implementation. The implementation is designed to be
933 // inlined and specialized for the two user entry points.
934 static inline void tokenizeWindowsCommandLineImpl(
935     StringRef Src, StringSaver &Saver, function_ref<void(StringRef)> AddToken,
936     bool AlwaysCopy, function_ref<void()> MarkEOL, bool InitialCommandName) {
937   SmallString<128> Token;
938 
939   // Sometimes, this function will be handling a full command line including an
940   // executable pathname at the start. In that situation, the initial pathname
941   // needs different handling from the following arguments, because when
942   // CreateProcess or cmd.exe scans the pathname, it doesn't treat \ as
943   // escaping the quote character, whereas when libc scans the rest of the
944   // command line, it does.
945   bool CommandName = InitialCommandName;
946 
947   // Try to do as much work inside the state machine as possible.
948   enum { INIT, UNQUOTED, QUOTED } State = INIT;
949 
950   for (size_t I = 0, E = Src.size(); I < E; ++I) {
951     switch (State) {
952     case INIT: {
953       assert(Token.empty() && "token should be empty in initial state");
954       // Eat whitespace before a token.
955       while (I < E && isWhitespaceOrNull(Src[I])) {
956         if (Src[I] == '\n')
957           MarkEOL();
958         ++I;
959       }
960       // Stop if this was trailing whitespace.
961       if (I >= E)
962         break;
963       size_t Start = I;
964       if (CommandName) {
965         while (I < E && !isWindowsSpecialCharInCommandName(Src[I]))
966           ++I;
967       } else {
968         while (I < E && !isWindowsSpecialChar(Src[I]))
969           ++I;
970       }
971       StringRef NormalChars = Src.slice(Start, I);
972       if (I >= E || isWhitespaceOrNull(Src[I])) {
973         // No special characters: slice out the substring and start the next
974         // token. Copy the string if the caller asks us to.
975         AddToken(AlwaysCopy ? Saver.save(NormalChars) : NormalChars);
976         if (I < E && Src[I] == '\n') {
977           MarkEOL();
978           CommandName = InitialCommandName;
979         } else {
980           CommandName = false;
981         }
982       } else if (Src[I] == '\"') {
983         Token += NormalChars;
984         State = QUOTED;
985       } else if (Src[I] == '\\') {
986         assert(!CommandName && "or else we'd have treated it as a normal char");
987         Token += NormalChars;
988         I = parseBackslash(Src, I, Token);
989         State = UNQUOTED;
990       } else {
991         llvm_unreachable("unexpected special character");
992       }
993       break;
994     }
995 
996     case UNQUOTED:
997       if (isWhitespaceOrNull(Src[I])) {
998         // Whitespace means the end of the token. If we are in this state, the
999         // token must have contained a special character, so we must copy the
1000         // token.
1001         AddToken(Saver.save(Token.str()));
1002         Token.clear();
1003         if (Src[I] == '\n') {
1004           CommandName = InitialCommandName;
1005           MarkEOL();
1006         } else {
1007           CommandName = false;
1008         }
1009         State = INIT;
1010       } else if (Src[I] == '\"') {
1011         State = QUOTED;
1012       } else if (Src[I] == '\\' && !CommandName) {
1013         I = parseBackslash(Src, I, Token);
1014       } else {
1015         Token.push_back(Src[I]);
1016       }
1017       break;
1018 
1019     case QUOTED:
1020       if (Src[I] == '\"') {
1021         if (I < (E - 1) && Src[I + 1] == '"') {
1022           // Consecutive double-quotes inside a quoted string implies one
1023           // double-quote.
1024           Token.push_back('"');
1025           ++I;
1026         } else {
1027           // Otherwise, end the quoted portion and return to the unquoted state.
1028           State = UNQUOTED;
1029         }
1030       } else if (Src[I] == '\\' && !CommandName) {
1031         I = parseBackslash(Src, I, Token);
1032       } else {
1033         Token.push_back(Src[I]);
1034       }
1035       break;
1036     }
1037   }
1038 
1039   if (State != INIT)
1040     AddToken(Saver.save(Token.str()));
1041 }
1042 
1043 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
1044                                     SmallVectorImpl<const char *> &NewArgv,
1045                                     bool MarkEOLs) {
1046   auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
1047   auto OnEOL = [&]() {
1048     if (MarkEOLs)
1049       NewArgv.push_back(nullptr);
1050   };
1051   tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
1052                                  /*AlwaysCopy=*/true, OnEOL, false);
1053 }
1054 
1055 void cl::TokenizeWindowsCommandLineNoCopy(StringRef Src, StringSaver &Saver,
1056                                           SmallVectorImpl<StringRef> &NewArgv) {
1057   auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok); };
1058   auto OnEOL = []() {};
1059   tokenizeWindowsCommandLineImpl(Src, Saver, AddToken, /*AlwaysCopy=*/false,
1060                                  OnEOL, false);
1061 }
1062 
1063 void cl::TokenizeWindowsCommandLineFull(StringRef Src, StringSaver &Saver,
1064                                         SmallVectorImpl<const char *> &NewArgv,
1065                                         bool MarkEOLs) {
1066   auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
1067   auto OnEOL = [&]() {
1068     if (MarkEOLs)
1069       NewArgv.push_back(nullptr);
1070   };
1071   tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
1072                                  /*AlwaysCopy=*/true, OnEOL, true);
1073 }
1074 
1075 void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
1076                             SmallVectorImpl<const char *> &NewArgv,
1077                             bool MarkEOLs) {
1078   for (const char *Cur = Source.begin(); Cur != Source.end();) {
1079     SmallString<128> Line;
1080     // Check for comment line.
1081     if (isWhitespace(*Cur)) {
1082       while (Cur != Source.end() && isWhitespace(*Cur))
1083         ++Cur;
1084       continue;
1085     }
1086     if (*Cur == '#') {
1087       while (Cur != Source.end() && *Cur != '\n')
1088         ++Cur;
1089       continue;
1090     }
1091     // Find end of the current line.
1092     const char *Start = Cur;
1093     for (const char *End = Source.end(); Cur != End; ++Cur) {
1094       if (*Cur == '\\') {
1095         if (Cur + 1 != End) {
1096           ++Cur;
1097           if (*Cur == '\n' ||
1098               (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
1099             Line.append(Start, Cur - 1);
1100             if (*Cur == '\r')
1101               ++Cur;
1102             Start = Cur + 1;
1103           }
1104         }
1105       } else if (*Cur == '\n')
1106         break;
1107     }
1108     // Tokenize line.
1109     Line.append(Start, Cur);
1110     cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
1111   }
1112 }
1113 
1114 // It is called byte order marker but the UTF-8 BOM is actually not affected
1115 // by the host system's endianness.
1116 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
1117   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
1118 }
1119 
1120 // Substitute <CFGDIR> with the file's base path.
1121 static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver,
1122                             const char *&Arg) {
1123   assert(sys::path::is_absolute(BasePath));
1124   constexpr StringLiteral Token("<CFGDIR>");
1125   const StringRef ArgString(Arg);
1126 
1127   SmallString<128> ResponseFile;
1128   StringRef::size_type StartPos = 0;
1129   for (StringRef::size_type TokenPos = ArgString.find(Token);
1130        TokenPos != StringRef::npos;
1131        TokenPos = ArgString.find(Token, StartPos)) {
1132     // Token may appear more than once per arg (e.g. comma-separated linker
1133     // args). Support by using path-append on any subsequent appearances.
1134     const StringRef LHS = ArgString.substr(StartPos, TokenPos - StartPos);
1135     if (ResponseFile.empty())
1136       ResponseFile = LHS;
1137     else
1138       llvm::sys::path::append(ResponseFile, LHS);
1139     ResponseFile.append(BasePath);
1140     StartPos = TokenPos + Token.size();
1141   }
1142 
1143   if (!ResponseFile.empty()) {
1144     // Path-append the remaining arg substring if at least one token appeared.
1145     const StringRef Remaining = ArgString.substr(StartPos);
1146     if (!Remaining.empty())
1147       llvm::sys::path::append(ResponseFile, Remaining);
1148     Arg = Saver.save(ResponseFile.str()).data();
1149   }
1150 }
1151 
1152 // FName must be an absolute path.
1153 Error ExpansionContext::expandResponseFile(
1154     StringRef FName, SmallVectorImpl<const char *> &NewArgv) {
1155   assert(sys::path::is_absolute(FName));
1156   llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
1157       FS->getBufferForFile(FName);
1158   if (!MemBufOrErr) {
1159     std::error_code EC = MemBufOrErr.getError();
1160     return llvm::createStringError(EC, Twine("cannot not open file '") + FName +
1161                                            "': " + EC.message());
1162   }
1163   MemoryBuffer &MemBuf = *MemBufOrErr.get();
1164   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
1165 
1166   // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
1167   ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
1168   std::string UTF8Buf;
1169   if (hasUTF16ByteOrderMark(BufRef)) {
1170     if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
1171       return llvm::createStringError(std::errc::illegal_byte_sequence,
1172                                      "Could not convert UTF16 to UTF8");
1173     Str = StringRef(UTF8Buf);
1174   }
1175   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
1176   // these bytes before parsing.
1177   // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
1178   else if (hasUTF8ByteOrderMark(BufRef))
1179     Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
1180 
1181   // Tokenize the contents into NewArgv.
1182   Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1183 
1184   // Expanded file content may require additional transformations, like using
1185   // absolute paths instead of relative in '@file' constructs or expanding
1186   // macros.
1187   if (!RelativeNames && !InConfigFile)
1188     return Error::success();
1189 
1190   StringRef BasePath = llvm::sys::path::parent_path(FName);
1191   for (const char *&Arg : NewArgv) {
1192     if (!Arg)
1193       continue;
1194 
1195     // Substitute <CFGDIR> with the file's base path.
1196     if (InConfigFile)
1197       ExpandBasePaths(BasePath, Saver, Arg);
1198 
1199     // Discover the case, when argument should be transformed into '@file' and
1200     // evaluate 'file' for it.
1201     StringRef ArgStr(Arg);
1202     StringRef FileName;
1203     bool ConfigInclusion = false;
1204     if (ArgStr.consume_front("@")) {
1205       FileName = ArgStr;
1206       if (!llvm::sys::path::is_relative(FileName))
1207         continue;
1208     } else if (ArgStr.consume_front("--config=")) {
1209       FileName = ArgStr;
1210       ConfigInclusion = true;
1211     } else {
1212       continue;
1213     }
1214 
1215     // Update expansion construct.
1216     SmallString<128> ResponseFile;
1217     ResponseFile.push_back('@');
1218     if (ConfigInclusion && !llvm::sys::path::has_parent_path(FileName)) {
1219       SmallString<128> FilePath;
1220       if (!findConfigFile(FileName, FilePath))
1221         return createStringError(
1222             std::make_error_code(std::errc::no_such_file_or_directory),
1223             "cannot not find configuration file: " + FileName);
1224       ResponseFile.append(FilePath);
1225     } else {
1226       ResponseFile.append(BasePath);
1227       llvm::sys::path::append(ResponseFile, FileName);
1228     }
1229     Arg = Saver.save(ResponseFile.str()).data();
1230   }
1231   return Error::success();
1232 }
1233 
1234 /// Expand response files on a command line recursively using the given
1235 /// StringSaver and tokenization strategy.
1236 Error ExpansionContext::expandResponseFiles(
1237     SmallVectorImpl<const char *> &Argv) {
1238   struct ResponseFileRecord {
1239     std::string File;
1240     size_t End;
1241   };
1242 
1243   // To detect recursive response files, we maintain a stack of files and the
1244   // position of the last argument in the file. This position is updated
1245   // dynamically as we recursively expand files.
1246   SmallVector<ResponseFileRecord, 3> FileStack;
1247 
1248   // Push a dummy entry that represents the initial command line, removing
1249   // the need to check for an empty list.
1250   FileStack.push_back({"", Argv.size()});
1251 
1252   // Don't cache Argv.size() because it can change.
1253   for (unsigned I = 0; I != Argv.size();) {
1254     while (I == FileStack.back().End) {
1255       // Passing the end of a file's argument list, so we can remove it from the
1256       // stack.
1257       FileStack.pop_back();
1258     }
1259 
1260     const char *Arg = Argv[I];
1261     // Check if it is an EOL marker
1262     if (Arg == nullptr) {
1263       ++I;
1264       continue;
1265     }
1266 
1267     if (Arg[0] != '@') {
1268       ++I;
1269       continue;
1270     }
1271 
1272     const char *FName = Arg + 1;
1273     // Note that CurrentDir is only used for top-level rsp files, the rest will
1274     // always have an absolute path deduced from the containing file.
1275     SmallString<128> CurrDir;
1276     if (llvm::sys::path::is_relative(FName)) {
1277       if (CurrentDir.empty()) {
1278         if (auto CWD = FS->getCurrentWorkingDirectory()) {
1279           CurrDir = *CWD;
1280         } else {
1281           return createStringError(
1282               CWD.getError(), Twine("cannot get absolute path for: ") + FName);
1283         }
1284       } else {
1285         CurrDir = CurrentDir;
1286       }
1287       llvm::sys::path::append(CurrDir, FName);
1288       FName = CurrDir.c_str();
1289     }
1290 
1291     ErrorOr<llvm::vfs::Status> Res = FS->status(FName);
1292     if (!Res || !Res->exists()) {
1293       std::error_code EC = Res.getError();
1294       if (!InConfigFile) {
1295         // If the specified file does not exist, leave '@file' unexpanded, as
1296         // libiberty does.
1297         if (!EC || EC == llvm::errc::no_such_file_or_directory) {
1298           ++I;
1299           continue;
1300         }
1301       }
1302       if (!EC)
1303         EC = llvm::errc::no_such_file_or_directory;
1304       return createStringError(EC, Twine("cannot not open file '") + FName +
1305                                        "': " + EC.message());
1306     }
1307     const llvm::vfs::Status &FileStatus = Res.get();
1308 
1309     auto IsEquivalent =
1310         [FileStatus, this](const ResponseFileRecord &RFile) -> ErrorOr<bool> {
1311       ErrorOr<llvm::vfs::Status> RHS = FS->status(RFile.File);
1312       if (!RHS)
1313         return RHS.getError();
1314       return FileStatus.equivalent(*RHS);
1315     };
1316 
1317     // Check for recursive response files.
1318     for (const auto &F : drop_begin(FileStack)) {
1319       if (ErrorOr<bool> R = IsEquivalent(F)) {
1320         if (R.get())
1321           return createStringError(
1322               R.getError(), Twine("recursive expansion of: '") + F.File + "'");
1323       } else {
1324         return createStringError(R.getError(),
1325                                  Twine("cannot open file: ") + F.File);
1326       }
1327     }
1328 
1329     // Replace this response file argument with the tokenization of its
1330     // contents.  Nested response files are expanded in subsequent iterations.
1331     SmallVector<const char *, 0> ExpandedArgv;
1332     if (Error Err = expandResponseFile(FName, ExpandedArgv))
1333       return Err;
1334 
1335     for (ResponseFileRecord &Record : FileStack) {
1336       // Increase the end of all active records by the number of newly expanded
1337       // arguments, minus the response file itself.
1338       Record.End += ExpandedArgv.size() - 1;
1339     }
1340 
1341     FileStack.push_back({FName, I + ExpandedArgv.size()});
1342     Argv.erase(Argv.begin() + I);
1343     Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1344   }
1345 
1346   // If successful, the top of the file stack will mark the end of the Argv
1347   // stream. A failure here indicates a bug in the stack popping logic above.
1348   // Note that FileStack may have more than one element at this point because we
1349   // don't have a chance to pop the stack when encountering recursive files at
1350   // the end of the stream, so seeing that doesn't indicate a bug.
1351   assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End);
1352   return Error::success();
1353 }
1354 
1355 bool cl::expandResponseFiles(int Argc, const char *const *Argv,
1356                              const char *EnvVar, StringSaver &Saver,
1357                              SmallVectorImpl<const char *> &NewArgv) {
1358 #ifdef _WIN32
1359   auto Tokenize = cl::TokenizeWindowsCommandLine;
1360 #else
1361   auto Tokenize = cl::TokenizeGNUCommandLine;
1362 #endif
1363   // The environment variable specifies initial options.
1364   if (EnvVar)
1365     if (std::optional<std::string> EnvValue = sys::Process::GetEnv(EnvVar))
1366       Tokenize(*EnvValue, Saver, NewArgv, /*MarkEOLs=*/false);
1367 
1368   // Command line options can override the environment variable.
1369   NewArgv.append(Argv + 1, Argv + Argc);
1370   ExpansionContext ECtx(Saver.getAllocator(), Tokenize);
1371   if (Error Err = ECtx.expandResponseFiles(NewArgv)) {
1372     errs() << toString(std::move(Err)) << '\n';
1373     return false;
1374   }
1375   return true;
1376 }
1377 
1378 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1379                              SmallVectorImpl<const char *> &Argv) {
1380   ExpansionContext ECtx(Saver.getAllocator(), Tokenizer);
1381   if (Error Err = ECtx.expandResponseFiles(Argv)) {
1382     errs() << toString(std::move(Err)) << '\n';
1383     return false;
1384   }
1385   return true;
1386 }
1387 
1388 ExpansionContext::ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T)
1389     : Saver(A), Tokenizer(T), FS(vfs::getRealFileSystem().get()) {}
1390 
1391 bool ExpansionContext::findConfigFile(StringRef FileName,
1392                                       SmallVectorImpl<char> &FilePath) {
1393   SmallString<128> CfgFilePath;
1394   const auto FileExists = [this](SmallString<128> Path) -> bool {
1395     auto Status = FS->status(Path);
1396     return Status &&
1397            Status->getType() == llvm::sys::fs::file_type::regular_file;
1398   };
1399 
1400   // If file name contains directory separator, treat it as a path to
1401   // configuration file.
1402   if (llvm::sys::path::has_parent_path(FileName)) {
1403     CfgFilePath = FileName;
1404     if (llvm::sys::path::is_relative(FileName) && FS->makeAbsolute(CfgFilePath))
1405       return false;
1406     if (!FileExists(CfgFilePath))
1407       return false;
1408     FilePath.assign(CfgFilePath.begin(), CfgFilePath.end());
1409     return true;
1410   }
1411 
1412   // Look for the file in search directories.
1413   for (const StringRef &Dir : SearchDirs) {
1414     if (Dir.empty())
1415       continue;
1416     CfgFilePath.assign(Dir);
1417     llvm::sys::path::append(CfgFilePath, FileName);
1418     llvm::sys::path::native(CfgFilePath);
1419     if (FileExists(CfgFilePath)) {
1420       FilePath.assign(CfgFilePath.begin(), CfgFilePath.end());
1421       return true;
1422     }
1423   }
1424 
1425   return false;
1426 }
1427 
1428 Error ExpansionContext::readConfigFile(StringRef CfgFile,
1429                                        SmallVectorImpl<const char *> &Argv) {
1430   SmallString<128> AbsPath;
1431   if (sys::path::is_relative(CfgFile)) {
1432     AbsPath.assign(CfgFile);
1433     if (std::error_code EC = FS->makeAbsolute(AbsPath))
1434       return make_error<StringError>(
1435           EC, Twine("cannot get absolute path for " + CfgFile));
1436     CfgFile = AbsPath.str();
1437   }
1438   InConfigFile = true;
1439   RelativeNames = true;
1440   if (Error Err = expandResponseFile(CfgFile, Argv))
1441     return Err;
1442   return expandResponseFiles(Argv);
1443 }
1444 
1445 static void initCommonOptions();
1446 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1447                                  StringRef Overview, raw_ostream *Errs,
1448                                  const char *EnvVar,
1449                                  bool LongOptionsUseDoubleDash) {
1450   initCommonOptions();
1451   SmallVector<const char *, 20> NewArgv;
1452   BumpPtrAllocator A;
1453   StringSaver Saver(A);
1454   NewArgv.push_back(argv[0]);
1455 
1456   // Parse options from environment variable.
1457   if (EnvVar) {
1458     if (std::optional<std::string> EnvValue =
1459             sys::Process::GetEnv(StringRef(EnvVar)))
1460       TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
1461   }
1462 
1463   // Append options from command line.
1464   for (int I = 1; I < argc; ++I)
1465     NewArgv.push_back(argv[I]);
1466   int NewArgc = static_cast<int>(NewArgv.size());
1467 
1468   // Parse all options.
1469   return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1470                                                Errs, LongOptionsUseDoubleDash);
1471 }
1472 
1473 /// Reset all options at least once, so that we can parse different options.
1474 void CommandLineParser::ResetAllOptionOccurrences() {
1475   // Reset all option values to look like they have never been seen before.
1476   // Options might be reset twice (they can be reference in both OptionsMap
1477   // and one of the other members), but that does not harm.
1478   for (auto *SC : RegisteredSubCommands) {
1479     for (auto &O : SC->OptionsMap)
1480       O.second->reset();
1481     for (Option *O : SC->PositionalOpts)
1482       O->reset();
1483     for (Option *O : SC->SinkOpts)
1484       O->reset();
1485     if (SC->ConsumeAfterOpt)
1486       SC->ConsumeAfterOpt->reset();
1487   }
1488 }
1489 
1490 bool CommandLineParser::ParseCommandLineOptions(int argc,
1491                                                 const char *const *argv,
1492                                                 StringRef Overview,
1493                                                 raw_ostream *Errs,
1494                                                 bool LongOptionsUseDoubleDash) {
1495   assert(hasOptions() && "No options specified!");
1496 
1497   ProgramOverview = Overview;
1498   bool IgnoreErrors = Errs;
1499   if (!Errs)
1500     Errs = &errs();
1501   bool ErrorParsing = false;
1502 
1503   // Expand response files.
1504   SmallVector<const char *, 20> newArgv(argv, argv + argc);
1505   BumpPtrAllocator A;
1506 #ifdef _WIN32
1507   auto Tokenize = cl::TokenizeWindowsCommandLine;
1508 #else
1509   auto Tokenize = cl::TokenizeGNUCommandLine;
1510 #endif
1511   ExpansionContext ECtx(A, Tokenize);
1512   if (Error Err = ECtx.expandResponseFiles(newArgv)) {
1513     *Errs << toString(std::move(Err)) << '\n';
1514     return false;
1515   }
1516   argv = &newArgv[0];
1517   argc = static_cast<int>(newArgv.size());
1518 
1519   // Copy the program name into ProgName, making sure not to overflow it.
1520   ProgramName = std::string(sys::path::filename(StringRef(argv[0])));
1521 
1522   // Check out the positional arguments to collect information about them.
1523   unsigned NumPositionalRequired = 0;
1524 
1525   // Determine whether or not there are an unlimited number of positionals
1526   bool HasUnlimitedPositionals = false;
1527 
1528   int FirstArg = 1;
1529   SubCommand *ChosenSubCommand = &SubCommand::getTopLevel();
1530   if (argc >= 2 && argv[FirstArg][0] != '-') {
1531     // If the first argument specifies a valid subcommand, start processing
1532     // options from the second argument.
1533     ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1534     if (ChosenSubCommand != &SubCommand::getTopLevel())
1535       FirstArg = 2;
1536   }
1537   GlobalParser->ActiveSubCommand = ChosenSubCommand;
1538 
1539   assert(ChosenSubCommand);
1540   auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1541   auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1542   auto &SinkOpts = ChosenSubCommand->SinkOpts;
1543   auto &OptionsMap = ChosenSubCommand->OptionsMap;
1544 
1545   for (auto *O: DefaultOptions) {
1546     addOption(O, true);
1547   }
1548 
1549   if (ConsumeAfterOpt) {
1550     assert(PositionalOpts.size() > 0 &&
1551            "Cannot specify cl::ConsumeAfter without a positional argument!");
1552   }
1553   if (!PositionalOpts.empty()) {
1554 
1555     // Calculate how many positional values are _required_.
1556     bool UnboundedFound = false;
1557     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1558       Option *Opt = PositionalOpts[i];
1559       if (RequiresValue(Opt))
1560         ++NumPositionalRequired;
1561       else if (ConsumeAfterOpt) {
1562         // ConsumeAfter cannot be combined with "optional" positional options
1563         // unless there is only one positional argument...
1564         if (PositionalOpts.size() > 1) {
1565           if (!IgnoreErrors)
1566             Opt->error("error - this positional option will never be matched, "
1567                        "because it does not Require a value, and a "
1568                        "cl::ConsumeAfter option is active!");
1569           ErrorParsing = true;
1570         }
1571       } else if (UnboundedFound && !Opt->hasArgStr()) {
1572         // This option does not "require" a value...  Make sure this option is
1573         // not specified after an option that eats all extra arguments, or this
1574         // one will never get any!
1575         //
1576         if (!IgnoreErrors)
1577           Opt->error("error - option can never match, because "
1578                      "another positional argument will match an "
1579                      "unbounded number of values, and this option"
1580                      " does not require a value!");
1581         *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1582               << "' is all messed up!\n";
1583         *Errs << PositionalOpts.size();
1584         ErrorParsing = true;
1585       }
1586       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1587     }
1588     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1589   }
1590 
1591   // PositionalVals - A vector of "positional" arguments we accumulate into
1592   // the process at the end.
1593   //
1594   SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1595 
1596   // If the program has named positional arguments, and the name has been run
1597   // across, keep track of which positional argument was named.  Otherwise put
1598   // the positional args into the PositionalVals list...
1599   Option *ActivePositionalArg = nullptr;
1600 
1601   // Loop over all of the arguments... processing them.
1602   bool DashDashFound = false; // Have we read '--'?
1603   for (int i = FirstArg; i < argc; ++i) {
1604     Option *Handler = nullptr;
1605     Option *NearestHandler = nullptr;
1606     std::string NearestHandlerString;
1607     StringRef Value;
1608     StringRef ArgName = "";
1609     bool HaveDoubleDash = false;
1610 
1611     // Check to see if this is a positional argument.  This argument is
1612     // considered to be positional if it doesn't start with '-', if it is "-"
1613     // itself, or if we have seen "--" already.
1614     //
1615     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1616       // Positional argument!
1617       if (ActivePositionalArg) {
1618         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1619         continue; // We are done!
1620       }
1621 
1622       if (!PositionalOpts.empty()) {
1623         PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1624 
1625         // All of the positional arguments have been fulfulled, give the rest to
1626         // the consume after option... if it's specified...
1627         //
1628         if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1629           for (++i; i < argc; ++i)
1630             PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1631           break; // Handle outside of the argument processing loop...
1632         }
1633 
1634         // Delay processing positional arguments until the end...
1635         continue;
1636       }
1637     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1638                !DashDashFound) {
1639       DashDashFound = true; // This is the mythical "--"?
1640       continue;             // Don't try to process it as an argument itself.
1641     } else if (ActivePositionalArg &&
1642                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1643       // If there is a positional argument eating options, check to see if this
1644       // option is another positional argument.  If so, treat it as an argument,
1645       // otherwise feed it to the eating positional.
1646       ArgName = StringRef(argv[i] + 1);
1647       // Eat second dash.
1648       if (!ArgName.empty() && ArgName[0] == '-') {
1649         HaveDoubleDash = true;
1650         ArgName = ArgName.substr(1);
1651       }
1652 
1653       Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1654                                  LongOptionsUseDoubleDash, HaveDoubleDash);
1655       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1656         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1657         continue; // We are done!
1658       }
1659     } else { // We start with a '-', must be an argument.
1660       ArgName = StringRef(argv[i] + 1);
1661       // Eat second dash.
1662       if (!ArgName.empty() && ArgName[0] == '-') {
1663         HaveDoubleDash = true;
1664         ArgName = ArgName.substr(1);
1665       }
1666 
1667       Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1668                                  LongOptionsUseDoubleDash, HaveDoubleDash);
1669 
1670       // Check to see if this "option" is really a prefixed or grouped argument.
1671       if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
1672         Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1673                                                 OptionsMap);
1674 
1675       // Otherwise, look for the closest available option to report to the user
1676       // in the upcoming error.
1677       if (!Handler && SinkOpts.empty())
1678         NearestHandler =
1679             LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1680     }
1681 
1682     if (!Handler) {
1683       if (SinkOpts.empty()) {
1684         *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1685               << "'.  Try: '" << argv[0] << " --help'\n";
1686 
1687         if (NearestHandler) {
1688           // If we know a near match, report it as well.
1689           *Errs << ProgramName << ": Did you mean '"
1690                 << PrintArg(NearestHandlerString, 0) << "'?\n";
1691         }
1692 
1693         ErrorParsing = true;
1694       } else {
1695         for (Option *SinkOpt : SinkOpts)
1696           SinkOpt->addOccurrence(i, "", StringRef(argv[i]));
1697       }
1698       continue;
1699     }
1700 
1701     // If this is a named positional argument, just remember that it is the
1702     // active one...
1703     if (Handler->getFormattingFlag() == cl::Positional) {
1704       if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1705         Handler->error("This argument does not take a value.\n"
1706                        "\tInstead, it consumes any positional arguments until "
1707                        "the next recognized option.", *Errs);
1708         ErrorParsing = true;
1709       }
1710       ActivePositionalArg = Handler;
1711     }
1712     else
1713       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1714   }
1715 
1716   // Check and handle positional arguments now...
1717   if (NumPositionalRequired > PositionalVals.size()) {
1718       *Errs << ProgramName
1719              << ": Not enough positional command line arguments specified!\n"
1720              << "Must specify at least " << NumPositionalRequired
1721              << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1722              << ": See: " << argv[0] << " --help\n";
1723 
1724     ErrorParsing = true;
1725   } else if (!HasUnlimitedPositionals &&
1726              PositionalVals.size() > PositionalOpts.size()) {
1727     *Errs << ProgramName << ": Too many positional arguments specified!\n"
1728           << "Can specify at most " << PositionalOpts.size()
1729           << " positional arguments: See: " << argv[0] << " --help\n";
1730     ErrorParsing = true;
1731 
1732   } else if (!ConsumeAfterOpt) {
1733     // Positional args have already been handled if ConsumeAfter is specified.
1734     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1735     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1736       if (RequiresValue(PositionalOpts[i])) {
1737         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1738                                 PositionalVals[ValNo].second);
1739         ValNo++;
1740         --NumPositionalRequired; // We fulfilled our duty...
1741       }
1742 
1743       // If we _can_ give this option more arguments, do so now, as long as we
1744       // do not give it values that others need.  'Done' controls whether the
1745       // option even _WANTS_ any more.
1746       //
1747       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1748       while (NumVals - ValNo > NumPositionalRequired && !Done) {
1749         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1750         case cl::Optional:
1751           Done = true; // Optional arguments want _at most_ one value
1752           [[fallthrough]];
1753         case cl::ZeroOrMore: // Zero or more will take all they can get...
1754         case cl::OneOrMore:  // One or more will take all they can get...
1755           ProvidePositionalOption(PositionalOpts[i],
1756                                   PositionalVals[ValNo].first,
1757                                   PositionalVals[ValNo].second);
1758           ValNo++;
1759           break;
1760         default:
1761           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1762                            "positional argument processing!");
1763         }
1764       }
1765     }
1766   } else {
1767     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1768     unsigned ValNo = 0;
1769     for (size_t J = 0, E = PositionalOpts.size(); J != E; ++J)
1770       if (RequiresValue(PositionalOpts[J])) {
1771         ErrorParsing |= ProvidePositionalOption(PositionalOpts[J],
1772                                                 PositionalVals[ValNo].first,
1773                                                 PositionalVals[ValNo].second);
1774         ValNo++;
1775       }
1776 
1777     // Handle the case where there is just one positional option, and it's
1778     // optional.  In this case, we want to give JUST THE FIRST option to the
1779     // positional option and keep the rest for the consume after.  The above
1780     // loop would have assigned no values to positional options in this case.
1781     //
1782     if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1783       ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1784                                               PositionalVals[ValNo].first,
1785                                               PositionalVals[ValNo].second);
1786       ValNo++;
1787     }
1788 
1789     // Handle over all of the rest of the arguments to the
1790     // cl::ConsumeAfter command line option...
1791     for (; ValNo != PositionalVals.size(); ++ValNo)
1792       ErrorParsing |=
1793           ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1794                                   PositionalVals[ValNo].second);
1795   }
1796 
1797   // Loop over args and make sure all required args are specified!
1798   for (const auto &Opt : OptionsMap) {
1799     switch (Opt.second->getNumOccurrencesFlag()) {
1800     case Required:
1801     case OneOrMore:
1802       if (Opt.second->getNumOccurrences() == 0) {
1803         Opt.second->error("must be specified at least once!");
1804         ErrorParsing = true;
1805       }
1806       [[fallthrough]];
1807     default:
1808       break;
1809     }
1810   }
1811 
1812   // Now that we know if -debug is specified, we can use it.
1813   // Note that if ReadResponseFiles == true, this must be done before the
1814   // memory allocated for the expanded command line is free()d below.
1815   LLVM_DEBUG(dbgs() << "Args: ";
1816              for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1817              dbgs() << '\n';);
1818 
1819   // Free all of the memory allocated to the map.  Command line options may only
1820   // be processed once!
1821   MoreHelp.clear();
1822 
1823   // If we had an error processing our arguments, don't let the program execute
1824   if (ErrorParsing) {
1825     if (!IgnoreErrors)
1826       exit(1);
1827     return false;
1828   }
1829   return true;
1830 }
1831 
1832 //===----------------------------------------------------------------------===//
1833 // Option Base class implementation
1834 //
1835 
1836 bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
1837   if (!ArgName.data())
1838     ArgName = ArgStr;
1839   if (ArgName.empty())
1840     Errs << HelpStr; // Be nice for positional arguments
1841   else
1842     Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName, 0);
1843 
1844   Errs << " option: " << Message << "\n";
1845   return true;
1846 }
1847 
1848 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1849                            bool MultiArg) {
1850   if (!MultiArg)
1851     NumOccurrences++; // Increment the number of times we have been seen
1852 
1853   return handleOccurrence(pos, ArgName, Value);
1854 }
1855 
1856 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1857 // has been specified yet.
1858 //
1859 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1860   if (O.ValueStr.empty())
1861     return DefaultMsg;
1862   return O.ValueStr;
1863 }
1864 
1865 //===----------------------------------------------------------------------===//
1866 // cl::alias class implementation
1867 //
1868 
1869 // Return the width of the option tag for printing...
1870 size_t alias::getOptionWidth() const {
1871   return argPlusPrefixesSize(ArgStr);
1872 }
1873 
1874 void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1875                           size_t FirstLineIndentedBy) {
1876   assert(Indent >= FirstLineIndentedBy);
1877   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1878   outs().indent(Indent - FirstLineIndentedBy)
1879       << ArgHelpPrefix << Split.first << "\n";
1880   while (!Split.second.empty()) {
1881     Split = Split.second.split('\n');
1882     outs().indent(Indent) << Split.first << "\n";
1883   }
1884 }
1885 
1886 void Option::printEnumValHelpStr(StringRef HelpStr, size_t BaseIndent,
1887                                  size_t FirstLineIndentedBy) {
1888   const StringRef ValHelpPrefix = "  ";
1889   assert(BaseIndent >= FirstLineIndentedBy);
1890   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1891   outs().indent(BaseIndent - FirstLineIndentedBy)
1892       << ArgHelpPrefix << ValHelpPrefix << Split.first << "\n";
1893   while (!Split.second.empty()) {
1894     Split = Split.second.split('\n');
1895     outs().indent(BaseIndent + ValHelpPrefix.size()) << Split.first << "\n";
1896   }
1897 }
1898 
1899 // Print out the option for the alias.
1900 void alias::printOptionInfo(size_t GlobalWidth) const {
1901   outs() << PrintArg(ArgStr);
1902   printHelpStr(HelpStr, GlobalWidth, argPlusPrefixesSize(ArgStr));
1903 }
1904 
1905 //===----------------------------------------------------------------------===//
1906 // Parser Implementation code...
1907 //
1908 
1909 // basic_parser implementation
1910 //
1911 
1912 // Return the width of the option tag for printing...
1913 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1914   size_t Len = argPlusPrefixesSize(O.ArgStr);
1915   auto ValName = getValueName();
1916   if (!ValName.empty()) {
1917     size_t FormattingLen = 3;
1918     if (O.getMiscFlags() & PositionalEatsArgs)
1919       FormattingLen = 6;
1920     Len += getValueStr(O, ValName).size() + FormattingLen;
1921   }
1922 
1923   return Len;
1924 }
1925 
1926 // printOptionInfo - Print out information about this option.  The
1927 // to-be-maintained width is specified.
1928 //
1929 void basic_parser_impl::printOptionInfo(const Option &O,
1930                                         size_t GlobalWidth) const {
1931   outs() << PrintArg(O.ArgStr);
1932 
1933   auto ValName = getValueName();
1934   if (!ValName.empty()) {
1935     if (O.getMiscFlags() & PositionalEatsArgs) {
1936       outs() << " <" << getValueStr(O, ValName) << ">...";
1937     } else if (O.getValueExpectedFlag() == ValueOptional)
1938       outs() << "[=<" << getValueStr(O, ValName) << ">]";
1939     else {
1940       outs() << (O.ArgStr.size() == 1 ? " <" : "=<") << getValueStr(O, ValName)
1941              << '>';
1942     }
1943   }
1944 
1945   Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1946 }
1947 
1948 void basic_parser_impl::printOptionName(const Option &O,
1949                                         size_t GlobalWidth) const {
1950   outs() << PrintArg(O.ArgStr);
1951   outs().indent(GlobalWidth - O.ArgStr.size());
1952 }
1953 
1954 // parser<bool> implementation
1955 //
1956 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1957                          bool &Value) {
1958   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1959       Arg == "1") {
1960     Value = true;
1961     return false;
1962   }
1963 
1964   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1965     Value = false;
1966     return false;
1967   }
1968   return O.error("'" + Arg +
1969                  "' is invalid value for boolean argument! Try 0 or 1");
1970 }
1971 
1972 // parser<boolOrDefault> implementation
1973 //
1974 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1975                                   boolOrDefault &Value) {
1976   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1977       Arg == "1") {
1978     Value = BOU_TRUE;
1979     return false;
1980   }
1981   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1982     Value = BOU_FALSE;
1983     return false;
1984   }
1985 
1986   return O.error("'" + Arg +
1987                  "' is invalid value for boolean argument! Try 0 or 1");
1988 }
1989 
1990 // parser<int> implementation
1991 //
1992 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1993                         int &Value) {
1994   if (Arg.getAsInteger(0, Value))
1995     return O.error("'" + Arg + "' value invalid for integer argument!");
1996   return false;
1997 }
1998 
1999 // parser<long> implementation
2000 //
2001 bool parser<long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2002                          long &Value) {
2003   if (Arg.getAsInteger(0, Value))
2004     return O.error("'" + Arg + "' value invalid for long argument!");
2005   return false;
2006 }
2007 
2008 // parser<long long> implementation
2009 //
2010 bool parser<long long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2011                               long long &Value) {
2012   if (Arg.getAsInteger(0, Value))
2013     return O.error("'" + Arg + "' value invalid for llong argument!");
2014   return false;
2015 }
2016 
2017 // parser<unsigned> implementation
2018 //
2019 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
2020                              unsigned &Value) {
2021 
2022   if (Arg.getAsInteger(0, Value))
2023     return O.error("'" + Arg + "' value invalid for uint argument!");
2024   return false;
2025 }
2026 
2027 // parser<unsigned long> implementation
2028 //
2029 bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2030                                   unsigned long &Value) {
2031 
2032   if (Arg.getAsInteger(0, Value))
2033     return O.error("'" + Arg + "' value invalid for ulong argument!");
2034   return false;
2035 }
2036 
2037 // parser<unsigned long long> implementation
2038 //
2039 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
2040                                        StringRef Arg,
2041                                        unsigned long long &Value) {
2042 
2043   if (Arg.getAsInteger(0, Value))
2044     return O.error("'" + Arg + "' value invalid for ullong argument!");
2045   return false;
2046 }
2047 
2048 // parser<double>/parser<float> implementation
2049 //
2050 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
2051   if (to_float(Arg, Value))
2052     return false;
2053   return O.error("'" + Arg + "' value invalid for floating point argument!");
2054 }
2055 
2056 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
2057                            double &Val) {
2058   return parseDouble(O, Arg, Val);
2059 }
2060 
2061 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
2062                           float &Val) {
2063   double dVal;
2064   if (parseDouble(O, Arg, dVal))
2065     return true;
2066   Val = (float)dVal;
2067   return false;
2068 }
2069 
2070 // generic_parser_base implementation
2071 //
2072 
2073 // findOption - Return the option number corresponding to the specified
2074 // argument string.  If the option is not found, getNumOptions() is returned.
2075 //
2076 unsigned generic_parser_base::findOption(StringRef Name) {
2077   unsigned e = getNumOptions();
2078 
2079   for (unsigned i = 0; i != e; ++i) {
2080     if (getOption(i) == Name)
2081       return i;
2082   }
2083   return e;
2084 }
2085 
2086 static StringRef EqValue = "=<value>";
2087 static StringRef EmptyOption = "<empty>";
2088 static StringRef OptionPrefix = "    =";
2089 static size_t getOptionPrefixesSize() {
2090   return OptionPrefix.size() + ArgHelpPrefix.size();
2091 }
2092 
2093 static bool shouldPrintOption(StringRef Name, StringRef Description,
2094                               const Option &O) {
2095   return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
2096          !Description.empty();
2097 }
2098 
2099 // Return the width of the option tag for printing...
2100 size_t generic_parser_base::getOptionWidth(const Option &O) const {
2101   if (O.hasArgStr()) {
2102     size_t Size =
2103         argPlusPrefixesSize(O.ArgStr) + EqValue.size();
2104     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2105       StringRef Name = getOption(i);
2106       if (!shouldPrintOption(Name, getDescription(i), O))
2107         continue;
2108       size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
2109       Size = std::max(Size, NameSize + getOptionPrefixesSize());
2110     }
2111     return Size;
2112   } else {
2113     size_t BaseSize = 0;
2114     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
2115       BaseSize = std::max(BaseSize, getOption(i).size() + 8);
2116     return BaseSize;
2117   }
2118 }
2119 
2120 // printOptionInfo - Print out information about this option.  The
2121 // to-be-maintained width is specified.
2122 //
2123 void generic_parser_base::printOptionInfo(const Option &O,
2124                                           size_t GlobalWidth) const {
2125   if (O.hasArgStr()) {
2126     // When the value is optional, first print a line just describing the
2127     // option without values.
2128     if (O.getValueExpectedFlag() == ValueOptional) {
2129       for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2130         if (getOption(i).empty()) {
2131           outs() << PrintArg(O.ArgStr);
2132           Option::printHelpStr(O.HelpStr, GlobalWidth,
2133                                argPlusPrefixesSize(O.ArgStr));
2134           break;
2135         }
2136       }
2137     }
2138 
2139     outs() << PrintArg(O.ArgStr) << EqValue;
2140     Option::printHelpStr(O.HelpStr, GlobalWidth,
2141                          EqValue.size() +
2142                              argPlusPrefixesSize(O.ArgStr));
2143     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2144       StringRef OptionName = getOption(i);
2145       StringRef Description = getDescription(i);
2146       if (!shouldPrintOption(OptionName, Description, O))
2147         continue;
2148       size_t FirstLineIndent = OptionName.size() + getOptionPrefixesSize();
2149       outs() << OptionPrefix << OptionName;
2150       if (OptionName.empty()) {
2151         outs() << EmptyOption;
2152         assert(FirstLineIndent >= EmptyOption.size());
2153         FirstLineIndent += EmptyOption.size();
2154       }
2155       if (!Description.empty())
2156         Option::printEnumValHelpStr(Description, GlobalWidth, FirstLineIndent);
2157       else
2158         outs() << '\n';
2159     }
2160   } else {
2161     if (!O.HelpStr.empty())
2162       outs() << "  " << O.HelpStr << '\n';
2163     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2164       StringRef Option = getOption(i);
2165       outs() << "    " << PrintArg(Option);
2166       Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
2167     }
2168   }
2169 }
2170 
2171 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
2172 
2173 // printGenericOptionDiff - Print the value of this option and it's default.
2174 //
2175 // "Generic" options have each value mapped to a name.
2176 void generic_parser_base::printGenericOptionDiff(
2177     const Option &O, const GenericOptionValue &Value,
2178     const GenericOptionValue &Default, size_t GlobalWidth) const {
2179   outs() << "  " << PrintArg(O.ArgStr);
2180   outs().indent(GlobalWidth - O.ArgStr.size());
2181 
2182   unsigned NumOpts = getNumOptions();
2183   for (unsigned i = 0; i != NumOpts; ++i) {
2184     if (Value.compare(getOptionValue(i)))
2185       continue;
2186 
2187     outs() << "= " << getOption(i);
2188     size_t L = getOption(i).size();
2189     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
2190     outs().indent(NumSpaces) << " (default: ";
2191     for (unsigned j = 0; j != NumOpts; ++j) {
2192       if (Default.compare(getOptionValue(j)))
2193         continue;
2194       outs() << getOption(j);
2195       break;
2196     }
2197     outs() << ")\n";
2198     return;
2199   }
2200   outs() << "= *unknown option value*\n";
2201 }
2202 
2203 // printOptionDiff - Specializations for printing basic value types.
2204 //
2205 #define PRINT_OPT_DIFF(T)                                                      \
2206   void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
2207                                   size_t GlobalWidth) const {                  \
2208     printOptionName(O, GlobalWidth);                                           \
2209     std::string Str;                                                           \
2210     {                                                                          \
2211       raw_string_ostream SS(Str);                                              \
2212       SS << V;                                                                 \
2213     }                                                                          \
2214     outs() << "= " << Str;                                                     \
2215     size_t NumSpaces =                                                         \
2216         MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
2217     outs().indent(NumSpaces) << " (default: ";                                 \
2218     if (D.hasValue())                                                          \
2219       outs() << D.getValue();                                                  \
2220     else                                                                       \
2221       outs() << "*no default*";                                                \
2222     outs() << ")\n";                                                           \
2223   }
2224 
2225 PRINT_OPT_DIFF(bool)
2226 PRINT_OPT_DIFF(boolOrDefault)
2227 PRINT_OPT_DIFF(int)
2228 PRINT_OPT_DIFF(long)
2229 PRINT_OPT_DIFF(long long)
2230 PRINT_OPT_DIFF(unsigned)
2231 PRINT_OPT_DIFF(unsigned long)
2232 PRINT_OPT_DIFF(unsigned long long)
2233 PRINT_OPT_DIFF(double)
2234 PRINT_OPT_DIFF(float)
2235 PRINT_OPT_DIFF(char)
2236 
2237 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
2238                                           const OptionValue<std::string> &D,
2239                                           size_t GlobalWidth) const {
2240   printOptionName(O, GlobalWidth);
2241   outs() << "= " << V;
2242   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
2243   outs().indent(NumSpaces) << " (default: ";
2244   if (D.hasValue())
2245     outs() << D.getValue();
2246   else
2247     outs() << "*no default*";
2248   outs() << ")\n";
2249 }
2250 
2251 // Print a placeholder for options that don't yet support printOptionDiff().
2252 void basic_parser_impl::printOptionNoValue(const Option &O,
2253                                            size_t GlobalWidth) const {
2254   printOptionName(O, GlobalWidth);
2255   outs() << "= *cannot print option value*\n";
2256 }
2257 
2258 //===----------------------------------------------------------------------===//
2259 // -help and -help-hidden option implementation
2260 //
2261 
2262 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
2263                           const std::pair<const char *, Option *> *RHS) {
2264   return strcmp(LHS->first, RHS->first);
2265 }
2266 
2267 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
2268                           const std::pair<const char *, SubCommand *> *RHS) {
2269   return strcmp(LHS->first, RHS->first);
2270 }
2271 
2272 // Copy Options into a vector so we can sort them as we like.
2273 static void sortOpts(StringMap<Option *> &OptMap,
2274                      SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
2275                      bool ShowHidden) {
2276   SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
2277 
2278   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
2279        I != E; ++I) {
2280     // Ignore really-hidden options.
2281     if (I->second->getOptionHiddenFlag() == ReallyHidden)
2282       continue;
2283 
2284     // Unless showhidden is set, ignore hidden flags.
2285     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
2286       continue;
2287 
2288     // If we've already seen this option, don't add it to the list again.
2289     if (!OptionSet.insert(I->second).second)
2290       continue;
2291 
2292     Opts.push_back(
2293         std::pair<const char *, Option *>(I->getKey().data(), I->second));
2294   }
2295 
2296   // Sort the options list alphabetically.
2297   array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
2298 }
2299 
2300 static void
2301 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
2302                 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
2303   for (auto *S : SubMap) {
2304     if (S->getName().empty())
2305       continue;
2306     Subs.push_back(std::make_pair(S->getName().data(), S));
2307   }
2308   array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
2309 }
2310 
2311 namespace {
2312 
2313 class HelpPrinter {
2314 protected:
2315   const bool ShowHidden;
2316   typedef SmallVector<std::pair<const char *, Option *>, 128>
2317       StrOptionPairVector;
2318   typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
2319       StrSubCommandPairVector;
2320   // Print the options. Opts is assumed to be alphabetically sorted.
2321   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
2322     for (size_t i = 0, e = Opts.size(); i != e; ++i)
2323       Opts[i].second->printOptionInfo(MaxArgLen);
2324   }
2325 
2326   void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
2327     for (const auto &S : Subs) {
2328       outs() << "  " << S.first;
2329       if (!S.second->getDescription().empty()) {
2330         outs().indent(MaxSubLen - strlen(S.first));
2331         outs() << " - " << S.second->getDescription();
2332       }
2333       outs() << "\n";
2334     }
2335   }
2336 
2337 public:
2338   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
2339   virtual ~HelpPrinter() = default;
2340 
2341   // Invoke the printer.
2342   void operator=(bool Value) {
2343     if (!Value)
2344       return;
2345     printHelp();
2346 
2347     // Halt the program since help information was printed
2348     exit(0);
2349   }
2350 
2351   void printHelp() {
2352     SubCommand *Sub = GlobalParser->getActiveSubCommand();
2353     auto &OptionsMap = Sub->OptionsMap;
2354     auto &PositionalOpts = Sub->PositionalOpts;
2355     auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
2356 
2357     StrOptionPairVector Opts;
2358     sortOpts(OptionsMap, Opts, ShowHidden);
2359 
2360     StrSubCommandPairVector Subs;
2361     sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
2362 
2363     if (!GlobalParser->ProgramOverview.empty())
2364       outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
2365 
2366     if (Sub == &SubCommand::getTopLevel()) {
2367       outs() << "USAGE: " << GlobalParser->ProgramName;
2368       if (Subs.size() > 2)
2369         outs() << " [subcommand]";
2370       outs() << " [options]";
2371     } else {
2372       if (!Sub->getDescription().empty()) {
2373         outs() << "SUBCOMMAND '" << Sub->getName()
2374                << "': " << Sub->getDescription() << "\n\n";
2375       }
2376       outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
2377              << " [options]";
2378     }
2379 
2380     for (auto *Opt : PositionalOpts) {
2381       if (Opt->hasArgStr())
2382         outs() << " --" << Opt->ArgStr;
2383       outs() << " " << Opt->HelpStr;
2384     }
2385 
2386     // Print the consume after option info if it exists...
2387     if (ConsumeAfterOpt)
2388       outs() << " " << ConsumeAfterOpt->HelpStr;
2389 
2390     if (Sub == &SubCommand::getTopLevel() && !Subs.empty()) {
2391       // Compute the maximum subcommand length...
2392       size_t MaxSubLen = 0;
2393       for (size_t i = 0, e = Subs.size(); i != e; ++i)
2394         MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
2395 
2396       outs() << "\n\n";
2397       outs() << "SUBCOMMANDS:\n\n";
2398       printSubCommands(Subs, MaxSubLen);
2399       outs() << "\n";
2400       outs() << "  Type \"" << GlobalParser->ProgramName
2401              << " <subcommand> --help\" to get more help on a specific "
2402                 "subcommand";
2403     }
2404 
2405     outs() << "\n\n";
2406 
2407     // Compute the maximum argument length...
2408     size_t MaxArgLen = 0;
2409     for (size_t i = 0, e = Opts.size(); i != e; ++i)
2410       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2411 
2412     outs() << "OPTIONS:\n";
2413     printOptions(Opts, MaxArgLen);
2414 
2415     // Print any extra help the user has declared.
2416     for (const auto &I : GlobalParser->MoreHelp)
2417       outs() << I;
2418     GlobalParser->MoreHelp.clear();
2419   }
2420 };
2421 
2422 class CategorizedHelpPrinter : public HelpPrinter {
2423 public:
2424   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
2425 
2426   // Helper function for printOptions().
2427   // It shall return a negative value if A's name should be lexicographically
2428   // ordered before B's name. It returns a value greater than zero if B's name
2429   // should be ordered before A's name, and it returns 0 otherwise.
2430   static int OptionCategoryCompare(OptionCategory *const *A,
2431                                    OptionCategory *const *B) {
2432     return (*A)->getName().compare((*B)->getName());
2433   }
2434 
2435   // Make sure we inherit our base class's operator=()
2436   using HelpPrinter::operator=;
2437 
2438 protected:
2439   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
2440     std::vector<OptionCategory *> SortedCategories;
2441     DenseMap<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2442 
2443     // Collect registered option categories into vector in preparation for
2444     // sorting.
2445     for (OptionCategory *Category : GlobalParser->RegisteredOptionCategories)
2446       SortedCategories.push_back(Category);
2447 
2448     // Sort the different option categories alphabetically.
2449     assert(SortedCategories.size() > 0 && "No option categories registered!");
2450     array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
2451                    OptionCategoryCompare);
2452 
2453     // Walk through pre-sorted options and assign into categories.
2454     // Because the options are already alphabetically sorted the
2455     // options within categories will also be alphabetically sorted.
2456     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
2457       Option *Opt = Opts[I].second;
2458       for (auto &Cat : Opt->Categories) {
2459         assert(llvm::is_contained(SortedCategories, Cat) &&
2460                "Option has an unregistered category");
2461         CategorizedOptions[Cat].push_back(Opt);
2462       }
2463     }
2464 
2465     // Now do printing.
2466     for (OptionCategory *Category : SortedCategories) {
2467       // Hide empty categories for --help, but show for --help-hidden.
2468       const auto &CategoryOptions = CategorizedOptions[Category];
2469       bool IsEmptyCategory = CategoryOptions.empty();
2470       if (!ShowHidden && IsEmptyCategory)
2471         continue;
2472 
2473       // Print category information.
2474       outs() << "\n";
2475       outs() << Category->getName() << ":\n";
2476 
2477       // Check if description is set.
2478       if (!Category->getDescription().empty())
2479         outs() << Category->getDescription() << "\n\n";
2480       else
2481         outs() << "\n";
2482 
2483       // When using --help-hidden explicitly state if the category has no
2484       // options associated with it.
2485       if (IsEmptyCategory) {
2486         outs() << "  This option category has no options.\n";
2487         continue;
2488       }
2489       // Loop over the options in the category and print.
2490       for (const Option *Opt : CategoryOptions)
2491         Opt->printOptionInfo(MaxArgLen);
2492     }
2493   }
2494 };
2495 
2496 // This wraps the Uncategorizing and Categorizing printers and decides
2497 // at run time which should be invoked.
2498 class HelpPrinterWrapper {
2499 private:
2500   HelpPrinter &UncategorizedPrinter;
2501   CategorizedHelpPrinter &CategorizedPrinter;
2502 
2503 public:
2504   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2505                               CategorizedHelpPrinter &CategorizedPrinter)
2506       : UncategorizedPrinter(UncategorizedPrinter),
2507         CategorizedPrinter(CategorizedPrinter) {}
2508 
2509   // Invoke the printer.
2510   void operator=(bool Value);
2511 };
2512 
2513 } // End anonymous namespace
2514 
2515 #if defined(__GNUC__)
2516 // GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are
2517 // enabled.
2518 # if defined(__OPTIMIZE__)
2519 #  define LLVM_IS_DEBUG_BUILD 0
2520 # else
2521 #  define LLVM_IS_DEBUG_BUILD 1
2522 # endif
2523 #elif defined(_MSC_VER)
2524 // MSVC doesn't have a predefined macro indicating if optimizations are enabled.
2525 // Use _DEBUG instead. This macro actually corresponds to the choice between
2526 // debug and release CRTs, but it is a reasonable proxy.
2527 # if defined(_DEBUG)
2528 #  define LLVM_IS_DEBUG_BUILD 1
2529 # else
2530 #  define LLVM_IS_DEBUG_BUILD 0
2531 # endif
2532 #else
2533 // Otherwise, for an unknown compiler, assume this is an optimized build.
2534 # define LLVM_IS_DEBUG_BUILD 0
2535 #endif
2536 
2537 namespace {
2538 class VersionPrinter {
2539 public:
2540   void print(std::vector<VersionPrinterTy> ExtraPrinters = {}) {
2541     raw_ostream &OS = outs();
2542 #ifdef PACKAGE_VENDOR
2543     OS << PACKAGE_VENDOR << " ";
2544 #else
2545     OS << "LLVM (http://llvm.org/):\n  ";
2546 #endif
2547     OS << PACKAGE_NAME << " version " << PACKAGE_VERSION << "\n  ";
2548 #if LLVM_IS_DEBUG_BUILD
2549     OS << "DEBUG build";
2550 #else
2551     OS << "Optimized build";
2552 #endif
2553 #ifndef NDEBUG
2554     OS << " with assertions";
2555 #endif
2556     OS << ".\n";
2557 
2558     // Iterate over any registered extra printers and call them to add further
2559     // information.
2560     if (!ExtraPrinters.empty()) {
2561       for (const auto &I : ExtraPrinters)
2562         I(outs());
2563     }
2564   }
2565   void operator=(bool OptionWasSpecified);
2566 };
2567 
2568 struct CommandLineCommonOptions {
2569   // Declare the four HelpPrinter instances that are used to print out help, or
2570   // help-hidden as an uncategorized list or in categories.
2571   HelpPrinter UncategorizedNormalPrinter{false};
2572   HelpPrinter UncategorizedHiddenPrinter{true};
2573   CategorizedHelpPrinter CategorizedNormalPrinter{false};
2574   CategorizedHelpPrinter CategorizedHiddenPrinter{true};
2575   // Declare HelpPrinter wrappers that will decide whether or not to invoke
2576   // a categorizing help printer
2577   HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
2578                                           CategorizedNormalPrinter};
2579   HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
2580                                           CategorizedHiddenPrinter};
2581   // Define a category for generic options that all tools should have.
2582   cl::OptionCategory GenericCategory{"Generic Options"};
2583 
2584   // Define uncategorized help printers.
2585   // --help-list is hidden by default because if Option categories are being
2586   // used then --help behaves the same as --help-list.
2587   cl::opt<HelpPrinter, true, parser<bool>> HLOp{
2588       "help-list",
2589       cl::desc(
2590           "Display list of available options (--help-list-hidden for more)"),
2591       cl::location(UncategorizedNormalPrinter),
2592       cl::Hidden,
2593       cl::ValueDisallowed,
2594       cl::cat(GenericCategory),
2595       cl::sub(SubCommand::getAll())};
2596 
2597   cl::opt<HelpPrinter, true, parser<bool>> HLHOp{
2598       "help-list-hidden",
2599       cl::desc("Display list of all available options"),
2600       cl::location(UncategorizedHiddenPrinter),
2601       cl::Hidden,
2602       cl::ValueDisallowed,
2603       cl::cat(GenericCategory),
2604       cl::sub(SubCommand::getAll())};
2605 
2606   // Define uncategorized/categorized help printers. These printers change their
2607   // behaviour at runtime depending on whether one or more Option categories
2608   // have been declared.
2609   cl::opt<HelpPrinterWrapper, true, parser<bool>> HOp{
2610       "help",
2611       cl::desc("Display available options (--help-hidden for more)"),
2612       cl::location(WrappedNormalPrinter),
2613       cl::ValueDisallowed,
2614       cl::cat(GenericCategory),
2615       cl::sub(SubCommand::getAll())};
2616 
2617   cl::alias HOpA{"h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
2618                  cl::DefaultOption};
2619 
2620   cl::opt<HelpPrinterWrapper, true, parser<bool>> HHOp{
2621       "help-hidden",
2622       cl::desc("Display all available options"),
2623       cl::location(WrappedHiddenPrinter),
2624       cl::Hidden,
2625       cl::ValueDisallowed,
2626       cl::cat(GenericCategory),
2627       cl::sub(SubCommand::getAll())};
2628 
2629   cl::opt<bool> PrintOptions{
2630       "print-options",
2631       cl::desc("Print non-default options after command line parsing"),
2632       cl::Hidden,
2633       cl::init(false),
2634       cl::cat(GenericCategory),
2635       cl::sub(SubCommand::getAll())};
2636 
2637   cl::opt<bool> PrintAllOptions{
2638       "print-all-options",
2639       cl::desc("Print all option values after command line parsing"),
2640       cl::Hidden,
2641       cl::init(false),
2642       cl::cat(GenericCategory),
2643       cl::sub(SubCommand::getAll())};
2644 
2645   VersionPrinterTy OverrideVersionPrinter = nullptr;
2646 
2647   std::vector<VersionPrinterTy> ExtraVersionPrinters;
2648 
2649   // Define the --version option that prints out the LLVM version for the tool
2650   VersionPrinter VersionPrinterInstance;
2651 
2652   cl::opt<VersionPrinter, true, parser<bool>> VersOp{
2653       "version", cl::desc("Display the version of this program"),
2654       cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2655       cl::cat(GenericCategory)};
2656 };
2657 } // End anonymous namespace
2658 
2659 // Lazy-initialized global instance of options controlling the command-line
2660 // parser and general handling.
2661 static ManagedStatic<CommandLineCommonOptions> CommonOptions;
2662 
2663 static void initCommonOptions() {
2664   *CommonOptions;
2665   initDebugCounterOptions();
2666   initGraphWriterOptions();
2667   initSignalsOptions();
2668   initStatisticOptions();
2669   initTimerOptions();
2670   initTypeSizeOptions();
2671   initWithColorOptions();
2672   initDebugOptions();
2673   initRandomSeedOptions();
2674 }
2675 
2676 OptionCategory &cl::getGeneralCategory() {
2677   // Initialise the general option category.
2678   static OptionCategory GeneralCategory{"General options"};
2679   return GeneralCategory;
2680 }
2681 
2682 void VersionPrinter::operator=(bool OptionWasSpecified) {
2683   if (!OptionWasSpecified)
2684     return;
2685 
2686   if (CommonOptions->OverrideVersionPrinter != nullptr) {
2687     CommonOptions->OverrideVersionPrinter(outs());
2688     exit(0);
2689   }
2690   print(CommonOptions->ExtraVersionPrinters);
2691 
2692   exit(0);
2693 }
2694 
2695 void HelpPrinterWrapper::operator=(bool Value) {
2696   if (!Value)
2697     return;
2698 
2699   // Decide which printer to invoke. If more than one option category is
2700   // registered then it is useful to show the categorized help instead of
2701   // uncategorized help.
2702   if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2703     // unhide --help-list option so user can have uncategorized output if they
2704     // want it.
2705     CommonOptions->HLOp.setHiddenFlag(NotHidden);
2706 
2707     CategorizedPrinter = true; // Invoke categorized printer
2708   } else
2709     UncategorizedPrinter = true; // Invoke uncategorized printer
2710 }
2711 
2712 // Print the value of each option.
2713 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2714 
2715 void CommandLineParser::printOptionValues() {
2716   if (!CommonOptions->PrintOptions && !CommonOptions->PrintAllOptions)
2717     return;
2718 
2719   SmallVector<std::pair<const char *, Option *>, 128> Opts;
2720   sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2721 
2722   // Compute the maximum argument length...
2723   size_t MaxArgLen = 0;
2724   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2725     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2726 
2727   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2728     Opts[i].second->printOptionValue(MaxArgLen, CommonOptions->PrintAllOptions);
2729 }
2730 
2731 // Utility function for printing the help message.
2732 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2733   if (!Hidden && !Categorized)
2734     CommonOptions->UncategorizedNormalPrinter.printHelp();
2735   else if (!Hidden && Categorized)
2736     CommonOptions->CategorizedNormalPrinter.printHelp();
2737   else if (Hidden && !Categorized)
2738     CommonOptions->UncategorizedHiddenPrinter.printHelp();
2739   else
2740     CommonOptions->CategorizedHiddenPrinter.printHelp();
2741 }
2742 
2743 /// Utility function for printing version number.
2744 void cl::PrintVersionMessage() {
2745   CommonOptions->VersionPrinterInstance.print(CommonOptions->ExtraVersionPrinters);
2746 }
2747 
2748 void cl::SetVersionPrinter(VersionPrinterTy func) {
2749   CommonOptions->OverrideVersionPrinter = func;
2750 }
2751 
2752 void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2753   CommonOptions->ExtraVersionPrinters.push_back(func);
2754 }
2755 
2756 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2757   initCommonOptions();
2758   auto &Subs = GlobalParser->RegisteredSubCommands;
2759   (void)Subs;
2760   assert(Subs.contains(&Sub));
2761   return Sub.OptionsMap;
2762 }
2763 
2764 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2765 cl::getRegisteredSubcommands() {
2766   return GlobalParser->getRegisteredSubcommands();
2767 }
2768 
2769 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2770   initCommonOptions();
2771   for (auto &I : Sub.OptionsMap) {
2772     bool Unrelated = true;
2773     for (auto &Cat : I.second->Categories) {
2774       if (Cat == &Category || Cat == &CommonOptions->GenericCategory)
2775         Unrelated = false;
2776     }
2777     if (Unrelated)
2778       I.second->setHiddenFlag(cl::ReallyHidden);
2779   }
2780 }
2781 
2782 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2783                               SubCommand &Sub) {
2784   initCommonOptions();
2785   for (auto &I : Sub.OptionsMap) {
2786     bool Unrelated = true;
2787     for (auto &Cat : I.second->Categories) {
2788       if (is_contained(Categories, Cat) ||
2789           Cat == &CommonOptions->GenericCategory)
2790         Unrelated = false;
2791     }
2792     if (Unrelated)
2793       I.second->setHiddenFlag(cl::ReallyHidden);
2794   }
2795 }
2796 
2797 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2798 void cl::ResetAllOptionOccurrences() {
2799   GlobalParser->ResetAllOptionOccurrences();
2800 }
2801 
2802 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2803                                  const char *Overview) {
2804   llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
2805                                     &llvm::nulls());
2806 }
2807