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