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