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