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