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