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