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