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