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