xref: /freebsd/contrib/llvm-project/llvm/lib/Support/CommandLine.cpp (revision d56accc7c3dcc897489b6a07834763a03b9f3d68)
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   switch (getNumOccurrencesFlag()) {
1741   case Optional:
1742     if (NumOccurrences > 1)
1743       return error("may only occur zero or one times!", ArgName);
1744     break;
1745   case Required:
1746     if (NumOccurrences > 1)
1747       return error("must occur exactly one time!", ArgName);
1748     LLVM_FALLTHROUGH;
1749   case OneOrMore:
1750   case ZeroOrMore:
1751   case ConsumeAfter:
1752     break;
1753   }
1754 
1755   return handleOccurrence(pos, ArgName, Value);
1756 }
1757 
1758 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1759 // has been specified yet.
1760 //
1761 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1762   if (O.ValueStr.empty())
1763     return DefaultMsg;
1764   return O.ValueStr;
1765 }
1766 
1767 //===----------------------------------------------------------------------===//
1768 // cl::alias class implementation
1769 //
1770 
1771 // Return the width of the option tag for printing...
1772 size_t alias::getOptionWidth() const {
1773   return argPlusPrefixesSize(ArgStr);
1774 }
1775 
1776 void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1777                           size_t FirstLineIndentedBy) {
1778   assert(Indent >= FirstLineIndentedBy);
1779   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1780   outs().indent(Indent - FirstLineIndentedBy)
1781       << ArgHelpPrefix << Split.first << "\n";
1782   while (!Split.second.empty()) {
1783     Split = Split.second.split('\n');
1784     outs().indent(Indent) << Split.first << "\n";
1785   }
1786 }
1787 
1788 void Option::printEnumValHelpStr(StringRef HelpStr, size_t BaseIndent,
1789                                  size_t FirstLineIndentedBy) {
1790   const StringRef ValHelpPrefix = "  ";
1791   assert(BaseIndent >= FirstLineIndentedBy);
1792   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1793   outs().indent(BaseIndent - FirstLineIndentedBy)
1794       << ArgHelpPrefix << ValHelpPrefix << Split.first << "\n";
1795   while (!Split.second.empty()) {
1796     Split = Split.second.split('\n');
1797     outs().indent(BaseIndent + ValHelpPrefix.size()) << Split.first << "\n";
1798   }
1799 }
1800 
1801 // Print out the option for the alias.
1802 void alias::printOptionInfo(size_t GlobalWidth) const {
1803   outs() << PrintArg(ArgStr);
1804   printHelpStr(HelpStr, GlobalWidth, argPlusPrefixesSize(ArgStr));
1805 }
1806 
1807 //===----------------------------------------------------------------------===//
1808 // Parser Implementation code...
1809 //
1810 
1811 // basic_parser implementation
1812 //
1813 
1814 // Return the width of the option tag for printing...
1815 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1816   size_t Len = argPlusPrefixesSize(O.ArgStr);
1817   auto ValName = getValueName();
1818   if (!ValName.empty()) {
1819     size_t FormattingLen = 3;
1820     if (O.getMiscFlags() & PositionalEatsArgs)
1821       FormattingLen = 6;
1822     Len += getValueStr(O, ValName).size() + FormattingLen;
1823   }
1824 
1825   return Len;
1826 }
1827 
1828 // printOptionInfo - Print out information about this option.  The
1829 // to-be-maintained width is specified.
1830 //
1831 void basic_parser_impl::printOptionInfo(const Option &O,
1832                                         size_t GlobalWidth) const {
1833   outs() << PrintArg(O.ArgStr);
1834 
1835   auto ValName = getValueName();
1836   if (!ValName.empty()) {
1837     if (O.getMiscFlags() & PositionalEatsArgs) {
1838       outs() << " <" << getValueStr(O, ValName) << ">...";
1839     } else if (O.getValueExpectedFlag() == ValueOptional)
1840       outs() << "[=<" << getValueStr(O, ValName) << ">]";
1841     else
1842       outs() << "=<" << getValueStr(O, ValName) << '>';
1843   }
1844 
1845   Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1846 }
1847 
1848 void basic_parser_impl::printOptionName(const Option &O,
1849                                         size_t GlobalWidth) const {
1850   outs() << PrintArg(O.ArgStr);
1851   outs().indent(GlobalWidth - O.ArgStr.size());
1852 }
1853 
1854 // parser<bool> implementation
1855 //
1856 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1857                          bool &Value) {
1858   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1859       Arg == "1") {
1860     Value = true;
1861     return false;
1862   }
1863 
1864   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1865     Value = false;
1866     return false;
1867   }
1868   return O.error("'" + Arg +
1869                  "' is invalid value for boolean argument! Try 0 or 1");
1870 }
1871 
1872 // parser<boolOrDefault> implementation
1873 //
1874 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1875                                   boolOrDefault &Value) {
1876   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1877       Arg == "1") {
1878     Value = BOU_TRUE;
1879     return false;
1880   }
1881   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1882     Value = BOU_FALSE;
1883     return false;
1884   }
1885 
1886   return O.error("'" + Arg +
1887                  "' is invalid value for boolean argument! Try 0 or 1");
1888 }
1889 
1890 // parser<int> implementation
1891 //
1892 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1893                         int &Value) {
1894   if (Arg.getAsInteger(0, Value))
1895     return O.error("'" + Arg + "' value invalid for integer argument!");
1896   return false;
1897 }
1898 
1899 // parser<long> implementation
1900 //
1901 bool parser<long>::parse(Option &O, StringRef ArgName, StringRef Arg,
1902                          long &Value) {
1903   if (Arg.getAsInteger(0, Value))
1904     return O.error("'" + Arg + "' value invalid for long argument!");
1905   return false;
1906 }
1907 
1908 // parser<long long> implementation
1909 //
1910 bool parser<long long>::parse(Option &O, StringRef ArgName, StringRef Arg,
1911                               long long &Value) {
1912   if (Arg.getAsInteger(0, Value))
1913     return O.error("'" + Arg + "' value invalid for llong argument!");
1914   return false;
1915 }
1916 
1917 // parser<unsigned> implementation
1918 //
1919 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1920                              unsigned &Value) {
1921 
1922   if (Arg.getAsInteger(0, Value))
1923     return O.error("'" + Arg + "' value invalid for uint argument!");
1924   return false;
1925 }
1926 
1927 // parser<unsigned long> implementation
1928 //
1929 bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
1930                                   unsigned long &Value) {
1931 
1932   if (Arg.getAsInteger(0, Value))
1933     return O.error("'" + Arg + "' value invalid for ulong argument!");
1934   return false;
1935 }
1936 
1937 // parser<unsigned long long> implementation
1938 //
1939 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1940                                        StringRef Arg,
1941                                        unsigned long long &Value) {
1942 
1943   if (Arg.getAsInteger(0, Value))
1944     return O.error("'" + Arg + "' value invalid for ullong argument!");
1945   return false;
1946 }
1947 
1948 // parser<double>/parser<float> implementation
1949 //
1950 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1951   if (to_float(Arg, Value))
1952     return false;
1953   return O.error("'" + Arg + "' value invalid for floating point argument!");
1954 }
1955 
1956 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1957                            double &Val) {
1958   return parseDouble(O, Arg, Val);
1959 }
1960 
1961 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1962                           float &Val) {
1963   double dVal;
1964   if (parseDouble(O, Arg, dVal))
1965     return true;
1966   Val = (float)dVal;
1967   return false;
1968 }
1969 
1970 // generic_parser_base implementation
1971 //
1972 
1973 // findOption - Return the option number corresponding to the specified
1974 // argument string.  If the option is not found, getNumOptions() is returned.
1975 //
1976 unsigned generic_parser_base::findOption(StringRef Name) {
1977   unsigned e = getNumOptions();
1978 
1979   for (unsigned i = 0; i != e; ++i) {
1980     if (getOption(i) == Name)
1981       return i;
1982   }
1983   return e;
1984 }
1985 
1986 static StringRef EqValue = "=<value>";
1987 static StringRef EmptyOption = "<empty>";
1988 static StringRef OptionPrefix = "    =";
1989 static size_t getOptionPrefixesSize() {
1990   return OptionPrefix.size() + ArgHelpPrefix.size();
1991 }
1992 
1993 static bool shouldPrintOption(StringRef Name, StringRef Description,
1994                               const Option &O) {
1995   return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
1996          !Description.empty();
1997 }
1998 
1999 // Return the width of the option tag for printing...
2000 size_t generic_parser_base::getOptionWidth(const Option &O) const {
2001   if (O.hasArgStr()) {
2002     size_t Size =
2003         argPlusPrefixesSize(O.ArgStr) + EqValue.size();
2004     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2005       StringRef Name = getOption(i);
2006       if (!shouldPrintOption(Name, getDescription(i), O))
2007         continue;
2008       size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
2009       Size = std::max(Size, NameSize + getOptionPrefixesSize());
2010     }
2011     return Size;
2012   } else {
2013     size_t BaseSize = 0;
2014     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
2015       BaseSize = std::max(BaseSize, getOption(i).size() + 8);
2016     return BaseSize;
2017   }
2018 }
2019 
2020 // printOptionInfo - Print out information about this option.  The
2021 // to-be-maintained width is specified.
2022 //
2023 void generic_parser_base::printOptionInfo(const Option &O,
2024                                           size_t GlobalWidth) const {
2025   if (O.hasArgStr()) {
2026     // When the value is optional, first print a line just describing the
2027     // option without values.
2028     if (O.getValueExpectedFlag() == ValueOptional) {
2029       for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2030         if (getOption(i).empty()) {
2031           outs() << PrintArg(O.ArgStr);
2032           Option::printHelpStr(O.HelpStr, GlobalWidth,
2033                                argPlusPrefixesSize(O.ArgStr));
2034           break;
2035         }
2036       }
2037     }
2038 
2039     outs() << PrintArg(O.ArgStr) << EqValue;
2040     Option::printHelpStr(O.HelpStr, GlobalWidth,
2041                          EqValue.size() +
2042                              argPlusPrefixesSize(O.ArgStr));
2043     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2044       StringRef OptionName = getOption(i);
2045       StringRef Description = getDescription(i);
2046       if (!shouldPrintOption(OptionName, Description, O))
2047         continue;
2048       size_t FirstLineIndent = OptionName.size() + getOptionPrefixesSize();
2049       outs() << OptionPrefix << OptionName;
2050       if (OptionName.empty()) {
2051         outs() << EmptyOption;
2052         assert(FirstLineIndent >= EmptyOption.size());
2053         FirstLineIndent += EmptyOption.size();
2054       }
2055       if (!Description.empty())
2056         Option::printEnumValHelpStr(Description, GlobalWidth, FirstLineIndent);
2057       else
2058         outs() << '\n';
2059     }
2060   } else {
2061     if (!O.HelpStr.empty())
2062       outs() << "  " << O.HelpStr << '\n';
2063     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2064       StringRef Option = getOption(i);
2065       outs() << "    " << PrintArg(Option);
2066       Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
2067     }
2068   }
2069 }
2070 
2071 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
2072 
2073 // printGenericOptionDiff - Print the value of this option and it's default.
2074 //
2075 // "Generic" options have each value mapped to a name.
2076 void generic_parser_base::printGenericOptionDiff(
2077     const Option &O, const GenericOptionValue &Value,
2078     const GenericOptionValue &Default, size_t GlobalWidth) const {
2079   outs() << "  " << PrintArg(O.ArgStr);
2080   outs().indent(GlobalWidth - O.ArgStr.size());
2081 
2082   unsigned NumOpts = getNumOptions();
2083   for (unsigned i = 0; i != NumOpts; ++i) {
2084     if (Value.compare(getOptionValue(i)))
2085       continue;
2086 
2087     outs() << "= " << getOption(i);
2088     size_t L = getOption(i).size();
2089     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
2090     outs().indent(NumSpaces) << " (default: ";
2091     for (unsigned j = 0; j != NumOpts; ++j) {
2092       if (Default.compare(getOptionValue(j)))
2093         continue;
2094       outs() << getOption(j);
2095       break;
2096     }
2097     outs() << ")\n";
2098     return;
2099   }
2100   outs() << "= *unknown option value*\n";
2101 }
2102 
2103 // printOptionDiff - Specializations for printing basic value types.
2104 //
2105 #define PRINT_OPT_DIFF(T)                                                      \
2106   void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
2107                                   size_t GlobalWidth) const {                  \
2108     printOptionName(O, GlobalWidth);                                           \
2109     std::string Str;                                                           \
2110     {                                                                          \
2111       raw_string_ostream SS(Str);                                              \
2112       SS << V;                                                                 \
2113     }                                                                          \
2114     outs() << "= " << Str;                                                     \
2115     size_t NumSpaces =                                                         \
2116         MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
2117     outs().indent(NumSpaces) << " (default: ";                                 \
2118     if (D.hasValue())                                                          \
2119       outs() << D.getValue();                                                  \
2120     else                                                                       \
2121       outs() << "*no default*";                                                \
2122     outs() << ")\n";                                                           \
2123   }
2124 
2125 PRINT_OPT_DIFF(bool)
2126 PRINT_OPT_DIFF(boolOrDefault)
2127 PRINT_OPT_DIFF(int)
2128 PRINT_OPT_DIFF(long)
2129 PRINT_OPT_DIFF(long long)
2130 PRINT_OPT_DIFF(unsigned)
2131 PRINT_OPT_DIFF(unsigned long)
2132 PRINT_OPT_DIFF(unsigned long long)
2133 PRINT_OPT_DIFF(double)
2134 PRINT_OPT_DIFF(float)
2135 PRINT_OPT_DIFF(char)
2136 
2137 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
2138                                           const OptionValue<std::string> &D,
2139                                           size_t GlobalWidth) const {
2140   printOptionName(O, GlobalWidth);
2141   outs() << "= " << V;
2142   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
2143   outs().indent(NumSpaces) << " (default: ";
2144   if (D.hasValue())
2145     outs() << D.getValue();
2146   else
2147     outs() << "*no default*";
2148   outs() << ")\n";
2149 }
2150 
2151 // Print a placeholder for options that don't yet support printOptionDiff().
2152 void basic_parser_impl::printOptionNoValue(const Option &O,
2153                                            size_t GlobalWidth) const {
2154   printOptionName(O, GlobalWidth);
2155   outs() << "= *cannot print option value*\n";
2156 }
2157 
2158 //===----------------------------------------------------------------------===//
2159 // -help and -help-hidden option implementation
2160 //
2161 
2162 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
2163                           const std::pair<const char *, Option *> *RHS) {
2164   return strcmp(LHS->first, RHS->first);
2165 }
2166 
2167 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
2168                           const std::pair<const char *, SubCommand *> *RHS) {
2169   return strcmp(LHS->first, RHS->first);
2170 }
2171 
2172 // Copy Options into a vector so we can sort them as we like.
2173 static void sortOpts(StringMap<Option *> &OptMap,
2174                      SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
2175                      bool ShowHidden) {
2176   SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
2177 
2178   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
2179        I != E; ++I) {
2180     // Ignore really-hidden options.
2181     if (I->second->getOptionHiddenFlag() == ReallyHidden)
2182       continue;
2183 
2184     // Unless showhidden is set, ignore hidden flags.
2185     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
2186       continue;
2187 
2188     // If we've already seen this option, don't add it to the list again.
2189     if (!OptionSet.insert(I->second).second)
2190       continue;
2191 
2192     Opts.push_back(
2193         std::pair<const char *, Option *>(I->getKey().data(), I->second));
2194   }
2195 
2196   // Sort the options list alphabetically.
2197   array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
2198 }
2199 
2200 static void
2201 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
2202                 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
2203   for (auto *S : SubMap) {
2204     if (S->getName().empty())
2205       continue;
2206     Subs.push_back(std::make_pair(S->getName().data(), S));
2207   }
2208   array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
2209 }
2210 
2211 namespace {
2212 
2213 class HelpPrinter {
2214 protected:
2215   const bool ShowHidden;
2216   typedef SmallVector<std::pair<const char *, Option *>, 128>
2217       StrOptionPairVector;
2218   typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
2219       StrSubCommandPairVector;
2220   // Print the options. Opts is assumed to be alphabetically sorted.
2221   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
2222     for (size_t i = 0, e = Opts.size(); i != e; ++i)
2223       Opts[i].second->printOptionInfo(MaxArgLen);
2224   }
2225 
2226   void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
2227     for (const auto &S : Subs) {
2228       outs() << "  " << S.first;
2229       if (!S.second->getDescription().empty()) {
2230         outs().indent(MaxSubLen - strlen(S.first));
2231         outs() << " - " << S.second->getDescription();
2232       }
2233       outs() << "\n";
2234     }
2235   }
2236 
2237 public:
2238   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
2239   virtual ~HelpPrinter() {}
2240 
2241   // Invoke the printer.
2242   void operator=(bool Value) {
2243     if (!Value)
2244       return;
2245     printHelp();
2246 
2247     // Halt the program since help information was printed
2248     exit(0);
2249   }
2250 
2251   void printHelp() {
2252     SubCommand *Sub = GlobalParser->getActiveSubCommand();
2253     auto &OptionsMap = Sub->OptionsMap;
2254     auto &PositionalOpts = Sub->PositionalOpts;
2255     auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
2256 
2257     StrOptionPairVector Opts;
2258     sortOpts(OptionsMap, Opts, ShowHidden);
2259 
2260     StrSubCommandPairVector Subs;
2261     sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
2262 
2263     if (!GlobalParser->ProgramOverview.empty())
2264       outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
2265 
2266     if (Sub == &*TopLevelSubCommand) {
2267       outs() << "USAGE: " << GlobalParser->ProgramName;
2268       if (Subs.size() > 2)
2269         outs() << " [subcommand]";
2270       outs() << " [options]";
2271     } else {
2272       if (!Sub->getDescription().empty()) {
2273         outs() << "SUBCOMMAND '" << Sub->getName()
2274                << "': " << Sub->getDescription() << "\n\n";
2275       }
2276       outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
2277              << " [options]";
2278     }
2279 
2280     for (auto *Opt : PositionalOpts) {
2281       if (Opt->hasArgStr())
2282         outs() << " --" << Opt->ArgStr;
2283       outs() << " " << Opt->HelpStr;
2284     }
2285 
2286     // Print the consume after option info if it exists...
2287     if (ConsumeAfterOpt)
2288       outs() << " " << ConsumeAfterOpt->HelpStr;
2289 
2290     if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
2291       // Compute the maximum subcommand length...
2292       size_t MaxSubLen = 0;
2293       for (size_t i = 0, e = Subs.size(); i != e; ++i)
2294         MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
2295 
2296       outs() << "\n\n";
2297       outs() << "SUBCOMMANDS:\n\n";
2298       printSubCommands(Subs, MaxSubLen);
2299       outs() << "\n";
2300       outs() << "  Type \"" << GlobalParser->ProgramName
2301              << " <subcommand> --help\" to get more help on a specific "
2302                 "subcommand";
2303     }
2304 
2305     outs() << "\n\n";
2306 
2307     // Compute the maximum argument length...
2308     size_t MaxArgLen = 0;
2309     for (size_t i = 0, e = Opts.size(); i != e; ++i)
2310       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2311 
2312     outs() << "OPTIONS:\n";
2313     printOptions(Opts, MaxArgLen);
2314 
2315     // Print any extra help the user has declared.
2316     for (const auto &I : GlobalParser->MoreHelp)
2317       outs() << I;
2318     GlobalParser->MoreHelp.clear();
2319   }
2320 };
2321 
2322 class CategorizedHelpPrinter : public HelpPrinter {
2323 public:
2324   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
2325 
2326   // Helper function for printOptions().
2327   // It shall return a negative value if A's name should be lexicographically
2328   // ordered before B's name. It returns a value greater than zero if B's name
2329   // should be ordered before A's name, and it returns 0 otherwise.
2330   static int OptionCategoryCompare(OptionCategory *const *A,
2331                                    OptionCategory *const *B) {
2332     return (*A)->getName().compare((*B)->getName());
2333   }
2334 
2335   // Make sure we inherit our base class's operator=()
2336   using HelpPrinter::operator=;
2337 
2338 protected:
2339   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
2340     std::vector<OptionCategory *> SortedCategories;
2341     DenseMap<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2342 
2343     // Collect registered option categories into vector in preparation for
2344     // sorting.
2345     for (OptionCategory *Category : GlobalParser->RegisteredOptionCategories)
2346       SortedCategories.push_back(Category);
2347 
2348     // Sort the different option categories alphabetically.
2349     assert(SortedCategories.size() > 0 && "No option categories registered!");
2350     array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
2351                    OptionCategoryCompare);
2352 
2353     // Walk through pre-sorted options and assign into categories.
2354     // Because the options are already alphabetically sorted the
2355     // options within categories will also be alphabetically sorted.
2356     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
2357       Option *Opt = Opts[I].second;
2358       for (auto &Cat : Opt->Categories) {
2359         assert(find(SortedCategories, Cat) != SortedCategories.end() &&
2360                "Option has an unregistered category");
2361         CategorizedOptions[Cat].push_back(Opt);
2362       }
2363     }
2364 
2365     // Now do printing.
2366     for (OptionCategory *Category : SortedCategories) {
2367       // Hide empty categories for --help, but show for --help-hidden.
2368       const auto &CategoryOptions = CategorizedOptions[Category];
2369       bool IsEmptyCategory = CategoryOptions.empty();
2370       if (!ShowHidden && IsEmptyCategory)
2371         continue;
2372 
2373       // Print category information.
2374       outs() << "\n";
2375       outs() << Category->getName() << ":\n";
2376 
2377       // Check if description is set.
2378       if (!Category->getDescription().empty())
2379         outs() << Category->getDescription() << "\n\n";
2380       else
2381         outs() << "\n";
2382 
2383       // When using --help-hidden explicitly state if the category has no
2384       // options associated with it.
2385       if (IsEmptyCategory) {
2386         outs() << "  This option category has no options.\n";
2387         continue;
2388       }
2389       // Loop over the options in the category and print.
2390       for (const Option *Opt : CategoryOptions)
2391         Opt->printOptionInfo(MaxArgLen);
2392     }
2393   }
2394 };
2395 
2396 // This wraps the Uncategorizing and Categorizing printers and decides
2397 // at run time which should be invoked.
2398 class HelpPrinterWrapper {
2399 private:
2400   HelpPrinter &UncategorizedPrinter;
2401   CategorizedHelpPrinter &CategorizedPrinter;
2402 
2403 public:
2404   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2405                               CategorizedHelpPrinter &CategorizedPrinter)
2406       : UncategorizedPrinter(UncategorizedPrinter),
2407         CategorizedPrinter(CategorizedPrinter) {}
2408 
2409   // Invoke the printer.
2410   void operator=(bool Value);
2411 };
2412 
2413 } // End anonymous namespace
2414 
2415 #if defined(__GNUC__)
2416 // GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are
2417 // enabled.
2418 # if defined(__OPTIMIZE__)
2419 #  define LLVM_IS_DEBUG_BUILD 0
2420 # else
2421 #  define LLVM_IS_DEBUG_BUILD 1
2422 # endif
2423 #elif defined(_MSC_VER)
2424 // MSVC doesn't have a predefined macro indicating if optimizations are enabled.
2425 // Use _DEBUG instead. This macro actually corresponds to the choice between
2426 // debug and release CRTs, but it is a reasonable proxy.
2427 # if defined(_DEBUG)
2428 #  define LLVM_IS_DEBUG_BUILD 1
2429 # else
2430 #  define LLVM_IS_DEBUG_BUILD 0
2431 # endif
2432 #else
2433 // Otherwise, for an unknown compiler, assume this is an optimized build.
2434 # define LLVM_IS_DEBUG_BUILD 0
2435 #endif
2436 
2437 namespace {
2438 class VersionPrinter {
2439 public:
2440   void print() {
2441     raw_ostream &OS = outs();
2442 #ifdef PACKAGE_VENDOR
2443     OS << PACKAGE_VENDOR << " ";
2444 #else
2445     OS << "LLVM (http://llvm.org/):\n  ";
2446 #endif
2447     OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2448 #ifdef LLVM_VERSION_INFO
2449     OS << " " << LLVM_VERSION_INFO;
2450 #endif
2451     OS << "\n  ";
2452 #if LLVM_IS_DEBUG_BUILD
2453     OS << "DEBUG build";
2454 #else
2455     OS << "Optimized build";
2456 #endif
2457 #ifndef NDEBUG
2458     OS << " with assertions";
2459 #endif
2460 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
2461     std::string CPU = std::string(sys::getHostCPUName());
2462     if (CPU == "generic")
2463       CPU = "(unknown)";
2464     OS << ".\n"
2465        << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
2466        << "  Host CPU: " << CPU;
2467 #endif
2468     OS << '\n';
2469   }
2470   void operator=(bool OptionWasSpecified);
2471 };
2472 
2473 struct CommandLineCommonOptions {
2474   // Declare the four HelpPrinter instances that are used to print out help, or
2475   // help-hidden as an uncategorized list or in categories.
2476   HelpPrinter UncategorizedNormalPrinter{false};
2477   HelpPrinter UncategorizedHiddenPrinter{true};
2478   CategorizedHelpPrinter CategorizedNormalPrinter{false};
2479   CategorizedHelpPrinter CategorizedHiddenPrinter{true};
2480   // Declare HelpPrinter wrappers that will decide whether or not to invoke
2481   // a categorizing help printer
2482   HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
2483                                           CategorizedNormalPrinter};
2484   HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
2485                                           CategorizedHiddenPrinter};
2486   // Define a category for generic options that all tools should have.
2487   cl::OptionCategory GenericCategory{"Generic Options"};
2488 
2489   // Define uncategorized help printers.
2490   // --help-list is hidden by default because if Option categories are being
2491   // used then --help behaves the same as --help-list.
2492   cl::opt<HelpPrinter, true, parser<bool>> HLOp{
2493       "help-list",
2494       cl::desc(
2495           "Display list of available options (--help-list-hidden for more)"),
2496       cl::location(UncategorizedNormalPrinter),
2497       cl::Hidden,
2498       cl::ValueDisallowed,
2499       cl::cat(GenericCategory),
2500       cl::sub(*AllSubCommands)};
2501 
2502   cl::opt<HelpPrinter, true, parser<bool>> HLHOp{
2503       "help-list-hidden",
2504       cl::desc("Display list of all available options"),
2505       cl::location(UncategorizedHiddenPrinter),
2506       cl::Hidden,
2507       cl::ValueDisallowed,
2508       cl::cat(GenericCategory),
2509       cl::sub(*AllSubCommands)};
2510 
2511   // Define uncategorized/categorized help printers. These printers change their
2512   // behaviour at runtime depending on whether one or more Option categories
2513   // have been declared.
2514   cl::opt<HelpPrinterWrapper, true, parser<bool>> HOp{
2515       "help",
2516       cl::desc("Display available options (--help-hidden for more)"),
2517       cl::location(WrappedNormalPrinter),
2518       cl::ValueDisallowed,
2519       cl::cat(GenericCategory),
2520       cl::sub(*AllSubCommands)};
2521 
2522   cl::alias HOpA{"h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
2523                  cl::DefaultOption};
2524 
2525   cl::opt<HelpPrinterWrapper, true, parser<bool>> HHOp{
2526       "help-hidden",
2527       cl::desc("Display all available options"),
2528       cl::location(WrappedHiddenPrinter),
2529       cl::Hidden,
2530       cl::ValueDisallowed,
2531       cl::cat(GenericCategory),
2532       cl::sub(*AllSubCommands)};
2533 
2534   cl::opt<bool> PrintOptions{
2535       "print-options",
2536       cl::desc("Print non-default options after command line parsing"),
2537       cl::Hidden,
2538       cl::init(false),
2539       cl::cat(GenericCategory),
2540       cl::sub(*AllSubCommands)};
2541 
2542   cl::opt<bool> PrintAllOptions{
2543       "print-all-options",
2544       cl::desc("Print all option values after command line parsing"),
2545       cl::Hidden,
2546       cl::init(false),
2547       cl::cat(GenericCategory),
2548       cl::sub(*AllSubCommands)};
2549 
2550   VersionPrinterTy OverrideVersionPrinter = nullptr;
2551 
2552   std::vector<VersionPrinterTy> ExtraVersionPrinters;
2553 
2554   // Define the --version option that prints out the LLVM version for the tool
2555   VersionPrinter VersionPrinterInstance;
2556 
2557   cl::opt<VersionPrinter, true, parser<bool>> VersOp{
2558       "version", cl::desc("Display the version of this program"),
2559       cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2560       cl::cat(GenericCategory)};
2561 };
2562 } // End anonymous namespace
2563 
2564 // Lazy-initialized global instance of options controlling the command-line
2565 // parser and general handling.
2566 static ManagedStatic<CommandLineCommonOptions> CommonOptions;
2567 
2568 static void initCommonOptions() {
2569   *CommonOptions;
2570   initDebugCounterOptions();
2571   initGraphWriterOptions();
2572   initSignalsOptions();
2573   initStatisticOptions();
2574   initTimerOptions();
2575   initTypeSizeOptions();
2576   initWithColorOptions();
2577   initDebugOptions();
2578   initRandomSeedOptions();
2579 }
2580 
2581 OptionCategory &cl::getGeneralCategory() {
2582   // Initialise the general option category.
2583   static OptionCategory GeneralCategory{"General options"};
2584   return GeneralCategory;
2585 }
2586 
2587 void VersionPrinter::operator=(bool OptionWasSpecified) {
2588   if (!OptionWasSpecified)
2589     return;
2590 
2591   if (CommonOptions->OverrideVersionPrinter != nullptr) {
2592     CommonOptions->OverrideVersionPrinter(outs());
2593     exit(0);
2594   }
2595   print();
2596 
2597   // Iterate over any registered extra printers and call them to add further
2598   // information.
2599   if (!CommonOptions->ExtraVersionPrinters.empty()) {
2600     outs() << '\n';
2601     for (const auto &I : CommonOptions->ExtraVersionPrinters)
2602       I(outs());
2603   }
2604 
2605   exit(0);
2606 }
2607 
2608 void HelpPrinterWrapper::operator=(bool Value) {
2609   if (!Value)
2610     return;
2611 
2612   // Decide which printer to invoke. If more than one option category is
2613   // registered then it is useful to show the categorized help instead of
2614   // uncategorized help.
2615   if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2616     // unhide --help-list option so user can have uncategorized output if they
2617     // want it.
2618     CommonOptions->HLOp.setHiddenFlag(NotHidden);
2619 
2620     CategorizedPrinter = true; // Invoke categorized printer
2621   } else
2622     UncategorizedPrinter = true; // Invoke uncategorized printer
2623 }
2624 
2625 // Print the value of each option.
2626 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2627 
2628 void CommandLineParser::printOptionValues() {
2629   if (!CommonOptions->PrintOptions && !CommonOptions->PrintAllOptions)
2630     return;
2631 
2632   SmallVector<std::pair<const char *, Option *>, 128> Opts;
2633   sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2634 
2635   // Compute the maximum argument length...
2636   size_t MaxArgLen = 0;
2637   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2638     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2639 
2640   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2641     Opts[i].second->printOptionValue(MaxArgLen, CommonOptions->PrintAllOptions);
2642 }
2643 
2644 // Utility function for printing the help message.
2645 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2646   if (!Hidden && !Categorized)
2647     CommonOptions->UncategorizedNormalPrinter.printHelp();
2648   else if (!Hidden && Categorized)
2649     CommonOptions->CategorizedNormalPrinter.printHelp();
2650   else if (Hidden && !Categorized)
2651     CommonOptions->UncategorizedHiddenPrinter.printHelp();
2652   else
2653     CommonOptions->CategorizedHiddenPrinter.printHelp();
2654 }
2655 
2656 /// Utility function for printing version number.
2657 void cl::PrintVersionMessage() {
2658   CommonOptions->VersionPrinterInstance.print();
2659 }
2660 
2661 void cl::SetVersionPrinter(VersionPrinterTy func) {
2662   CommonOptions->OverrideVersionPrinter = func;
2663 }
2664 
2665 void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2666   CommonOptions->ExtraVersionPrinters.push_back(func);
2667 }
2668 
2669 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2670   initCommonOptions();
2671   auto &Subs = GlobalParser->RegisteredSubCommands;
2672   (void)Subs;
2673   assert(is_contained(Subs, &Sub));
2674   return Sub.OptionsMap;
2675 }
2676 
2677 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2678 cl::getRegisteredSubcommands() {
2679   return GlobalParser->getRegisteredSubcommands();
2680 }
2681 
2682 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2683   initCommonOptions();
2684   for (auto &I : Sub.OptionsMap) {
2685     bool Unrelated = true;
2686     for (auto &Cat : I.second->Categories) {
2687       if (Cat == &Category || Cat == &CommonOptions->GenericCategory)
2688         Unrelated = false;
2689     }
2690     if (Unrelated)
2691       I.second->setHiddenFlag(cl::ReallyHidden);
2692   }
2693 }
2694 
2695 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2696                               SubCommand &Sub) {
2697   initCommonOptions();
2698   for (auto &I : Sub.OptionsMap) {
2699     bool Unrelated = true;
2700     for (auto &Cat : I.second->Categories) {
2701       if (is_contained(Categories, Cat) ||
2702           Cat == &CommonOptions->GenericCategory)
2703         Unrelated = false;
2704     }
2705     if (Unrelated)
2706       I.second->setHiddenFlag(cl::ReallyHidden);
2707   }
2708 }
2709 
2710 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2711 void cl::ResetAllOptionOccurrences() {
2712   GlobalParser->ResetAllOptionOccurrences();
2713 }
2714 
2715 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2716                                  const char *Overview) {
2717   llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
2718                                     &llvm::nulls());
2719 }
2720